View Javadoc

1   /**
2    *
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *     http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing, software
14   * distributed under the License is distributed on an "AS IS" BASIS,
15   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16   * See the License for the specific language governing permissions and
17   * limitations under the License.
18   */
19  package org.apache.hadoop.hbase.mapreduce;
20  
21  import java.io.File;
22  import java.io.IOException;
23  import java.lang.reflect.InvocationTargetException;
24  import java.lang.reflect.Method;
25  import java.net.URL;
26  import java.net.URLDecoder;
27  import java.util.ArrayList;
28  import java.util.Enumeration;
29  import java.util.HashMap;
30  import java.util.HashSet;
31  import java.util.List;
32  import java.util.Map;
33  import java.util.Set;
34  import java.util.zip.ZipEntry;
35  import java.util.zip.ZipFile;
36  
37  import org.apache.commons.logging.Log;
38  import org.apache.commons.logging.LogFactory;
39  import org.apache.hadoop.classification.InterfaceAudience;
40  import org.apache.hadoop.classification.InterfaceStability;
41  import org.apache.hadoop.conf.Configuration;
42  import org.apache.hadoop.fs.FileSystem;
43  import org.apache.hadoop.fs.Path;
44  import org.apache.hadoop.hbase.HBaseConfiguration;
45  import org.apache.hadoop.hbase.catalog.MetaReader;
46  import org.apache.hadoop.hbase.client.Put;
47  import org.apache.hadoop.hbase.client.Scan;
48  import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
49  import org.apache.hadoop.hbase.mapreduce.hadoopbackport.JarFinder;
50  import org.apache.hadoop.hbase.protobuf.ProtobufUtil;
51  import org.apache.hadoop.hbase.protobuf.generated.ClientProtos;
52  import org.apache.hadoop.hbase.security.User;
53  import org.apache.hadoop.hbase.security.UserProvider;
54  import org.apache.hadoop.hbase.security.token.AuthenticationTokenIdentifier;
55  import org.apache.hadoop.hbase.security.token.AuthenticationTokenSelector;
56  import org.apache.hadoop.hbase.util.Base64;
57  import org.apache.hadoop.hbase.util.Bytes;
58  import org.apache.hadoop.hbase.zookeeper.ZKClusterId;
59  import org.apache.hadoop.hbase.zookeeper.ZKUtil;
60  import org.apache.hadoop.hbase.zookeeper.ZooKeeperWatcher;
61  import org.apache.hadoop.io.Text;
62  import org.apache.hadoop.io.Writable;
63  import org.apache.hadoop.io.WritableComparable;
64  import org.apache.hadoop.mapreduce.InputFormat;
65  import org.apache.hadoop.mapreduce.Job;
66  import org.apache.hadoop.security.token.Token;
67  import org.apache.hadoop.util.StringUtils;
68  import org.apache.zookeeper.KeeperException;
69  import org.cliffc.high_scale_lib.Counter;
70  
71  import com.google.protobuf.InvalidProtocolBufferException;
72  
73  /**
74   * Utility for {@link TableMapper} and {@link TableReducer}
75   */
76  @SuppressWarnings({ "rawtypes", "unchecked" })
77  @InterfaceAudience.Public
78  @InterfaceStability.Stable
79  public class TableMapReduceUtil {
80    static Log LOG = LogFactory.getLog(TableMapReduceUtil.class);
81  
82    /**
83     * Use this before submitting a TableMap job. It will appropriately set up
84     * the job.
85     *
86     * @param table  The table name to read from.
87     * @param scan  The scan instance with the columns, time range etc.
88     * @param mapper  The mapper class to use.
89     * @param outputKeyClass  The class of the output key.
90     * @param outputValueClass  The class of the output value.
91     * @param job  The current job to adjust.  Make sure the passed job is
92     * carrying all necessary HBase configuration.
93     * @throws IOException When setting up the details fails.
94     */
95    public static void initTableMapperJob(String table, Scan scan,
96        Class<? extends TableMapper> mapper,
97        Class<?> outputKeyClass,
98        Class<?> outputValueClass, Job job)
99    throws IOException {
100     initTableMapperJob(table, scan, mapper, outputKeyClass, outputValueClass,
101         job, true);
102   }
103 
104   /**
105    * Use this before submitting a TableMap job. It will appropriately set up
106    * the job.
107    *
108    * @param table Binary representation of the table name to read from.
109    * @param scan  The scan instance with the columns, time range etc.
110    * @param mapper  The mapper class to use.
111    * @param outputKeyClass  The class of the output key.
112    * @param outputValueClass  The class of the output value.
113    * @param job  The current job to adjust.  Make sure the passed job is
114    * carrying all necessary HBase configuration.
115    * @throws IOException When setting up the details fails.
116    */
117    public static void initTableMapperJob(byte[] table, Scan scan,
118       Class<? extends TableMapper> mapper,
119       Class<?> outputKeyClass,
120       Class<?> outputValueClass, Job job)
121   throws IOException {
122       initTableMapperJob(Bytes.toString(table), scan, mapper, outputKeyClass, outputValueClass,
123               job, true);
124   }
125 
126    /**
127     * Use this before submitting a TableMap job. It will appropriately set up
128     * the job.
129     *
130     * @param table  The table name to read from.
131     * @param scan  The scan instance with the columns, time range etc.
132     * @param mapper  The mapper class to use.
133     * @param outputKeyClass  The class of the output key.
134     * @param outputValueClass  The class of the output value.
135     * @param job  The current job to adjust.  Make sure the passed job is
136     * carrying all necessary HBase configuration.
137     * @param addDependencyJars upload HBase jars and jars for any of the configured
138     *           job classes via the distributed cache (tmpjars).
139     * @throws IOException When setting up the details fails.
140     */
141    public static void initTableMapperJob(String table, Scan scan,
142        Class<? extends TableMapper> mapper,
143        Class<?> outputKeyClass,
144        Class<?> outputValueClass, Job job,
145        boolean addDependencyJars, Class<? extends InputFormat> inputFormatClass)
146    throws IOException {
147      initTableMapperJob(table, scan, mapper, outputKeyClass, outputValueClass, job,
148          addDependencyJars, true, inputFormatClass);
149    }
150 
151 
152   /**
153    * Use this before submitting a TableMap job. It will appropriately set up
154    * the job.
155    *
156    * @param table  The table name to read from.
157    * @param scan  The scan instance with the columns, time range etc.
158    * @param mapper  The mapper class to use.
159    * @param outputKeyClass  The class of the output key.
160    * @param outputValueClass  The class of the output value.
161    * @param job  The current job to adjust.  Make sure the passed job is
162    * carrying all necessary HBase configuration.
163    * @param addDependencyJars upload HBase jars and jars for any of the configured
164    *           job classes via the distributed cache (tmpjars).
165    * @param initCredentials whether to initialize hbase auth credentials for the job
166    * @param inputFormatClass the input format
167    * @throws IOException When setting up the details fails.
168    */
169   public static void initTableMapperJob(String table, Scan scan,
170       Class<? extends TableMapper> mapper,
171       Class<?> outputKeyClass,
172       Class<?> outputValueClass, Job job,
173       boolean addDependencyJars, boolean initCredentials,
174       Class<? extends InputFormat> inputFormatClass)
175   throws IOException {
176     job.setInputFormatClass(inputFormatClass);
177     if (outputValueClass != null) job.setMapOutputValueClass(outputValueClass);
178     if (outputKeyClass != null) job.setMapOutputKeyClass(outputKeyClass);
179     job.setMapperClass(mapper);
180     if (Put.class.equals(outputValueClass)) {
181       job.setCombinerClass(PutCombiner.class);
182     }
183     Configuration conf = job.getConfiguration();
184     HBaseConfiguration.merge(conf, HBaseConfiguration.create(conf));
185     conf.set(TableInputFormat.INPUT_TABLE, table);
186     conf.set(TableInputFormat.SCAN, convertScanToString(scan));
187     conf.setStrings("io.serializations", conf.get("io.serializations"),
188         MutationSerialization.class.getName(), ResultSerialization.class.getName(),
189         KeyValueSerialization.class.getName());
190     if (addDependencyJars) {
191       addDependencyJars(job);
192     }
193     if (initCredentials) {
194       initCredentials(job);
195     }
196   }
197 
198   /**
199    * Use this before submitting a TableMap job. It will appropriately set up
200    * the job.
201    *
202    * @param table Binary representation of the table name to read from.
203    * @param scan  The scan instance with the columns, time range etc.
204    * @param mapper  The mapper class to use.
205    * @param outputKeyClass  The class of the output key.
206    * @param outputValueClass  The class of the output value.
207    * @param job  The current job to adjust.  Make sure the passed job is
208    * carrying all necessary HBase configuration.
209    * @param addDependencyJars upload HBase jars and jars for any of the configured
210    *           job classes via the distributed cache (tmpjars).
211    * @param inputFormatClass The class of the input format
212    * @throws IOException When setting up the details fails.
213    */
214   public static void initTableMapperJob(byte[] table, Scan scan,
215       Class<? extends TableMapper> mapper,
216       Class<?> outputKeyClass,
217       Class<?> outputValueClass, Job job,
218       boolean addDependencyJars, Class<? extends InputFormat> inputFormatClass)
219   throws IOException {
220       initTableMapperJob(Bytes.toString(table), scan, mapper, outputKeyClass,
221               outputValueClass, job, addDependencyJars, inputFormatClass);
222   }
223 
224   /**
225    * Use this before submitting a TableMap job. It will appropriately set up
226    * the job.
227    *
228    * @param table Binary representation of the table name to read from.
229    * @param scan  The scan instance with the columns, time range etc.
230    * @param mapper  The mapper class to use.
231    * @param outputKeyClass  The class of the output key.
232    * @param outputValueClass  The class of the output value.
233    * @param job  The current job to adjust.  Make sure the passed job is
234    * carrying all necessary HBase configuration.
235    * @param addDependencyJars upload HBase jars and jars for any of the configured
236    *           job classes via the distributed cache (tmpjars).
237    * @throws IOException When setting up the details fails.
238    */
239   public static void initTableMapperJob(byte[] table, Scan scan,
240       Class<? extends TableMapper> mapper,
241       Class<?> outputKeyClass,
242       Class<?> outputValueClass, Job job,
243       boolean addDependencyJars)
244   throws IOException {
245       initTableMapperJob(Bytes.toString(table), scan, mapper, outputKeyClass,
246               outputValueClass, job, addDependencyJars, TableInputFormat.class);
247   }
248 
249   /**
250    * Use this before submitting a TableMap job. It will appropriately set up
251    * the job.
252    *
253    * @param table The table name to read from.
254    * @param scan  The scan instance with the columns, time range etc.
255    * @param mapper  The mapper class to use.
256    * @param outputKeyClass  The class of the output key.
257    * @param outputValueClass  The class of the output value.
258    * @param job  The current job to adjust.  Make sure the passed job is
259    * carrying all necessary HBase configuration.
260    * @param addDependencyJars upload HBase jars and jars for any of the configured
261    *           job classes via the distributed cache (tmpjars).
262    * @throws IOException When setting up the details fails.
263    */
264   public static void initTableMapperJob(String table, Scan scan,
265       Class<? extends TableMapper> mapper,
266       Class<?> outputKeyClass,
267       Class<?> outputValueClass, Job job,
268       boolean addDependencyJars)
269   throws IOException {
270       initTableMapperJob(table, scan, mapper, outputKeyClass,
271               outputValueClass, job, addDependencyJars, TableInputFormat.class);
272   }
273 
274   /**
275    * Sets up the job for reading from a table snapshot. It bypasses hbase servers
276    * and read directly from snapshot files.
277    *
278    * @param snapshotName The name of the snapshot (of a table) to read from.
279    * @param scan  The scan instance with the columns, time range etc.
280    * @param mapper  The mapper class to use.
281    * @param outputKeyClass  The class of the output key.
282    * @param outputValueClass  The class of the output value.
283    * @param job  The current job to adjust.  Make sure the passed job is
284    * carrying all necessary HBase configuration.
285    * @param addDependencyJars upload HBase jars and jars for any of the configured
286    *           job classes via the distributed cache (tmpjars).
287    *
288    * @param tmpRestoreDir a temporary directory to copy the snapshot files into. Current user should
289    * have write permissions to this directory, and this should not be a subdirectory of rootdir.
290    * After the job is finished, restore directory can be deleted.
291    * @throws IOException When setting up the details fails.
292    * @see TableSnapshotInputFormat
293    */
294   public static void initTableSnapshotMapperJob(String snapshotName, Scan scan,
295       Class<? extends TableMapper> mapper,
296       Class<?> outputKeyClass,
297       Class<?> outputValueClass, Job job,
298       boolean addDependencyJars, Path tmpRestoreDir)
299   throws IOException {
300     TableSnapshotInputFormat.setInput(job, snapshotName, tmpRestoreDir);
301     initTableMapperJob(snapshotName, scan, mapper, outputKeyClass,
302         outputValueClass, job, addDependencyJars, false, TableSnapshotInputFormat.class);
303 
304     // We would need even more libraries that hbase-server depends on
305     TableMapReduceUtil.addDependencyJars(job.getConfiguration(), Counter.class);
306   }
307 
308   /**
309    * Use this before submitting a Multi TableMap job. It will appropriately set
310    * up the job.
311    *
312    * @param scans The list of {@link Scan} objects to read from.
313    * @param mapper The mapper class to use.
314    * @param outputKeyClass The class of the output key.
315    * @param outputValueClass The class of the output value.
316    * @param job The current job to adjust. Make sure the passed job is carrying
317    *          all necessary HBase configuration.
318    * @throws IOException When setting up the details fails.
319    */
320   public static void initTableMapperJob(List<Scan> scans,
321       Class<? extends TableMapper> mapper,
322       Class<? extends WritableComparable> outputKeyClass,
323       Class<? extends Writable> outputValueClass, Job job) throws IOException {
324     initTableMapperJob(scans, mapper, outputKeyClass, outputValueClass, job,
325         true);
326   }
327 
328   /**
329    * Use this before submitting a Multi TableMap job. It will appropriately set
330    * up the job.
331    *
332    * @param scans The list of {@link Scan} objects to read from.
333    * @param mapper The mapper class to use.
334    * @param outputKeyClass The class of the output key.
335    * @param outputValueClass The class of the output value.
336    * @param job The current job to adjust. Make sure the passed job is carrying
337    *          all necessary HBase configuration.
338    * @param addDependencyJars upload HBase jars and jars for any of the
339    *          configured job classes via the distributed cache (tmpjars).
340    * @throws IOException When setting up the details fails.
341    */
342   public static void initTableMapperJob(List<Scan> scans,
343       Class<? extends TableMapper> mapper,
344       Class<? extends WritableComparable> outputKeyClass,
345       Class<? extends Writable> outputValueClass, Job job,
346       boolean addDependencyJars) throws IOException {
347     job.setInputFormatClass(MultiTableInputFormat.class);
348     if (outputValueClass != null) {
349       job.setMapOutputValueClass(outputValueClass);
350     }
351     if (outputKeyClass != null) {
352       job.setMapOutputKeyClass(outputKeyClass);
353     }
354     job.setMapperClass(mapper);
355     HBaseConfiguration.addHbaseResources(job.getConfiguration());
356     List<String> scanStrings = new ArrayList<String>();
357 
358     for (Scan scan : scans) {
359       scanStrings.add(convertScanToString(scan));
360     }
361     job.getConfiguration().setStrings(MultiTableInputFormat.SCANS,
362       scanStrings.toArray(new String[scanStrings.size()]));
363 
364     if (addDependencyJars) {
365       addDependencyJars(job);
366     }
367   }
368 
369   public static void initCredentials(Job job) throws IOException {
370     UserProvider userProvider = UserProvider.instantiate(job.getConfiguration());
371     if (userProvider.isHadoopSecurityEnabled()) {
372       // propagate delegation related props from launcher job to MR job
373       if (System.getenv("HADOOP_TOKEN_FILE_LOCATION") != null) {
374         job.getConfiguration().set("mapreduce.job.credentials.binary",
375                                    System.getenv("HADOOP_TOKEN_FILE_LOCATION"));
376       }
377     }
378 
379     if (userProvider.isHBaseSecurityEnabled()) {
380       try {
381         // init credentials for remote cluster
382         String quorumAddress = job.getConfiguration().get(TableOutputFormat.QUORUM_ADDRESS);
383         User user = userProvider.getCurrent();
384         if (quorumAddress != null) {
385           Configuration peerConf = HBaseConfiguration.create(job.getConfiguration());
386           ZKUtil.applyClusterKeyToConf(peerConf, quorumAddress);
387           obtainAuthTokenForJob(job, peerConf, user);
388         }
389 
390         obtainAuthTokenForJob(job, job.getConfiguration(), user);
391       } catch (InterruptedException ie) {
392         LOG.info("Interrupted obtaining user authentication token");
393         Thread.currentThread().interrupt();
394       }
395     }
396   }
397 
398   /**
399    * Obtain an authentication token, for the specified cluster, on behalf of the current user
400    * and add it to the credentials for the given map reduce job.
401    *
402    * The quorumAddress is the key to the ZK ensemble, which contains:
403    * hbase.zookeeper.quorum, hbase.zookeeper.client.port and zookeeper.znode.parent
404    *
405    * @param job The job that requires the permission.
406    * @param quorumAddress string that contains the 3 required configuratins
407    * @throws IOException When the authentication token cannot be obtained.
408    */
409   public static void initCredentialsForCluster(Job job, String quorumAddress)
410       throws IOException {
411     UserProvider userProvider = UserProvider.instantiate(job.getConfiguration());
412     if (userProvider.isHBaseSecurityEnabled()) {
413       try {
414         Configuration peerConf = HBaseConfiguration.create(job.getConfiguration());
415         ZKUtil.applyClusterKeyToConf(peerConf, quorumAddress);
416         obtainAuthTokenForJob(job, peerConf, userProvider.getCurrent());
417       } catch (InterruptedException e) {
418         LOG.info("Interrupted obtaining user authentication token");
419         Thread.interrupted();
420       }
421     }
422   }
423 
424   private static void obtainAuthTokenForJob(Job job, Configuration conf, User user)
425       throws IOException, InterruptedException {
426     Token<AuthenticationTokenIdentifier> authToken = getAuthToken(conf, user);
427     if (authToken == null) {
428       user.obtainAuthTokenForJob(conf, job);
429     } else {
430       job.getCredentials().addToken(authToken.getService(), authToken);
431     }
432   }
433 
434   /**
435    * Get the authentication token of the user for the cluster specified in the configuration
436    * @return null if the user does not have the token, otherwise the auth token for the cluster.
437    */
438   private static Token<AuthenticationTokenIdentifier> getAuthToken(Configuration conf, User user)
439       throws IOException, InterruptedException {
440     ZooKeeperWatcher zkw = new ZooKeeperWatcher(conf, "mr-init-credentials", null);
441     try {
442       String clusterId = ZKClusterId.readClusterIdZNode(zkw);
443       return new AuthenticationTokenSelector().selectToken(new Text(clusterId), user.getUGI().getTokens());
444     } catch (KeeperException e) {
445       throw new IOException(e);
446     } finally {
447       zkw.close();
448     }
449   }
450 
451   /**
452    * Writes the given scan into a Base64 encoded string.
453    *
454    * @param scan  The scan to write out.
455    * @return The scan saved in a Base64 encoded string.
456    * @throws IOException When writing the scan fails.
457    */
458   static String convertScanToString(Scan scan) throws IOException {
459     ClientProtos.Scan proto = ProtobufUtil.toScan(scan);
460     return Base64.encodeBytes(proto.toByteArray());
461   }
462 
463   /**
464    * Converts the given Base64 string back into a Scan instance.
465    *
466    * @param base64  The scan details.
467    * @return The newly created Scan instance.
468    * @throws IOException When reading the scan instance fails.
469    */
470   static Scan convertStringToScan(String base64) throws IOException {
471     byte [] decoded = Base64.decode(base64);
472     ClientProtos.Scan scan;
473     try {
474       scan = ClientProtos.Scan.parseFrom(decoded);
475     } catch (InvalidProtocolBufferException ipbe) {
476       throw new IOException(ipbe);
477     }
478 
479     return ProtobufUtil.toScan(scan);
480   }
481 
482   /**
483    * Use this before submitting a TableReduce job. It will
484    * appropriately set up the JobConf.
485    *
486    * @param table  The output table.
487    * @param reducer  The reducer class to use.
488    * @param job  The current job to adjust.
489    * @throws IOException When determining the region count fails.
490    */
491   public static void initTableReducerJob(String table,
492     Class<? extends TableReducer> reducer, Job job)
493   throws IOException {
494     initTableReducerJob(table, reducer, job, null);
495   }
496 
497   /**
498    * Use this before submitting a TableReduce job. It will
499    * appropriately set up the JobConf.
500    *
501    * @param table  The output table.
502    * @param reducer  The reducer class to use.
503    * @param job  The current job to adjust.
504    * @param partitioner  Partitioner to use. Pass <code>null</code> to use
505    * default partitioner.
506    * @throws IOException When determining the region count fails.
507    */
508   public static void initTableReducerJob(String table,
509     Class<? extends TableReducer> reducer, Job job,
510     Class partitioner) throws IOException {
511     initTableReducerJob(table, reducer, job, partitioner, null, null, null);
512   }
513 
514   /**
515    * Use this before submitting a TableReduce job. It will
516    * appropriately set up the JobConf.
517    *
518    * @param table  The output table.
519    * @param reducer  The reducer class to use.
520    * @param job  The current job to adjust.  Make sure the passed job is
521    * carrying all necessary HBase configuration.
522    * @param partitioner  Partitioner to use. Pass <code>null</code> to use
523    * default partitioner.
524    * @param quorumAddress Distant cluster to write to; default is null for
525    * output to the cluster that is designated in <code>hbase-site.xml</code>.
526    * Set this String to the zookeeper ensemble of an alternate remote cluster
527    * when you would have the reduce write a cluster that is other than the
528    * default; e.g. copying tables between clusters, the source would be
529    * designated by <code>hbase-site.xml</code> and this param would have the
530    * ensemble address of the remote cluster.  The format to pass is particular.
531    * Pass <code> &lt;hbase.zookeeper.quorum>:&lt;hbase.zookeeper.client.port>:&lt;zookeeper.znode.parent>
532    * </code> such as <code>server,server2,server3:2181:/hbase</code>.
533    * @param serverClass redefined hbase.regionserver.class
534    * @param serverImpl redefined hbase.regionserver.impl
535    * @throws IOException When determining the region count fails.
536    */
537   public static void initTableReducerJob(String table,
538     Class<? extends TableReducer> reducer, Job job,
539     Class partitioner, String quorumAddress, String serverClass,
540     String serverImpl) throws IOException {
541     initTableReducerJob(table, reducer, job, partitioner, quorumAddress,
542         serverClass, serverImpl, true);
543   }
544 
545   /**
546    * Use this before submitting a TableReduce job. It will
547    * appropriately set up the JobConf.
548    *
549    * @param table  The output table.
550    * @param reducer  The reducer class to use.
551    * @param job  The current job to adjust.  Make sure the passed job is
552    * carrying all necessary HBase configuration.
553    * @param partitioner  Partitioner to use. Pass <code>null</code> to use
554    * default partitioner.
555    * @param quorumAddress Distant cluster to write to; default is null for
556    * output to the cluster that is designated in <code>hbase-site.xml</code>.
557    * Set this String to the zookeeper ensemble of an alternate remote cluster
558    * when you would have the reduce write a cluster that is other than the
559    * default; e.g. copying tables between clusters, the source would be
560    * designated by <code>hbase-site.xml</code> and this param would have the
561    * ensemble address of the remote cluster.  The format to pass is particular.
562    * Pass <code> &lt;hbase.zookeeper.quorum>:&lt;hbase.zookeeper.client.port>:&lt;zookeeper.znode.parent>
563    * </code> such as <code>server,server2,server3:2181:/hbase</code>.
564    * @param serverClass redefined hbase.regionserver.class
565    * @param serverImpl redefined hbase.regionserver.impl
566    * @param addDependencyJars upload HBase jars and jars for any of the configured
567    *           job classes via the distributed cache (tmpjars).
568    * @throws IOException When determining the region count fails.
569    */
570   public static void initTableReducerJob(String table,
571     Class<? extends TableReducer> reducer, Job job,
572     Class partitioner, String quorumAddress, String serverClass,
573     String serverImpl, boolean addDependencyJars) throws IOException {
574 
575     Configuration conf = job.getConfiguration();
576     HBaseConfiguration.merge(conf, HBaseConfiguration.create(conf));
577     job.setOutputFormatClass(TableOutputFormat.class);
578     if (reducer != null) job.setReducerClass(reducer);
579     conf.set(TableOutputFormat.OUTPUT_TABLE, table);
580     conf.setStrings("io.serializations", conf.get("io.serializations"),
581         MutationSerialization.class.getName(), ResultSerialization.class.getName());
582     // If passed a quorum/ensemble address, pass it on to TableOutputFormat.
583     if (quorumAddress != null) {
584       // Calling this will validate the format
585       ZKUtil.transformClusterKey(quorumAddress);
586       conf.set(TableOutputFormat.QUORUM_ADDRESS,quorumAddress);
587     }
588     if (serverClass != null && serverImpl != null) {
589       conf.set(TableOutputFormat.REGION_SERVER_CLASS, serverClass);
590       conf.set(TableOutputFormat.REGION_SERVER_IMPL, serverImpl);
591     }
592     job.setOutputKeyClass(ImmutableBytesWritable.class);
593     job.setOutputValueClass(Writable.class);
594     if (partitioner == HRegionPartitioner.class) {
595       job.setPartitionerClass(HRegionPartitioner.class);
596       int regions = MetaReader.getRegionCount(conf, table);
597       if (job.getNumReduceTasks() > regions) {
598         job.setNumReduceTasks(regions);
599       }
600     } else if (partitioner != null) {
601       job.setPartitionerClass(partitioner);
602     }
603 
604     if (addDependencyJars) {
605       addDependencyJars(job);
606     }
607 
608     initCredentials(job);
609   }
610 
611   /**
612    * Ensures that the given number of reduce tasks for the given job
613    * configuration does not exceed the number of regions for the given table.
614    *
615    * @param table  The table to get the region count for.
616    * @param job  The current job to adjust.
617    * @throws IOException When retrieving the table details fails.
618    */
619   public static void limitNumReduceTasks(String table, Job job)
620   throws IOException {
621     int regions = MetaReader.getRegionCount(job.getConfiguration(), table);
622     if (job.getNumReduceTasks() > regions)
623       job.setNumReduceTasks(regions);
624   }
625 
626   /**
627    * Sets the number of reduce tasks for the given job configuration to the
628    * number of regions the given table has.
629    *
630    * @param table  The table to get the region count for.
631    * @param job  The current job to adjust.
632    * @throws IOException When retrieving the table details fails.
633    */
634   public static void setNumReduceTasks(String table, Job job)
635   throws IOException {
636     job.setNumReduceTasks(MetaReader.getRegionCount(job.getConfiguration(), table));
637   }
638 
639   /**
640    * Sets the number of rows to return and cache with each scanner iteration.
641    * Higher caching values will enable faster mapreduce jobs at the expense of
642    * requiring more heap to contain the cached rows.
643    *
644    * @param job The current job to adjust.
645    * @param batchSize The number of rows to return in batch with each scanner
646    * iteration.
647    */
648   public static void setScannerCaching(Job job, int batchSize) {
649     job.getConfiguration().setInt("hbase.client.scanner.caching", batchSize);
650   }
651 
652   /**
653    * Add HBase and its dependencies (only) to the job configuration.
654    * <p>
655    * This is intended as a low-level API, facilitating code reuse between this
656    * class and its mapred counterpart. It also of use to extenral tools that
657    * need to build a MapReduce job that interacts with HBase but want
658    * fine-grained control over the jars shipped to the cluster.
659    * </p>
660    * @param conf The Configuration object to extend with dependencies.
661    * @see org.apache.hadoop.hbase.mapred.TableMapReduceUtil
662    * @see <a href="https://issues.apache.org/jira/browse/PIG-3285">PIG-3285</a>
663    */
664   public static void addHBaseDependencyJars(Configuration conf) throws IOException {
665     addDependencyJars(conf,
666       // explicitly pull a class from each module
667       org.apache.hadoop.hbase.HConstants.class,                      // hbase-common
668       org.apache.hadoop.hbase.protobuf.generated.ClientProtos.class, // hbase-protocol
669       org.apache.hadoop.hbase.client.Put.class,                      // hbase-client
670       org.apache.hadoop.hbase.CompatibilityFactory.class,            // hbase-hadoop-compat
671       org.apache.hadoop.hbase.mapreduce.TableMapper.class,           // hbase-server
672       // pull necessary dependencies
673       org.apache.zookeeper.ZooKeeper.class,
674       org.jboss.netty.channel.ChannelFactory.class,
675       com.google.protobuf.Message.class,
676       com.google.common.collect.Lists.class,
677       org.cloudera.htrace.Trace.class);
678   }
679 
680   /**
681    * Returns a classpath string built from the content of the "tmpjars" value in {@code conf}.
682    * Also exposed to shell scripts via `bin/hbase mapredcp`.
683    */
684   public static String buildDependencyClasspath(Configuration conf) {
685     if (conf == null) {
686       throw new IllegalArgumentException("Must provide a configuration object.");
687     }
688     Set<String> paths = new HashSet<String>(conf.getStringCollection("tmpjars"));
689     if (paths.size() == 0) {
690       throw new IllegalArgumentException("Configuration contains no tmpjars.");
691     }
692     StringBuilder sb = new StringBuilder();
693     for (String s : paths) {
694       // entries can take the form 'file:/path/to/file.jar'.
695       int idx = s.indexOf(":");
696       if (idx != -1) s = s.substring(idx + 1);
697       if (sb.length() > 0) sb.append(File.pathSeparator);
698       sb.append(s);
699     }
700     return sb.toString();
701   }
702 
703   /**
704    * Add the HBase dependency jars as well as jars for any of the configured
705    * job classes to the job configuration, so that JobClient will ship them
706    * to the cluster and add them to the DistributedCache.
707    */
708   public static void addDependencyJars(Job job) throws IOException {
709     addHBaseDependencyJars(job.getConfiguration());
710     try {
711       addDependencyJars(job.getConfiguration(),
712           // when making changes here, consider also mapred.TableMapReduceUtil
713           // pull job classes
714           job.getMapOutputKeyClass(),
715           job.getMapOutputValueClass(),
716           job.getInputFormatClass(),
717           job.getOutputKeyClass(),
718           job.getOutputValueClass(),
719           job.getOutputFormatClass(),
720           job.getPartitionerClass(),
721           job.getCombinerClass());
722     } catch (ClassNotFoundException e) {
723       throw new IOException(e);
724     }
725   }
726 
727   /**
728    * Add the jars containing the given classes to the job's configuration
729    * such that JobClient will ship them to the cluster and add them to
730    * the DistributedCache.
731    */
732   public static void addDependencyJars(Configuration conf,
733       Class<?>... classes) throws IOException {
734 
735     FileSystem localFs = FileSystem.getLocal(conf);
736     Set<String> jars = new HashSet<String>();
737     // Add jars that are already in the tmpjars variable
738     jars.addAll(conf.getStringCollection("tmpjars"));
739 
740     // add jars as we find them to a map of contents jar name so that we can avoid
741     // creating new jars for classes that have already been packaged.
742     Map<String, String> packagedClasses = new HashMap<String, String>();
743 
744     // Add jars containing the specified classes
745     for (Class<?> clazz : classes) {
746       if (clazz == null) continue;
747 
748       Path path = findOrCreateJar(clazz, localFs, packagedClasses);
749       if (path == null) {
750         LOG.warn("Could not find jar for class " + clazz +
751                  " in order to ship it to the cluster.");
752         continue;
753       }
754       if (!localFs.exists(path)) {
755         LOG.warn("Could not validate jar file " + path + " for class "
756                  + clazz);
757         continue;
758       }
759       jars.add(path.toString());
760     }
761     if (jars.isEmpty()) return;
762 
763     conf.set("tmpjars", StringUtils.arrayToString(jars.toArray(new String[jars.size()])));
764   }
765 
766   /**
767    * If org.apache.hadoop.util.JarFinder is available (0.23+ hadoop), finds
768    * the Jar for a class or creates it if it doesn't exist. If the class is in
769    * a directory in the classpath, it creates a Jar on the fly with the
770    * contents of the directory and returns the path to that Jar. If a Jar is
771    * created, it is created in the system temporary directory. Otherwise,
772    * returns an existing jar that contains a class of the same name. Maintains
773    * a mapping from jar contents to the tmp jar created.
774    * @param my_class the class to find.
775    * @param fs the FileSystem with which to qualify the returned path.
776    * @param packagedClasses a map of class name to path.
777    * @return a jar file that contains the class.
778    * @throws IOException
779    */
780   private static Path findOrCreateJar(Class<?> my_class, FileSystem fs,
781       Map<String, String> packagedClasses)
782   throws IOException {
783     // attempt to locate an existing jar for the class.
784     String jar = findContainingJar(my_class, packagedClasses);
785     if (null == jar || jar.isEmpty()) {
786       jar = getJar(my_class);
787       updateMap(jar, packagedClasses);
788     }
789 
790     if (null == jar || jar.isEmpty()) {
791       return null;
792     }
793 
794     LOG.debug(String.format("For class %s, using jar %s", my_class.getName(), jar));
795     return new Path(jar).makeQualified(fs);
796   }
797 
798   /**
799    * Add entries to <code>packagedClasses</code> corresponding to class files
800    * contained in <code>jar</code>.
801    * @param jar The jar who's content to list.
802    * @param packagedClasses map[class -> jar]
803    */
804   private static void updateMap(String jar, Map<String, String> packagedClasses) throws IOException {
805     if (null == jar || jar.isEmpty()) {
806       return;
807     }
808     ZipFile zip = null;
809     try {
810       zip = new ZipFile(jar);
811       for (Enumeration<? extends ZipEntry> iter = zip.entries(); iter.hasMoreElements();) {
812         ZipEntry entry = iter.nextElement();
813         if (entry.getName().endsWith("class")) {
814           packagedClasses.put(entry.getName(), jar);
815         }
816       }
817     } finally {
818       if (null != zip) zip.close();
819     }
820   }
821 
822   /**
823    * Find a jar that contains a class of the same name, if any. It will return
824    * a jar file, even if that is not the first thing on the class path that
825    * has a class with the same name. Looks first on the classpath and then in
826    * the <code>packagedClasses</code> map.
827    * @param my_class the class to find.
828    * @return a jar file that contains the class, or null.
829    * @throws IOException
830    */
831   private static String findContainingJar(Class<?> my_class, Map<String, String> packagedClasses)
832       throws IOException {
833     ClassLoader loader = my_class.getClassLoader();
834     String class_file = my_class.getName().replaceAll("\\.", "/") + ".class";
835 
836     // first search the classpath
837     for (Enumeration<URL> itr = loader.getResources(class_file); itr.hasMoreElements();) {
838       URL url = itr.nextElement();
839       if ("jar".equals(url.getProtocol())) {
840         String toReturn = url.getPath();
841         if (toReturn.startsWith("file:")) {
842           toReturn = toReturn.substring("file:".length());
843         }
844         // URLDecoder is a misnamed class, since it actually decodes
845         // x-www-form-urlencoded MIME type rather than actual
846         // URL encoding (which the file path has). Therefore it would
847         // decode +s to ' 's which is incorrect (spaces are actually
848         // either unencoded or encoded as "%20"). Replace +s first, so
849         // that they are kept sacred during the decoding process.
850         toReturn = toReturn.replaceAll("\\+", "%2B");
851         toReturn = URLDecoder.decode(toReturn, "UTF-8");
852         return toReturn.replaceAll("!.*$", "");
853       }
854     }
855 
856     // now look in any jars we've packaged using JarFinder. Returns null when
857     // no jar is found.
858     return packagedClasses.get(class_file);
859   }
860 
861   /**
862    * Invoke 'getJar' on a JarFinder implementation. Useful for some job
863    * configuration contexts (HBASE-8140) and also for testing on MRv2. First
864    * check if we have HADOOP-9426. Lacking that, fall back to the backport.
865    * @param my_class the class to find.
866    * @return a jar file that contains the class, or null.
867    */
868   private static String getJar(Class<?> my_class) {
869     String ret = null;
870     String hadoopJarFinder = "org.apache.hadoop.util.JarFinder";
871     Class<?> jarFinder = null;
872     try {
873       LOG.debug("Looking for " + hadoopJarFinder + ".");
874       jarFinder = Class.forName(hadoopJarFinder);
875       LOG.debug(hadoopJarFinder + " found.");
876       Method getJar = jarFinder.getMethod("getJar", Class.class);
877       ret = (String) getJar.invoke(null, my_class);
878     } catch (ClassNotFoundException e) {
879       LOG.debug("Using backported JarFinder.");
880       ret = JarFinder.getJar(my_class);
881     } catch (InvocationTargetException e) {
882       // function was properly called, but threw it's own exception. Unwrap it
883       // and pass it on.
884       throw new RuntimeException(e.getCause());
885     } catch (Exception e) {
886       // toss all other exceptions, related to reflection failure
887       throw new RuntimeException("getJar invocation failed.", e);
888     }
889 
890     return ret;
891   }
892 }