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.net.URL;
24 import java.net.URLDecoder;
25 import java.util.*;
26 import java.util.zip.ZipEntry;
27 import java.util.zip.ZipFile;
28
29 import com.google.protobuf.InvalidProtocolBufferException;
30 import org.apache.commons.logging.Log;
31 import org.apache.commons.logging.LogFactory;
32 import org.apache.hadoop.conf.Configuration;
33 import org.apache.hadoop.fs.FileSystem;
34 import org.apache.hadoop.fs.Path;
35 import org.apache.hadoop.hbase.HBaseConfiguration;
36 import org.apache.hadoop.hbase.HConstants;
37 import org.apache.hadoop.hbase.MetaTableAccessor;
38 import org.apache.hadoop.hbase.TableName;
39 import org.apache.hadoop.hbase.classification.InterfaceAudience;
40 import org.apache.hadoop.hbase.classification.InterfaceStability;
41 import org.apache.hadoop.hbase.client.Connection;
42 import org.apache.hadoop.hbase.client.ConnectionFactory;
43 import org.apache.hadoop.hbase.client.Put;
44 import org.apache.hadoop.hbase.client.Scan;
45 import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
46 import org.apache.hadoop.hbase.protobuf.ProtobufUtil;
47 import org.apache.hadoop.hbase.protobuf.generated.ClientProtos;
48 import org.apache.hadoop.hbase.security.User;
49 import org.apache.hadoop.hbase.security.UserProvider;
50 import org.apache.hadoop.hbase.security.token.TokenUtil;
51 import org.apache.hadoop.hbase.util.Base64;
52 import org.apache.hadoop.hbase.util.Bytes;
53 import org.apache.hadoop.hbase.zookeeper.ZKConfig;
54 import org.apache.hadoop.io.Writable;
55 import org.apache.hadoop.mapreduce.InputFormat;
56 import org.apache.hadoop.mapreduce.Job;
57 import org.apache.hadoop.util.StringUtils;
58 import org.apache.hadoop.hbase.util.RegionSplitter;
59
60 /**
61 * Utility for {@link TableMapper} and {@link TableReducer}
62 */
63 @SuppressWarnings({ "rawtypes", "unchecked" })
64 @InterfaceAudience.Public
65 @InterfaceStability.Stable
66 public class TableMapReduceUtil {
67 private static final Log LOG = LogFactory.getLog(TableMapReduceUtil.class);
68
69 /**
70 * Use this before submitting a TableMap job. It will appropriately set up
71 * the job.
72 *
73 * @param table The table name to read from.
74 * @param scan The scan instance with the columns, time range etc.
75 * @param mapper The mapper class to use.
76 * @param outputKeyClass The class of the output key.
77 * @param outputValueClass The class of the output value.
78 * @param job The current job to adjust. Make sure the passed job is
79 * carrying all necessary HBase configuration.
80 * @throws IOException When setting up the details fails.
81 */
82 public static void initTableMapperJob(String table, Scan scan,
83 Class<? extends TableMapper> mapper,
84 Class<?> outputKeyClass,
85 Class<?> outputValueClass, Job job)
86 throws IOException {
87 initTableMapperJob(table, scan, mapper, outputKeyClass, outputValueClass,
88 job, true);
89 }
90
91
92 /**
93 * Use this before submitting a TableMap job. It will appropriately set up
94 * the job.
95 *
96 * @param table The table name to read from.
97 * @param scan The scan instance with the columns, time range etc.
98 * @param mapper The mapper class to use.
99 * @param outputKeyClass The class of the output key.
100 * @param outputValueClass The class of the output value.
101 * @param job The current job to adjust. Make sure the passed job is
102 * carrying all necessary HBase configuration.
103 * @throws IOException When setting up the details fails.
104 */
105 public static void initTableMapperJob(TableName table,
106 Scan scan,
107 Class<? extends TableMapper> mapper,
108 Class<?> outputKeyClass,
109 Class<?> outputValueClass,
110 Job job) throws IOException {
111 initTableMapperJob(table.getNameAsString(),
112 scan,
113 mapper,
114 outputKeyClass,
115 outputValueClass,
116 job,
117 true);
118 }
119
120 /**
121 * Use this before submitting a TableMap job. It will appropriately set up
122 * the job.
123 *
124 * @param table Binary representation of 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 * @throws IOException When setting up the details fails.
132 */
133 public static void initTableMapperJob(byte[] table, Scan scan,
134 Class<? extends TableMapper> mapper,
135 Class<?> outputKeyClass,
136 Class<?> outputValueClass, Job job)
137 throws IOException {
138 initTableMapperJob(Bytes.toString(table), scan, mapper, outputKeyClass, outputValueClass,
139 job, true);
140 }
141
142 /**
143 * Use this before submitting a TableMap job. It will appropriately set up
144 * the job.
145 *
146 * @param table The table name to read from.
147 * @param scan The scan instance with the columns, time range etc.
148 * @param mapper The mapper class to use.
149 * @param outputKeyClass The class of the output key.
150 * @param outputValueClass The class of the output value.
151 * @param job The current job to adjust. Make sure the passed job is
152 * carrying all necessary HBase configuration.
153 * @param addDependencyJars upload HBase jars and jars for any of the configured
154 * job classes via the distributed cache (tmpjars).
155 * @throws IOException When setting up the details fails.
156 */
157 public static void initTableMapperJob(String table, Scan scan,
158 Class<? extends TableMapper> mapper,
159 Class<?> outputKeyClass,
160 Class<?> outputValueClass, Job job,
161 boolean addDependencyJars, Class<? extends InputFormat> inputFormatClass)
162 throws IOException {
163 initTableMapperJob(table, scan, mapper, outputKeyClass, outputValueClass, job,
164 addDependencyJars, true, inputFormatClass);
165 }
166
167
168 /**
169 * Use this before submitting a TableMap job. It will appropriately set up
170 * the job.
171 *
172 * @param table The table name to read from.
173 * @param scan The scan instance with the columns, time range etc.
174 * @param mapper The mapper class to use.
175 * @param outputKeyClass The class of the output key.
176 * @param outputValueClass The class of the output value.
177 * @param job The current job to adjust. Make sure the passed job is
178 * carrying all necessary HBase configuration.
179 * @param addDependencyJars upload HBase jars and jars for any of the configured
180 * job classes via the distributed cache (tmpjars).
181 * @param initCredentials whether to initialize hbase auth credentials for the job
182 * @param inputFormatClass the input format
183 * @throws IOException When setting up the details fails.
184 */
185 public static void initTableMapperJob(String table, Scan scan,
186 Class<? extends TableMapper> mapper,
187 Class<?> outputKeyClass,
188 Class<?> outputValueClass, Job job,
189 boolean addDependencyJars, boolean initCredentials,
190 Class<? extends InputFormat> inputFormatClass)
191 throws IOException {
192 job.setInputFormatClass(inputFormatClass);
193 if (outputValueClass != null) job.setMapOutputValueClass(outputValueClass);
194 if (outputKeyClass != null) job.setMapOutputKeyClass(outputKeyClass);
195 job.setMapperClass(mapper);
196 if (Put.class.equals(outputValueClass)) {
197 job.setCombinerClass(PutCombiner.class);
198 }
199 Configuration conf = job.getConfiguration();
200 HBaseConfiguration.merge(conf, HBaseConfiguration.create(conf));
201 conf.set(TableInputFormat.INPUT_TABLE, table);
202 conf.set(TableInputFormat.SCAN, convertScanToString(scan));
203 conf.setStrings("io.serializations", conf.get("io.serializations"),
204 MutationSerialization.class.getName(), ResultSerialization.class.getName(),
205 KeyValueSerialization.class.getName());
206 if (addDependencyJars) {
207 addDependencyJars(job);
208 }
209 if (initCredentials) {
210 initCredentials(job);
211 }
212 }
213
214 /**
215 * Use this before submitting a TableMap job. It will appropriately set up
216 * the job.
217 *
218 * @param table Binary representation of the table name to read from.
219 * @param scan The scan instance with the columns, time range etc.
220 * @param mapper The mapper class to use.
221 * @param outputKeyClass The class of the output key.
222 * @param outputValueClass The class of the output value.
223 * @param job The current job to adjust. Make sure the passed job is
224 * carrying all necessary HBase configuration.
225 * @param addDependencyJars upload HBase jars and jars for any of the configured
226 * job classes via the distributed cache (tmpjars).
227 * @param inputFormatClass The class of the input format
228 * @throws IOException When setting up the details fails.
229 */
230 public static void initTableMapperJob(byte[] table, Scan scan,
231 Class<? extends TableMapper> mapper,
232 Class<?> outputKeyClass,
233 Class<?> outputValueClass, Job job,
234 boolean addDependencyJars, Class<? extends InputFormat> inputFormatClass)
235 throws IOException {
236 initTableMapperJob(Bytes.toString(table), scan, mapper, outputKeyClass,
237 outputValueClass, job, addDependencyJars, inputFormatClass);
238 }
239
240 /**
241 * Use this before submitting a TableMap job. It will appropriately set up
242 * the job.
243 *
244 * @param table Binary representation of the table name to read from.
245 * @param scan The scan instance with the columns, time range etc.
246 * @param mapper The mapper class to use.
247 * @param outputKeyClass The class of the output key.
248 * @param outputValueClass The class of the output value.
249 * @param job The current job to adjust. Make sure the passed job is
250 * carrying all necessary HBase configuration.
251 * @param addDependencyJars upload HBase jars and jars for any of the configured
252 * job classes via the distributed cache (tmpjars).
253 * @throws IOException When setting up the details fails.
254 */
255 public static void initTableMapperJob(byte[] table, Scan scan,
256 Class<? extends TableMapper> mapper,
257 Class<?> outputKeyClass,
258 Class<?> outputValueClass, Job job,
259 boolean addDependencyJars)
260 throws IOException {
261 initTableMapperJob(Bytes.toString(table), scan, mapper, outputKeyClass,
262 outputValueClass, job, addDependencyJars, TableInputFormat.class);
263 }
264
265 /**
266 * Use this before submitting a TableMap job. It will appropriately set up
267 * the job.
268 *
269 * @param table The table name to read from.
270 * @param scan The scan instance with the columns, time range etc.
271 * @param mapper The mapper class to use.
272 * @param outputKeyClass The class of the output key.
273 * @param outputValueClass The class of the output value.
274 * @param job The current job to adjust. Make sure the passed job is
275 * carrying all necessary HBase configuration.
276 * @param addDependencyJars upload HBase jars and jars for any of the configured
277 * job classes via the distributed cache (tmpjars).
278 * @throws IOException When setting up the details fails.
279 */
280 public static void initTableMapperJob(String table, Scan scan,
281 Class<? extends TableMapper> mapper,
282 Class<?> outputKeyClass,
283 Class<?> outputValueClass, Job job,
284 boolean addDependencyJars)
285 throws IOException {
286 initTableMapperJob(table, scan, mapper, outputKeyClass,
287 outputValueClass, job, addDependencyJars, TableInputFormat.class);
288 }
289
290 /**
291 * Enable a basic on-heap cache for these jobs. Any BlockCache implementation based on
292 * direct memory will likely cause the map tasks to OOM when opening the region. This
293 * is done here instead of in TableSnapshotRegionRecordReader in case an advanced user
294 * wants to override this behavior in their job.
295 */
296 public static void resetCacheConfig(Configuration conf) {
297 conf.setFloat(
298 HConstants.HFILE_BLOCK_CACHE_SIZE_KEY, HConstants.HFILE_BLOCK_CACHE_SIZE_DEFAULT);
299 conf.setFloat(HConstants.BUCKET_CACHE_SIZE_KEY, 0f);
300 conf.unset(HConstants.BUCKET_CACHE_IOENGINE_KEY);
301 }
302
303 /**
304 * Sets up the job for reading from one or more table snapshots, with one or more scans
305 * per snapshot.
306 * It bypasses hbase servers and read directly from snapshot files.
307 *
308 * @param snapshotScans map of snapshot name to scans on that snapshot.
309 * @param mapper The mapper class to use.
310 * @param outputKeyClass The class of the output key.
311 * @param outputValueClass The class of the output value.
312 * @param job The current job to adjust. Make sure the passed job is
313 * carrying all necessary HBase configuration.
314 * @param addDependencyJars upload HBase jars and jars for any of the configured
315 * job classes via the distributed cache (tmpjars).
316 */
317 public static void initMultiTableSnapshotMapperJob(Map<String, Collection<Scan>> snapshotScans,
318 Class<? extends TableMapper> mapper, Class<?> outputKeyClass, Class<?> outputValueClass,
319 Job job, boolean addDependencyJars, Path tmpRestoreDir) throws IOException {
320 MultiTableSnapshotInputFormat.setInput(job.getConfiguration(), snapshotScans, tmpRestoreDir);
321
322 job.setInputFormatClass(MultiTableSnapshotInputFormat.class);
323 if (outputValueClass != null) {
324 job.setMapOutputValueClass(outputValueClass);
325 }
326 if (outputKeyClass != null) {
327 job.setMapOutputKeyClass(outputKeyClass);
328 }
329 job.setMapperClass(mapper);
330 Configuration conf = job.getConfiguration();
331 HBaseConfiguration.merge(conf, HBaseConfiguration.create(conf));
332
333 if (addDependencyJars) {
334 addDependencyJars(job);
335 }
336
337 resetCacheConfig(job.getConfiguration());
338 }
339
340 /**
341 * Sets up the job for reading from a table snapshot. It bypasses hbase servers
342 * and read directly from snapshot files.
343 *
344 * @param snapshotName The name of the snapshot (of a table) to read from.
345 * @param scan The scan instance with the columns, time range etc.
346 * @param mapper The mapper class to use.
347 * @param outputKeyClass The class of the output key.
348 * @param outputValueClass The class of the output value.
349 * @param job The current job to adjust. Make sure the passed job is
350 * carrying all necessary HBase configuration.
351 * @param addDependencyJars upload HBase jars and jars for any of the configured
352 * job classes via the distributed cache (tmpjars).
353 *
354 * @param tmpRestoreDir a temporary directory to copy the snapshot files into. Current user should
355 * have write permissions to this directory, and this should not be a subdirectory of rootdir.
356 * After the job is finished, restore directory can be deleted.
357 * @throws IOException When setting up the details fails.
358 * @see TableSnapshotInputFormat
359 */
360 public static void initTableSnapshotMapperJob(String snapshotName, Scan scan,
361 Class<? extends TableMapper> mapper,
362 Class<?> outputKeyClass,
363 Class<?> outputValueClass, Job job,
364 boolean addDependencyJars, Path tmpRestoreDir)
365 throws IOException {
366 TableSnapshotInputFormat.setInput(job, snapshotName, tmpRestoreDir);
367 initTableMapperJob(snapshotName, scan, mapper, outputKeyClass,
368 outputValueClass, job, addDependencyJars, false, TableSnapshotInputFormat.class);
369 resetCacheConfig(job.getConfiguration());
370 }
371
372 /**
373 * Sets up the job for reading from a table snapshot. It bypasses hbase servers
374 * and read directly from snapshot files.
375 *
376 * @param snapshotName The name of the snapshot (of a table) to read from.
377 * @param scan The scan instance with the columns, time range etc.
378 * @param mapper The mapper class to use.
379 * @param outputKeyClass The class of the output key.
380 * @param outputValueClass The class of the output value.
381 * @param job The current job to adjust. Make sure the passed job is
382 * carrying all necessary HBase configuration.
383 * @param addDependencyJars upload HBase jars and jars for any of the configured
384 * job classes via the distributed cache (tmpjars).
385 *
386 * @param tmpRestoreDir a temporary directory to copy the snapshot files into. Current user should
387 * have write permissions to this directory, and this should not be a subdirectory of rootdir.
388 * After the job is finished, restore directory can be deleted.
389 * @param splitAlgo algorithm to split
390 * @param numSplitsPerRegion how many input splits to generate per one region
391 * @throws IOException When setting up the details fails.
392 * @see TableSnapshotInputFormat
393 */
394 public static void initTableSnapshotMapperJob(String snapshotName, Scan scan,
395 Class<? extends TableMapper> mapper,
396 Class<?> outputKeyClass,
397 Class<?> outputValueClass, Job job,
398 boolean addDependencyJars, Path tmpRestoreDir,
399 RegionSplitter.SplitAlgorithm splitAlgo,
400 int numSplitsPerRegion)
401 throws IOException {
402 TableSnapshotInputFormat.setInput(job, snapshotName, tmpRestoreDir, splitAlgo,
403 numSplitsPerRegion);
404 initTableMapperJob(snapshotName, scan, mapper, outputKeyClass,
405 outputValueClass, job, addDependencyJars, false, TableSnapshotInputFormat.class);
406 resetCacheConfig(job.getConfiguration());
407 }
408
409
410
411 /**
412 * Use this before submitting a Multi TableMap job. It will appropriately set
413 * up the job.
414 *
415 * @param scans The list of {@link Scan} objects to read from.
416 * @param mapper The mapper class to use.
417 * @param outputKeyClass The class of the output key.
418 * @param outputValueClass The class of the output value.
419 * @param job The current job to adjust. Make sure the passed job is carrying
420 * all necessary HBase configuration.
421 * @throws IOException When setting up the details fails.
422 */
423 public static void initTableMapperJob(List<Scan> scans,
424 Class<? extends TableMapper> mapper,
425 Class<?> outputKeyClass,
426 Class<?> outputValueClass, Job job) throws IOException {
427 initTableMapperJob(scans, mapper, outputKeyClass, outputValueClass, job,
428 true);
429 }
430
431 /**
432 * Use this before submitting a Multi TableMap job. It will appropriately set
433 * up the job.
434 *
435 * @param scans The list of {@link Scan} objects to read from.
436 * @param mapper The mapper class to use.
437 * @param outputKeyClass The class of the output key.
438 * @param outputValueClass The class of the output value.
439 * @param job The current job to adjust. Make sure the passed job is carrying
440 * all necessary HBase configuration.
441 * @param addDependencyJars upload HBase jars and jars for any of the
442 * configured job classes via the distributed cache (tmpjars).
443 * @throws IOException When setting up the details fails.
444 */
445 public static void initTableMapperJob(List<Scan> scans,
446 Class<? extends TableMapper> mapper,
447 Class<?> outputKeyClass,
448 Class<?> outputValueClass, Job job,
449 boolean addDependencyJars) throws IOException {
450 initTableMapperJob(scans, mapper, outputKeyClass, outputValueClass, job,
451 addDependencyJars, true);
452 }
453
454 /**
455 * Use this before submitting a Multi TableMap job. It will appropriately set
456 * up the job.
457 *
458 * @param scans The list of {@link Scan} objects to read from.
459 * @param mapper The mapper class to use.
460 * @param outputKeyClass The class of the output key.
461 * @param outputValueClass The class of the output value.
462 * @param job The current job to adjust. Make sure the passed job is carrying
463 * all necessary HBase configuration.
464 * @param addDependencyJars upload HBase jars and jars for any of the
465 * configured job classes via the distributed cache (tmpjars).
466 * @param initCredentials whether to initialize hbase auth credentials for the job
467 * @throws IOException When setting up the details fails.
468 */
469 public static void initTableMapperJob(List<Scan> scans,
470 Class<? extends TableMapper> mapper,
471 Class<?> outputKeyClass,
472 Class<?> outputValueClass, Job job,
473 boolean addDependencyJars,
474 boolean initCredentials) throws IOException {
475 job.setInputFormatClass(MultiTableInputFormat.class);
476 if (outputValueClass != null) {
477 job.setMapOutputValueClass(outputValueClass);
478 }
479 if (outputKeyClass != null) {
480 job.setMapOutputKeyClass(outputKeyClass);
481 }
482 job.setMapperClass(mapper);
483 Configuration conf = job.getConfiguration();
484 HBaseConfiguration.merge(conf, HBaseConfiguration.create(conf));
485 List<String> scanStrings = new ArrayList<String>();
486
487 for (Scan scan : scans) {
488 scanStrings.add(convertScanToString(scan));
489 }
490 job.getConfiguration().setStrings(MultiTableInputFormat.SCANS,
491 scanStrings.toArray(new String[scanStrings.size()]));
492
493 if (addDependencyJars) {
494 addDependencyJars(job);
495 }
496
497 if (initCredentials) {
498 initCredentials(job);
499 }
500 }
501
502 public static void initCredentials(Job job) throws IOException {
503 UserProvider userProvider = UserProvider.instantiate(job.getConfiguration());
504 if (userProvider.isHadoopSecurityEnabled()) {
505 // propagate delegation related props from launcher job to MR job
506 if (System.getenv("HADOOP_TOKEN_FILE_LOCATION") != null) {
507 job.getConfiguration().set("mapreduce.job.credentials.binary",
508 System.getenv("HADOOP_TOKEN_FILE_LOCATION"));
509 }
510 }
511
512 if (userProvider.isHBaseSecurityEnabled()) {
513 try {
514 // init credentials for remote cluster
515 String quorumAddress = job.getConfiguration().get(TableOutputFormat.QUORUM_ADDRESS);
516 User user = userProvider.getCurrent();
517 if (quorumAddress != null) {
518 Configuration peerConf = HBaseConfiguration.createClusterConf(job.getConfiguration(),
519 quorumAddress, TableOutputFormat.OUTPUT_CONF_PREFIX);
520 Connection peerConn = ConnectionFactory.createConnection(peerConf);
521 try {
522 TokenUtil.addTokenForJob(peerConn, user, job);
523 } finally {
524 peerConn.close();
525 }
526 }
527
528 Connection conn = ConnectionFactory.createConnection(job.getConfiguration());
529 try {
530 TokenUtil.addTokenForJob(conn, user, job);
531 } finally {
532 conn.close();
533 }
534 } catch (InterruptedException ie) {
535 LOG.info("Interrupted obtaining user authentication token");
536 Thread.currentThread().interrupt();
537 }
538 }
539 }
540
541 /**
542 * Obtain an authentication token, for the specified cluster, on behalf of the current user
543 * and add it to the credentials for the given map reduce job.
544 *
545 * The quorumAddress is the key to the ZK ensemble, which contains:
546 * hbase.zookeeper.quorum, hbase.zookeeper.client.port and
547 * zookeeper.znode.parent
548 *
549 * @param job The job that requires the permission.
550 * @param quorumAddress string that contains the 3 required configuratins
551 * @throws IOException When the authentication token cannot be obtained.
552 * @deprecated Since 1.2.0, use {@link #initCredentialsForCluster(Job, Configuration)} instead.
553 */
554 @Deprecated
555 public static void initCredentialsForCluster(Job job, String quorumAddress)
556 throws IOException {
557 Configuration peerConf = HBaseConfiguration.createClusterConf(job.getConfiguration(),
558 quorumAddress);
559 initCredentialsForCluster(job, peerConf);
560 }
561
562 /**
563 * Obtain an authentication token, for the specified cluster, on behalf of the current user
564 * and add it to the credentials for the given map reduce job.
565 *
566 * @param job The job that requires the permission.
567 * @param conf The configuration to use in connecting to the peer cluster
568 * @throws IOException When the authentication token cannot be obtained.
569 */
570 public static void initCredentialsForCluster(Job job, Configuration conf)
571 throws IOException {
572 UserProvider userProvider = UserProvider.instantiate(job.getConfiguration());
573 if (userProvider.isHBaseSecurityEnabled()) {
574 try {
575 Connection peerConn = ConnectionFactory.createConnection(conf);
576 try {
577 TokenUtil.addTokenForJob(peerConn, userProvider.getCurrent(), job);
578 } finally {
579 peerConn.close();
580 }
581 } catch (InterruptedException e) {
582 LOG.info("Interrupted obtaining user authentication token");
583 Thread.interrupted();
584 }
585 }
586 }
587
588 /**
589 * Writes the given scan into a Base64 encoded string.
590 *
591 * @param scan The scan to write out.
592 * @return The scan saved in a Base64 encoded string.
593 * @throws IOException When writing the scan fails.
594 */
595 public static String convertScanToString(Scan scan) throws IOException {
596 ClientProtos.Scan proto = ProtobufUtil.toScan(scan);
597 return Base64.encodeBytes(proto.toByteArray());
598 }
599
600 /**
601 * Converts the given Base64 string back into a Scan instance.
602 *
603 * @param base64 The scan details.
604 * @return The newly created Scan instance.
605 * @throws IOException When reading the scan instance fails.
606 */
607 public static Scan convertStringToScan(String base64) throws IOException {
608 byte [] decoded = Base64.decode(base64);
609 ClientProtos.Scan scan;
610 try {
611 scan = ClientProtos.Scan.parseFrom(decoded);
612 } catch (InvalidProtocolBufferException ipbe) {
613 throw new IOException(ipbe);
614 }
615
616 return ProtobufUtil.toScan(scan);
617 }
618
619 /**
620 * Use this before submitting a TableReduce job. It will
621 * appropriately set up the JobConf.
622 *
623 * @param table The output table.
624 * @param reducer The reducer class to use.
625 * @param job The current job to adjust.
626 * @throws IOException When determining the region count fails.
627 */
628 public static void initTableReducerJob(String table,
629 Class<? extends TableReducer> reducer, Job job)
630 throws IOException {
631 initTableReducerJob(table, reducer, job, null);
632 }
633
634 /**
635 * Use this before submitting a TableReduce job. It will
636 * appropriately set up the JobConf.
637 *
638 * @param table The output table.
639 * @param reducer The reducer class to use.
640 * @param job The current job to adjust.
641 * @param partitioner Partitioner to use. Pass <code>null</code> to use
642 * default partitioner.
643 * @throws IOException When determining the region count fails.
644 */
645 public static void initTableReducerJob(String table,
646 Class<? extends TableReducer> reducer, Job job,
647 Class partitioner) throws IOException {
648 initTableReducerJob(table, reducer, job, partitioner, null, null, null);
649 }
650
651 /**
652 * Use this before submitting a TableReduce job. It will
653 * appropriately set up the JobConf.
654 *
655 * @param table The output table.
656 * @param reducer The reducer class to use.
657 * @param job The current job to adjust. Make sure the passed job is
658 * carrying all necessary HBase configuration.
659 * @param partitioner Partitioner to use. Pass <code>null</code> to use
660 * default partitioner.
661 * @param quorumAddress Distant cluster to write to; default is null for
662 * output to the cluster that is designated in <code>hbase-site.xml</code>.
663 * Set this String to the zookeeper ensemble of an alternate remote cluster
664 * when you would have the reduce write a cluster that is other than the
665 * default; e.g. copying tables between clusters, the source would be
666 * designated by <code>hbase-site.xml</code> and this param would have the
667 * ensemble address of the remote cluster. The format to pass is particular.
668 * Pass <code> <hbase.zookeeper.quorum>:<
669 * hbase.zookeeper.client.port>:<zookeeper.znode.parent>
670 * </code> such as <code>server,server2,server3:2181:/hbase</code>.
671 * @param serverClass redefined hbase.regionserver.class
672 * @param serverImpl redefined hbase.regionserver.impl
673 * @throws IOException When determining the region count fails.
674 */
675 public static void initTableReducerJob(String table,
676 Class<? extends TableReducer> reducer, Job job,
677 Class partitioner, String quorumAddress, String serverClass,
678 String serverImpl) throws IOException {
679 initTableReducerJob(table, reducer, job, partitioner, quorumAddress,
680 serverClass, serverImpl, true);
681 }
682
683 /**
684 * Use this before submitting a TableReduce job. It will
685 * appropriately set up the JobConf.
686 *
687 * @param table The output table.
688 * @param reducer The reducer class to use.
689 * @param job The current job to adjust. Make sure the passed job is
690 * carrying all necessary HBase configuration.
691 * @param partitioner Partitioner to use. Pass <code>null</code> to use
692 * default partitioner.
693 * @param quorumAddress Distant cluster to write to; default is null for
694 * output to the cluster that is designated in <code>hbase-site.xml</code>.
695 * Set this String to the zookeeper ensemble of an alternate remote cluster
696 * when you would have the reduce write a cluster that is other than the
697 * default; e.g. copying tables between clusters, the source would be
698 * designated by <code>hbase-site.xml</code> and this param would have the
699 * ensemble address of the remote cluster. The format to pass is particular.
700 * Pass <code> <hbase.zookeeper.quorum>:<
701 * hbase.zookeeper.client.port>:<zookeeper.znode.parent>
702 * </code> such as <code>server,server2,server3:2181:/hbase</code>.
703 * @param serverClass redefined hbase.regionserver.class
704 * @param serverImpl redefined hbase.regionserver.impl
705 * @param addDependencyJars upload HBase jars and jars for any of the configured
706 * job classes via the distributed cache (tmpjars).
707 * @throws IOException When determining the region count fails.
708 */
709 public static void initTableReducerJob(String table,
710 Class<? extends TableReducer> reducer, Job job,
711 Class partitioner, String quorumAddress, String serverClass,
712 String serverImpl, boolean addDependencyJars) throws IOException {
713
714 Configuration conf = job.getConfiguration();
715 HBaseConfiguration.merge(conf, HBaseConfiguration.create(conf));
716 job.setOutputFormatClass(TableOutputFormat.class);
717 if (reducer != null) job.setReducerClass(reducer);
718 conf.set(TableOutputFormat.OUTPUT_TABLE, table);
719 conf.setStrings("io.serializations", conf.get("io.serializations"),
720 MutationSerialization.class.getName(), ResultSerialization.class.getName());
721 // If passed a quorum/ensemble address, pass it on to TableOutputFormat.
722 if (quorumAddress != null) {
723 // Calling this will validate the format
724 ZKConfig.validateClusterKey(quorumAddress);
725 conf.set(TableOutputFormat.QUORUM_ADDRESS,quorumAddress);
726 }
727 if (serverClass != null && serverImpl != null) {
728 conf.set(TableOutputFormat.REGION_SERVER_CLASS, serverClass);
729 conf.set(TableOutputFormat.REGION_SERVER_IMPL, serverImpl);
730 }
731 job.setOutputKeyClass(ImmutableBytesWritable.class);
732 job.setOutputValueClass(Writable.class);
733 if (partitioner == HRegionPartitioner.class) {
734 job.setPartitionerClass(HRegionPartitioner.class);
735 int regions = MetaTableAccessor.getRegionCount(conf, TableName.valueOf(table));
736 if (job.getNumReduceTasks() > regions) {
737 job.setNumReduceTasks(regions);
738 }
739 } else if (partitioner != null) {
740 job.setPartitionerClass(partitioner);
741 }
742
743 if (addDependencyJars) {
744 addDependencyJars(job);
745 }
746
747 initCredentials(job);
748 }
749
750 /**
751 * Ensures that the given number of reduce tasks for the given job
752 * configuration does not exceed the number of regions for the given table.
753 *
754 * @param table The table to get the region count for.
755 * @param job The current job to adjust.
756 * @throws IOException When retrieving the table details fails.
757 */
758 public static void limitNumReduceTasks(String table, Job job)
759 throws IOException {
760 int regions =
761 MetaTableAccessor.getRegionCount(job.getConfiguration(), TableName.valueOf(table));
762 if (job.getNumReduceTasks() > regions)
763 job.setNumReduceTasks(regions);
764 }
765
766 /**
767 * Sets the number of reduce tasks for the given job configuration to the
768 * number of regions the given table has.
769 *
770 * @param table The table to get the region count for.
771 * @param job The current job to adjust.
772 * @throws IOException When retrieving the table details fails.
773 */
774 public static void setNumReduceTasks(String table, Job job)
775 throws IOException {
776 job.setNumReduceTasks(MetaTableAccessor.getRegionCount(job.getConfiguration(),
777 TableName.valueOf(table)));
778 }
779
780 /**
781 * Sets the number of rows to return and cache with each scanner iteration.
782 * Higher caching values will enable faster mapreduce jobs at the expense of
783 * requiring more heap to contain the cached rows.
784 *
785 * @param job The current job to adjust.
786 * @param batchSize The number of rows to return in batch with each scanner
787 * iteration.
788 */
789 public static void setScannerCaching(Job job, int batchSize) {
790 job.getConfiguration().setInt("hbase.client.scanner.caching", batchSize);
791 }
792
793 /**
794 * Add HBase and its dependencies (only) to the job configuration.
795 * <p>
796 * This is intended as a low-level API, facilitating code reuse between this
797 * class and its mapred counterpart. It also of use to external tools that
798 * need to build a MapReduce job that interacts with HBase but want
799 * fine-grained control over the jars shipped to the cluster.
800 * </p>
801 * @param conf The Configuration object to extend with dependencies.
802 * @see org.apache.hadoop.hbase.mapred.TableMapReduceUtil
803 * @see <a href="https://issues.apache.org/jira/browse/PIG-3285">PIG-3285</a>
804 */
805 public static void addHBaseDependencyJars(Configuration conf) throws IOException {
806
807 // PrefixTreeCodec is part of the hbase-prefix-tree module. If not included in MR jobs jar
808 // dependencies, MR jobs that write encoded hfiles will fail.
809 // We used reflection here so to prevent a circular module dependency.
810 // TODO - if we extract the MR into a module, make it depend on hbase-prefix-tree.
811 Class prefixTreeCodecClass = null;
812 try {
813 prefixTreeCodecClass =
814 Class.forName("org.apache.hadoop.hbase.codec.prefixtree.PrefixTreeCodec");
815 } catch (ClassNotFoundException e) {
816 // this will show up in unit tests but should not show in real deployments
817 LOG.warn("The hbase-prefix-tree module jar containing PrefixTreeCodec is not present." +
818 " Continuing without it.");
819 }
820
821 addDependencyJarsForClasses(conf,
822 // explicitly pull a class from each module
823 org.apache.hadoop.hbase.HConstants.class, // hbase-common
824 org.apache.hadoop.hbase.protobuf.generated.ClientProtos.class, // hbase-protocol
825 org.apache.hadoop.hbase.client.Put.class, // hbase-client
826 org.apache.hadoop.hbase.CompatibilityFactory.class, // hbase-hadoop-compat
827 org.apache.hadoop.hbase.mapreduce.JobUtil.class, // hbase-hadoop2-compat
828 org.apache.hadoop.hbase.mapreduce.TableMapper.class, // hbase-server
829 org.apache.hadoop.hbase.metrics.impl.FastLongHistogram.class, // hbase-metrics
830 org.apache.hadoop.hbase.metrics.Snapshot.class, // hbase-metrics-api
831 org.apache.hbase.thirdparty.com.google.gson.GsonBuilder.class, // hbase-shaded-gson
832 prefixTreeCodecClass, // hbase-prefix-tree (if null will be skipped)
833 // pull necessary dependencies
834 org.apache.zookeeper.ZooKeeper.class,
835 io.netty.channel.Channel.class,
836 com.google.protobuf.Message.class,
837 com.google.common.collect.Lists.class,
838 org.apache.htrace.Trace.class,
839 com.yammer.metrics.core.MetricsRegistry.class);
840 }
841
842 /**
843 * Returns a classpath string built from the content of the "tmpjars" value in {@code conf}.
844 * Also exposed to shell scripts via `bin/hbase mapredcp`.
845 */
846 public static String buildDependencyClasspath(Configuration conf) {
847 if (conf == null) {
848 throw new IllegalArgumentException("Must provide a configuration object.");
849 }
850 Set<String> paths = new HashSet<String>(conf.getStringCollection("tmpjars"));
851 if (paths.size() == 0) {
852 throw new IllegalArgumentException("Configuration contains no tmpjars.");
853 }
854 StringBuilder sb = new StringBuilder();
855 for (String s : paths) {
856 // entries can take the form 'file:/path/to/file.jar'.
857 int idx = s.indexOf(":");
858 if (idx != -1) s = s.substring(idx + 1);
859 if (sb.length() > 0) sb.append(File.pathSeparator);
860 sb.append(s);
861 }
862 return sb.toString();
863 }
864
865 /**
866 * Add the HBase dependency jars as well as jars for any of the configured
867 * job classes to the job configuration, so that JobClient will ship them
868 * to the cluster and add them to the DistributedCache.
869 */
870 public static void addDependencyJars(Job job) throws IOException {
871 addHBaseDependencyJars(job.getConfiguration());
872 try {
873 addDependencyJarsForClasses(job.getConfiguration(),
874 // when making changes here, consider also mapred.TableMapReduceUtil
875 // pull job classes
876 job.getMapOutputKeyClass(),
877 job.getMapOutputValueClass(),
878 job.getInputFormatClass(),
879 job.getOutputKeyClass(),
880 job.getOutputValueClass(),
881 job.getOutputFormatClass(),
882 job.getPartitionerClass(),
883 job.getCombinerClass());
884 } catch (ClassNotFoundException e) {
885 throw new IOException(e);
886 }
887 }
888
889 /**
890 * Add the jars containing the given classes to the job's configuration
891 * such that JobClient will ship them to the cluster and add them to
892 * the DistributedCache.
893 * @deprecated rely on {@link #addDependencyJars(Job)} instead.
894 */
895 @Deprecated
896 public static void addDependencyJars(Configuration conf,
897 Class<?>... classes) throws IOException {
898 LOG.warn("The addDependencyJars(Configuration, Class<?>...) method has been deprecated since it"
899 + " is easy to use incorrectly. Most users should rely on addDependencyJars(Job) " +
900 "instead. See HBASE-8386 for more details.");
901 addDependencyJarsForClasses(conf, classes);
902 }
903
904 /**
905 * Add the jars containing the given classes to the job's configuration
906 * such that JobClient will ship them to the cluster and add them to
907 * the DistributedCache.
908 *
909 * N.B. that this method at most adds one jar per class given. If there is more than one
910 * jar available containing a class with the same name as a given class, we don't define
911 * which of those jars might be chosen.
912 *
913 * @param conf The Hadoop Configuration to modify
914 * @param classes will add just those dependencies needed to find the given classes
915 * @throws IOException if an underlying library call fails.
916 */
917 @InterfaceAudience.Private
918 public static void addDependencyJarsForClasses(Configuration conf,
919 Class<?>... classes) throws IOException {
920
921 FileSystem localFs = FileSystem.getLocal(conf);
922 Set<String> jars = new HashSet<String>();
923 // Add jars that are already in the tmpjars variable
924 jars.addAll(conf.getStringCollection("tmpjars"));
925
926 // add jars as we find them to a map of contents jar name so that we can avoid
927 // creating new jars for classes that have already been packaged.
928 Map<String, String> packagedClasses = new HashMap<String, String>();
929
930 // Add jars containing the specified classes
931 for (Class<?> clazz : classes) {
932 if (clazz == null) continue;
933
934 Path path = findOrCreateJar(clazz, localFs, packagedClasses);
935 if (path == null) {
936 LOG.warn("Could not find jar for class " + clazz +
937 " in order to ship it to the cluster.");
938 continue;
939 }
940 if (!localFs.exists(path)) {
941 LOG.warn("Could not validate jar file " + path + " for class "
942 + clazz);
943 continue;
944 }
945 jars.add(path.toString());
946 }
947 if (jars.isEmpty()) return;
948
949 conf.set("tmpjars", StringUtils.arrayToString(jars.toArray(new String[jars.size()])));
950 }
951
952 /**
953 * Finds the Jar for a class or creates it if it doesn't exist. If the class is in
954 * a directory in the classpath, it creates a Jar on the fly with the
955 * contents of the directory and returns the path to that Jar. If a Jar is
956 * created, it is created in the system temporary directory. Otherwise,
957 * returns an existing jar that contains a class of the same name. Maintains
958 * a mapping from jar contents to the tmp jar created.
959 * @param my_class the class to find.
960 * @param fs the FileSystem with which to qualify the returned path.
961 * @param packagedClasses a map of class name to path.
962 * @return a jar file that contains the class.
963 * @throws IOException
964 */
965 private static Path findOrCreateJar(Class<?> my_class, FileSystem fs,
966 Map<String, String> packagedClasses)
967 throws IOException {
968 // attempt to locate an existing jar for the class.
969 String jar = findContainingJar(my_class, packagedClasses);
970 if (null == jar || jar.isEmpty()) {
971 jar = getJar(my_class);
972 updateMap(jar, packagedClasses);
973 }
974
975 if (null == jar || jar.isEmpty()) {
976 return null;
977 }
978
979 LOG.debug(String.format("For class %s, using jar %s", my_class.getName(), jar));
980 return new Path(jar).makeQualified(fs);
981 }
982
983 /**
984 * Add entries to <code>packagedClasses</code> corresponding to class files
985 * contained in <code>jar</code>.
986 * @param jar The jar who's content to list.
987 * @param packagedClasses map[class -> jar]
988 */
989 private static void updateMap(String jar, Map<String, String> packagedClasses) throws IOException {
990 if (null == jar || jar.isEmpty()) {
991 return;
992 }
993 ZipFile zip = null;
994 try {
995 zip = new ZipFile(jar);
996 for (Enumeration<? extends ZipEntry> iter = zip.entries(); iter.hasMoreElements();) {
997 ZipEntry entry = iter.nextElement();
998 if (entry.getName().endsWith("class")) {
999 packagedClasses.put(entry.getName(), jar);
1000 }
1001 }
1002 } finally {
1003 if (null != zip) zip.close();
1004 }
1005 }
1006
1007 /**
1008 * Find a jar that contains a class of the same name, if any. It will return
1009 * a jar file, even if that is not the first thing on the class path that
1010 * has a class with the same name. Looks first on the classpath and then in
1011 * the <code>packagedClasses</code> map.
1012 * @param my_class the class to find.
1013 * @return a jar file that contains the class, or null.
1014 * @throws IOException
1015 */
1016 private static String findContainingJar(Class<?> my_class, Map<String, String> packagedClasses)
1017 throws IOException {
1018 ClassLoader loader = my_class.getClassLoader();
1019
1020 String class_file = my_class.getName().replaceAll("\\.", "/") + ".class";
1021
1022 if (loader != null) {
1023 // first search the classpath
1024 for (Enumeration<URL> itr = loader.getResources(class_file); itr.hasMoreElements();) {
1025 URL url = itr.nextElement();
1026 if ("jar".equals(url.getProtocol())) {
1027 String toReturn = url.getPath();
1028 if (toReturn.startsWith("file:")) {
1029 toReturn = toReturn.substring("file:".length());
1030 }
1031 // URLDecoder is a misnamed class, since it actually decodes
1032 // x-www-form-urlencoded MIME type rather than actual
1033 // URL encoding (which the file path has). Therefore it would
1034 // decode +s to ' 's which is incorrect (spaces are actually
1035 // either unencoded or encoded as "%20"). Replace +s first, so
1036 // that they are kept sacred during the decoding process.
1037 toReturn = toReturn.replaceAll("\\+", "%2B");
1038 toReturn = URLDecoder.decode(toReturn, "UTF-8");
1039 return toReturn.replaceAll("!.*$", "");
1040 }
1041 }
1042 }
1043
1044 // now look in any jars we've packaged using JarFinder. Returns null when
1045 // no jar is found.
1046 return packagedClasses.get(class_file);
1047 }
1048
1049 /**
1050 * Invoke 'getJar' on a custom JarFinder implementation. Useful for some job
1051 * configuration contexts (HBASE-8140) and also for testing on MRv2.
1052 * check if we have HADOOP-9426.
1053 * @param my_class the class to find.
1054 * @return a jar file that contains the class, or null.
1055 */
1056 private static String getJar(Class<?> my_class) {
1057 String ret = null;
1058 try {
1059 ret = JarFinder.getJar(my_class);
1060 } catch (Exception e) {
1061 // toss all other exceptions, related to reflection failure
1062 throw new RuntimeException("getJar invocation failed.", e);
1063 }
1064
1065 return ret;
1066 }
1067 }