View Javadoc

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