1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.hadoop.hbase.mapreduce;
20
21 import static java.lang.String.format;
22
23 import java.io.FileNotFoundException;
24 import java.io.IOException;
25 import java.io.InterruptedIOException;
26 import java.nio.ByteBuffer;
27 import java.util.ArrayList;
28 import java.util.Arrays;
29 import java.util.Collection;
30 import java.util.Deque;
31 import java.util.HashMap;
32 import java.util.HashSet;
33 import java.util.Iterator;
34 import java.util.LinkedList;
35 import java.util.List;
36 import java.util.Map;
37 import java.util.Map.Entry;
38 import java.util.Set;
39 import java.util.TreeMap;
40 import java.util.UUID;
41 import java.util.concurrent.Callable;
42 import java.util.concurrent.ExecutionException;
43 import java.util.concurrent.ExecutorService;
44 import java.util.concurrent.Future;
45 import java.util.concurrent.LinkedBlockingQueue;
46 import java.util.concurrent.ThreadPoolExecutor;
47 import java.util.concurrent.TimeUnit;
48
49 import org.apache.commons.lang.mutable.MutableInt;
50 import org.apache.commons.logging.Log;
51 import org.apache.commons.logging.LogFactory;
52 import org.apache.hadoop.conf.Configuration;
53 import org.apache.hadoop.conf.Configured;
54 import org.apache.hadoop.fs.FileStatus;
55 import org.apache.hadoop.fs.FileSystem;
56 import org.apache.hadoop.fs.Path;
57 import org.apache.hadoop.fs.permission.FsPermission;
58 import org.apache.hadoop.hbase.HBaseConfiguration;
59 import org.apache.hadoop.hbase.HColumnDescriptor;
60 import org.apache.hadoop.hbase.HConstants;
61 import org.apache.hadoop.hbase.HTableDescriptor;
62 import org.apache.hadoop.hbase.TableName;
63 import org.apache.hadoop.hbase.TableNotFoundException;
64 import org.apache.hadoop.hbase.classification.InterfaceAudience;
65 import org.apache.hadoop.hbase.classification.InterfaceStability;
66 import org.apache.hadoop.hbase.client.Admin;
67 import org.apache.hadoop.hbase.client.ClusterConnection;
68 import org.apache.hadoop.hbase.client.Connection;
69 import org.apache.hadoop.hbase.client.ConnectionFactory;
70 import org.apache.hadoop.hbase.client.HBaseAdmin;
71 import org.apache.hadoop.hbase.client.HConnection;
72 import org.apache.hadoop.hbase.client.HTable;
73 import org.apache.hadoop.hbase.client.RegionLocator;
74 import org.apache.hadoop.hbase.client.RegionServerCallable;
75 import org.apache.hadoop.hbase.client.RpcRetryingCallerFactory;
76 import org.apache.hadoop.hbase.client.Table;
77 import org.apache.hadoop.hbase.client.coprocessor.SecureBulkLoadClient;
78 import org.apache.hadoop.hbase.coprocessor.CoprocessorHost;
79 import org.apache.hadoop.hbase.io.HFileLink;
80 import org.apache.hadoop.hbase.io.HalfStoreFileReader;
81 import org.apache.hadoop.hbase.io.Reference;
82 import org.apache.hadoop.hbase.io.compress.Compression.Algorithm;
83 import org.apache.hadoop.hbase.io.hfile.CacheConfig;
84 import org.apache.hadoop.hbase.io.hfile.HFile;
85 import org.apache.hadoop.hbase.io.hfile.HFileContext;
86 import org.apache.hadoop.hbase.io.hfile.HFileContextBuilder;
87 import org.apache.hadoop.hbase.io.hfile.HFileDataBlockEncoder;
88 import org.apache.hadoop.hbase.io.hfile.HFileScanner;
89 import org.apache.hadoop.hbase.protobuf.ProtobufUtil;
90 import org.apache.hadoop.hbase.regionserver.BloomType;
91 import org.apache.hadoop.hbase.regionserver.HStore;
92 import org.apache.hadoop.hbase.regionserver.StoreFile;
93 import org.apache.hadoop.hbase.regionserver.StoreFileInfo;
94 import org.apache.hadoop.hbase.security.UserProvider;
95 import org.apache.hadoop.hbase.security.access.SecureBulkLoadEndpoint;
96 import org.apache.hadoop.hbase.security.token.FsDelegationToken;
97 import org.apache.hadoop.hbase.util.Bytes;
98 import org.apache.hadoop.hbase.util.FSHDFSUtils;
99 import org.apache.hadoop.hbase.util.Pair;
100 import org.apache.hadoop.util.Tool;
101 import org.apache.hadoop.util.ToolRunner;
102
103 import com.google.common.collect.HashMultimap;
104 import com.google.common.collect.Multimap;
105 import com.google.common.collect.Multimaps;
106 import com.google.common.util.concurrent.ThreadFactoryBuilder;
107
108
109
110
111
112 @InterfaceAudience.Public
113 @InterfaceStability.Stable
114 public class LoadIncrementalHFiles extends Configured implements Tool {
115 private static final Log LOG = LogFactory.getLog(LoadIncrementalHFiles.class);
116 private Admin hbAdmin;
117
118 public static final String NAME = "completebulkload";
119 public static final String MAX_FILES_PER_REGION_PER_FAMILY
120 = "hbase.mapreduce.bulkload.max.hfiles.perRegion.perFamily";
121 private static final String ASSIGN_SEQ_IDS = "hbase.mapreduce.bulkload.assign.sequenceNumbers";
122 public final static String CREATE_TABLE_CONF_KEY = "create.table";
123
124
125
126 final static String TMP_DIR = ".tmp";
127
128 private int maxFilesPerRegionPerFamily;
129 private boolean assignSeqIds;
130
131
132 private FileSystem fs;
133
134 private FsDelegationToken fsDelegationToken;
135 private String bulkToken;
136 private UserProvider userProvider;
137 private int nrThreads;
138
139 private List<String> clusterIds = new ArrayList<>();
140
141 private LoadIncrementalHFiles() {}
142
143 public LoadIncrementalHFiles(Configuration conf) throws Exception {
144 super(conf);
145 initialize();
146 }
147
148 public void setClusterIds(List<String> clusterIds) {
149 this.clusterIds = clusterIds;
150 }
151
152 private void initialize() throws Exception {
153 if (hbAdmin == null) {
154
155 setConf(HBaseConfiguration.create(getConf()));
156 Configuration conf = getConf();
157
158 conf.setFloat(HConstants.HFILE_BLOCK_CACHE_SIZE_KEY, 0);
159 this.hbAdmin = new HBaseAdmin(conf);
160 this.userProvider = UserProvider.instantiate(conf);
161 this.fsDelegationToken = new FsDelegationToken(userProvider, "renewer");
162 assignSeqIds = conf.getBoolean(ASSIGN_SEQ_IDS, true);
163 maxFilesPerRegionPerFamily = conf.getInt(MAX_FILES_PER_REGION_PER_FAMILY, 32);
164 nrThreads = conf.getInt("hbase.loadincremental.threads.max",
165 Runtime.getRuntime().availableProcessors());
166 }
167 }
168
169 private void usage() {
170 System.err.println("usage: " + NAME + " /path/to/hfileoutputformat-output tablename" + "\n -D"
171 + CREATE_TABLE_CONF_KEY + "=no - can be used to avoid creation of table by this tool\n"
172 + " Note: if you set this to 'no', then the target table must already exist in HBase\n"
173 + "\n");
174 }
175
176 private static interface BulkHFileVisitor<TFamily> {
177 TFamily bulkFamily(final byte[] familyName)
178 throws IOException;
179 void bulkHFile(final TFamily family, final FileStatus hfileStatus)
180 throws IOException;
181 }
182
183
184
185
186
187 private static <TFamily> void visitBulkHFiles(final FileSystem fs, final Path bulkDir,
188 final BulkHFileVisitor<TFamily> visitor) throws IOException {
189 visitBulkHFiles(fs, bulkDir, visitor, true);
190 }
191
192
193
194
195
196
197
198 private static <TFamily> void visitBulkHFiles(final FileSystem fs, final Path bulkDir,
199 final BulkHFileVisitor<TFamily> visitor, final boolean validateHFile) throws IOException {
200 if (!fs.exists(bulkDir)) {
201 throw new FileNotFoundException("Bulkload dir " + bulkDir + " not found");
202 }
203
204 FileStatus[] familyDirStatuses = fs.listStatus(bulkDir);
205 if (familyDirStatuses == null) {
206 throw new FileNotFoundException("No families found in " + bulkDir);
207 }
208
209 for (FileStatus familyStat : familyDirStatuses) {
210 if (!familyStat.isDirectory()) {
211 LOG.warn("Skipping non-directory " + familyStat.getPath());
212 continue;
213 }
214 Path familyDir = familyStat.getPath();
215 byte[] familyName = familyDir.getName().getBytes();
216
217 try {
218 HColumnDescriptor.isLegalFamilyName(familyName);
219 }
220 catch (IllegalArgumentException e) {
221 LOG.warn("Skipping invalid " + familyStat.getPath());
222 continue;
223 }
224 TFamily family = visitor.bulkFamily(familyName);
225
226 FileStatus[] hfileStatuses = fs.listStatus(familyDir);
227 for (FileStatus hfileStatus : hfileStatuses) {
228 if (!fs.isFile(hfileStatus.getPath())) {
229 LOG.warn("Skipping non-file " + hfileStatus);
230 continue;
231 }
232
233 Path hfile = hfileStatus.getPath();
234
235 String fileName = hfile.getName();
236 if (fileName.startsWith("_")) {
237 continue;
238 }
239 if (StoreFileInfo.isReference(fileName)) {
240 LOG.warn("Skipping reference " + fileName);
241 continue;
242 }
243 if (HFileLink.isHFileLink(fileName)) {
244 LOG.warn("Skipping HFileLink " + fileName);
245 continue;
246 }
247
248
249 if (validateHFile) {
250 try {
251 if (!HFile.isHFileFormat(fs, hfile)) {
252 LOG.warn("the file " + hfile + " doesn't seems to be an hfile. skipping");
253 continue;
254 }
255 } catch (FileNotFoundException e) {
256 LOG.warn("the file " + hfile + " was removed");
257 continue;
258 }
259 }
260
261 visitor.bulkHFile(family, hfileStatus);
262 }
263 }
264 }
265
266
267
268
269
270
271
272
273
274 public static class LoadQueueItem {
275 final byte[] family;
276 final Path hfilePath;
277
278 public LoadQueueItem(byte[] family, Path hfilePath) {
279 this.family = family;
280 this.hfilePath = hfilePath;
281 }
282
283 @Override
284 public String toString() {
285 return "family:"+ Bytes.toString(family) + " path:" + hfilePath.toString();
286 }
287 }
288
289
290
291
292
293 private void discoverLoadQueue(final Deque<LoadQueueItem> ret, final Path hfofDir,
294 final boolean validateHFile) throws IOException {
295 fs = hfofDir.getFileSystem(getConf());
296 visitBulkHFiles(fs, hfofDir, new BulkHFileVisitor<byte[]>() {
297 @Override
298 public byte[] bulkFamily(final byte[] familyName) {
299 return familyName;
300 }
301 @Override
302 public void bulkHFile(final byte[] family, final FileStatus hfile) throws IOException {
303 long length = hfile.getLen();
304 if (length > getConf().getLong(HConstants.HREGION_MAX_FILESIZE,
305 HConstants.DEFAULT_MAX_FILE_SIZE)) {
306 LOG.warn("Trying to bulk load hfile " + hfile.getPath() + " with size: " +
307 length + " bytes can be problematic as it may lead to oversplitting.");
308 }
309 ret.add(new LoadQueueItem(family, hfile.getPath()));
310 }
311 }, validateHFile);
312 }
313
314
315
316
317
318
319
320
321
322
323
324
325
326 @SuppressWarnings("deprecation")
327 @Deprecated
328 public void doBulkLoad(Path hfofDir, final HTable table)
329 throws TableNotFoundException, IOException
330 {
331 Admin admin = null;
332 Table t = table;
333 Connection conn = table.getConnection();
334 boolean closeConnWhenFinished = false;
335 try {
336 if (conn instanceof ClusterConnection && ((ClusterConnection) conn).isManaged()) {
337 LOG.warn("managed connection cannot be used for bulkload. Creating unmanaged connection.");
338
339 conn = ConnectionFactory.createConnection(table.getConfiguration());
340 t = conn.getTable(table.getName());
341 closeConnWhenFinished = true;
342 if (conn instanceof ClusterConnection && ((ClusterConnection) conn).isManaged()) {
343 throw new RuntimeException("Failed to create unmanaged connection.");
344 }
345 admin = conn.getAdmin();
346 } else {
347 admin = conn.getAdmin();
348 }
349 try (RegionLocator rl = conn.getRegionLocator(t.getName())) {
350 doBulkLoad(hfofDir, admin, t, rl);
351 }
352 } finally {
353 if (admin != null) admin.close();
354 if (closeConnWhenFinished) {
355 t.close();
356 conn.close();
357 }
358 }
359 }
360
361
362
363
364
365
366
367
368
369
370 public void doBulkLoad(Path hfofDir, final Admin admin, Table table,
371 RegionLocator regionLocator) throws TableNotFoundException, IOException {
372
373 if (!admin.isTableAvailable(regionLocator.getName())) {
374 throw new TableNotFoundException("Table " + table.getName() + " is not currently available.");
375 }
376
377 ExecutorService pool = createExecutorService();
378
379
380
381 Deque<LoadQueueItem> queue = new LinkedList<LoadQueueItem>();
382 try {
383
384
385
386
387 boolean validateHFile = getConf().getBoolean("hbase.loadincremental.validate.hfile", true);
388 if(!validateHFile) {
389 LOG.warn("You are skipping HFiles validation, it might cause some data loss if files " +
390 "are not correct. If you fail to read data from your table after using this " +
391 "option, consider removing the files and bulkload again without this option. " +
392 "See HBASE-13985");
393 }
394 prepareHFileQueue(hfofDir, table, queue, validateHFile);
395
396 int count = 0;
397
398 if (queue.isEmpty()) {
399 LOG.warn("Bulk load operation did not find any files to load in " +
400 "directory " + hfofDir.toUri() + ". Does it contain files in " +
401 "subdirectories that correspond to column family names?");
402 return;
403 }
404
405
406
407
408 fsDelegationToken.acquireDelegationToken(fs);
409 if(isSecureBulkLoadEndpointAvailable()) {
410 bulkToken = new SecureBulkLoadClient(table).prepareBulkLoad(table.getName());
411 }
412
413
414 while (!queue.isEmpty()) {
415
416 final Pair<byte[][], byte[][]> startEndKeys = regionLocator.getStartEndKeys();
417 if (count != 0) {
418 LOG.info("Split occured while grouping HFiles, retry attempt " +
419 + count + " with " + queue.size() + " files remaining to group or split");
420 }
421
422 int maxRetries = getConf().getInt(HConstants.BULKLOAD_MAX_RETRIES_NUMBER, 10);
423 maxRetries = Math.max(maxRetries, startEndKeys.getFirst().length + 1);
424 if (maxRetries != 0 && count >= maxRetries) {
425 throw new IOException("Retry attempted " + count +
426 " times without completing, bailing out");
427 }
428 count++;
429
430
431 Multimap<ByteBuffer, LoadQueueItem> regionGroups = groupOrSplitPhase(table,
432 pool, queue, startEndKeys);
433
434 if (!checkHFilesCountPerRegionPerFamily(regionGroups)) {
435
436 throw new IOException("Trying to load more than " + maxFilesPerRegionPerFamily
437 + " hfiles to one family of one region");
438 }
439
440 bulkLoadPhase(table, admin.getConnection(), pool, queue, regionGroups);
441
442
443
444
445 }
446
447 } finally {
448 fsDelegationToken.releaseDelegationToken();
449 if(bulkToken != null) {
450 new SecureBulkLoadClient(table).cleanupBulkLoad(bulkToken);
451 }
452 pool.shutdown();
453 if (queue != null && !queue.isEmpty()) {
454 StringBuilder err = new StringBuilder();
455 err.append("-------------------------------------------------\n");
456 err.append("Bulk load aborted with some files not yet loaded:\n");
457 err.append("-------------------------------------------------\n");
458 for (LoadQueueItem q : queue) {
459 err.append(" ").append(q.hfilePath).append('\n');
460 }
461 LOG.error(err);
462 }
463 }
464
465 if (queue != null && !queue.isEmpty()) {
466 throw new RuntimeException("Bulk load aborted with some files not yet loaded."
467 + "Please check log for more details.");
468 }
469 }
470
471
472
473
474
475
476
477
478
479
480
481 public void prepareHFileQueue(Path hfilesDir, Table table, Deque<LoadQueueItem> queue,
482 boolean validateHFile) throws IOException {
483 discoverLoadQueue(queue, hfilesDir, validateHFile);
484 validateFamiliesInHFiles(table, queue);
485 }
486
487
488 private ExecutorService createExecutorService() {
489 ThreadFactoryBuilder builder = new ThreadFactoryBuilder();
490 builder.setNameFormat("LoadIncrementalHFiles-%1$d");
491 ExecutorService pool = new ThreadPoolExecutor(nrThreads, nrThreads, 60, TimeUnit.SECONDS,
492 new LinkedBlockingQueue<Runnable>(), builder.build());
493 ((ThreadPoolExecutor) pool).allowCoreThreadTimeOut(true);
494 return pool;
495 }
496
497
498
499
500 private void validateFamiliesInHFiles(Table table, Deque<LoadQueueItem> queue)
501 throws IOException {
502 Collection<HColumnDescriptor> families = table.getTableDescriptor().getFamilies();
503 List<String> familyNames = new ArrayList<String>(families.size());
504 for (HColumnDescriptor family : families) {
505 familyNames.add(family.getNameAsString());
506 }
507 List<String> unmatchedFamilies = new ArrayList<String>();
508 Iterator<LoadQueueItem> queueIter = queue.iterator();
509 while (queueIter.hasNext()) {
510 LoadQueueItem lqi = queueIter.next();
511 String familyNameInHFile = Bytes.toString(lqi.family);
512 if (!familyNames.contains(familyNameInHFile)) {
513 unmatchedFamilies.add(familyNameInHFile);
514 }
515 }
516 if (unmatchedFamilies.size() > 0) {
517 String msg =
518 "Unmatched family names found: unmatched family names in HFiles to be bulkloaded: "
519 + unmatchedFamilies + "; valid family names of table " + table.getName() + " are: "
520 + familyNames;
521 LOG.error(msg);
522 throw new IOException(msg);
523 }
524 }
525
526
527
528
529
530
531
532
533
534
535
536 public void loadHFileQueue(final Table table, final Connection conn, Deque<LoadQueueItem> queue,
537 Pair<byte[][], byte[][]> startEndKeys) throws IOException {
538 ExecutorService pool = null;
539 try {
540 pool = createExecutorService();
541 Multimap<ByteBuffer, LoadQueueItem> regionGroups =
542 groupOrSplitPhase(table, pool, queue, startEndKeys);
543 bulkLoadPhase(table, conn, pool, queue, regionGroups);
544 } finally {
545 if (pool != null) {
546 pool.shutdown();
547 }
548 }
549 }
550
551
552
553
554
555
556 protected void bulkLoadPhase(final Table table, final Connection conn,
557 ExecutorService pool, Deque<LoadQueueItem> queue,
558 final Multimap<ByteBuffer, LoadQueueItem> regionGroups) throws IOException {
559
560 Set<Future<List<LoadQueueItem>>> loadingFutures = new HashSet<Future<List<LoadQueueItem>>>();
561 for (Entry<ByteBuffer, ? extends Collection<LoadQueueItem>> e: regionGroups.asMap().entrySet()) {
562 final byte[] first = e.getKey().array();
563 final Collection<LoadQueueItem> lqis = e.getValue();
564
565 final Callable<List<LoadQueueItem>> call = new Callable<List<LoadQueueItem>>() {
566 @Override
567 public List<LoadQueueItem> call() throws Exception {
568 List<LoadQueueItem> toRetry =
569 tryAtomicRegionLoad(conn, table.getName(), first, lqis);
570 return toRetry;
571 }
572 };
573 loadingFutures.add(pool.submit(call));
574 }
575
576
577 for (Future<List<LoadQueueItem>> future : loadingFutures) {
578 try {
579 List<LoadQueueItem> toRetry = future.get();
580
581
582 queue.addAll(toRetry);
583
584 } catch (ExecutionException e1) {
585 Throwable t = e1.getCause();
586 if (t instanceof IOException) {
587
588
589 throw new IOException("BulkLoad encountered an unrecoverable problem", t);
590 }
591 LOG.error("Unexpected execution exception during bulk load", e1);
592 throw new IllegalStateException(t);
593 } catch (InterruptedException e1) {
594 LOG.error("Unexpected interrupted exception during bulk load", e1);
595 throw (InterruptedIOException)new InterruptedIOException().initCause(e1);
596 }
597 }
598 }
599
600 private boolean checkHFilesCountPerRegionPerFamily(
601 final Multimap<ByteBuffer, LoadQueueItem> regionGroups) {
602 for (Entry<ByteBuffer,
603 ? extends Collection<LoadQueueItem>> e: regionGroups.asMap().entrySet()) {
604 final Collection<LoadQueueItem> lqis = e.getValue();
605 HashMap<byte[], MutableInt> filesMap = new HashMap<byte[], MutableInt>();
606 for (LoadQueueItem lqi: lqis) {
607 MutableInt count = filesMap.get(lqi.family);
608 if (count == null) {
609 count = new MutableInt();
610 filesMap.put(lqi.family, count);
611 }
612 count.increment();
613 if (count.intValue() > maxFilesPerRegionPerFamily) {
614 LOG.error("Trying to load more than " + maxFilesPerRegionPerFamily
615 + " hfiles to family " + Bytes.toStringBinary(lqi.family)
616 + " of region with start key "
617 + Bytes.toStringBinary(e.getKey()));
618 return false;
619 }
620 }
621 }
622 return true;
623 }
624
625
626
627
628
629 private Multimap<ByteBuffer, LoadQueueItem> groupOrSplitPhase(final Table table,
630 ExecutorService pool, Deque<LoadQueueItem> queue,
631 final Pair<byte[][], byte[][]> startEndKeys) throws IOException {
632
633
634 Multimap<ByteBuffer, LoadQueueItem> rgs = HashMultimap.create();
635 final Multimap<ByteBuffer, LoadQueueItem> regionGroups = Multimaps.synchronizedMultimap(rgs);
636
637
638 Set<Future<List<LoadQueueItem>>> splittingFutures = new HashSet<Future<List<LoadQueueItem>>>();
639 while (!queue.isEmpty()) {
640 final LoadQueueItem item = queue.remove();
641
642 final Callable<List<LoadQueueItem>> call = new Callable<List<LoadQueueItem>>() {
643 @Override
644 public List<LoadQueueItem> call() throws Exception {
645 List<LoadQueueItem> splits = groupOrSplit(regionGroups, item, table, startEndKeys);
646 return splits;
647 }
648 };
649 splittingFutures.add(pool.submit(call));
650 }
651
652
653 for (Future<List<LoadQueueItem>> lqis : splittingFutures) {
654 try {
655 List<LoadQueueItem> splits = lqis.get();
656 if (splits != null) {
657 queue.addAll(splits);
658 }
659 } catch (ExecutionException e1) {
660 Throwable t = e1.getCause();
661 if (t instanceof IOException) {
662 LOG.error("IOException during splitting", e1);
663 throw (IOException)t;
664 }
665 LOG.error("Unexpected execution exception during splitting", e1);
666 throw new IllegalStateException(t);
667 } catch (InterruptedException e1) {
668 LOG.error("Unexpected interrupted exception during splitting", e1);
669 throw (InterruptedIOException)new InterruptedIOException().initCause(e1);
670 }
671 }
672 return regionGroups;
673 }
674
675
676 private String getUniqueName() {
677 return UUID.randomUUID().toString().replaceAll("-", "");
678 }
679
680 protected List<LoadQueueItem> splitStoreFile(final LoadQueueItem item,
681 final Table table, byte[] startKey,
682 byte[] splitKey) throws IOException {
683 final Path hfilePath = item.hfilePath;
684
685 Path tmpDir = item.hfilePath.getParent();
686 if (!tmpDir.getName().equals(TMP_DIR)) {
687 tmpDir = new Path(tmpDir, TMP_DIR);
688 }
689
690 LOG.info("HFile at " + hfilePath + " no longer fits inside a single " +
691 "region. Splitting...");
692
693 String uniqueName = getUniqueName();
694 HColumnDescriptor familyDesc = table.getTableDescriptor().getFamily(item.family);
695
696 Path botOut = new Path(tmpDir, uniqueName + ".bottom");
697 Path topOut = new Path(tmpDir, uniqueName + ".top");
698 splitStoreFile(getConf(), hfilePath, familyDesc, splitKey, botOut, topOut);
699
700 FileSystem fs = tmpDir.getFileSystem(getConf());
701 fs.setPermission(tmpDir, FsPermission.valueOf("-rwxrwxrwx"));
702 fs.setPermission(botOut, FsPermission.valueOf("-rwxrwxrwx"));
703 fs.setPermission(topOut, FsPermission.valueOf("-rwxrwxrwx"));
704
705
706
707 List<LoadQueueItem> lqis = new ArrayList<LoadQueueItem>(2);
708 lqis.add(new LoadQueueItem(item.family, botOut));
709 lqis.add(new LoadQueueItem(item.family, topOut));
710
711
712
713
714 try {
715 tmpDir = item.hfilePath.getParent();
716 if (tmpDir.getName().equals(TMP_DIR)) {
717 fs.delete(item.hfilePath, false);
718 }
719 } catch (IOException e) {
720 LOG.warn("Unable to delete temporary split file " + item.hfilePath);
721 }
722 LOG.info("Successfully split into new HFiles " + botOut + " and " + topOut);
723 return lqis;
724 }
725
726
727
728
729
730
731
732
733
734
735 protected List<LoadQueueItem> groupOrSplit(Multimap<ByteBuffer, LoadQueueItem> regionGroups,
736 final LoadQueueItem item, final Table table,
737 final Pair<byte[][], byte[][]> startEndKeys)
738 throws IOException {
739 final Path hfilePath = item.hfilePath;
740
741 if (fs == null) {
742 fs = hfilePath.getFileSystem(getConf());
743 }
744 HFile.Reader hfr = HFile.createReader(fs, hfilePath,
745 new CacheConfig(getConf()), getConf());
746 final byte[] first, last;
747 try {
748 hfr.loadFileInfo();
749 first = hfr.getFirstRowKey();
750 last = hfr.getLastRowKey();
751 } finally {
752 hfr.close();
753 }
754
755 LOG.info("Trying to load hfile=" + hfilePath +
756 " first=" + Bytes.toStringBinary(first) +
757 " last=" + Bytes.toStringBinary(last));
758 if (first == null || last == null) {
759 assert first == null && last == null;
760
761 LOG.info("hfile " + hfilePath + " has no entries, skipping");
762 return null;
763 }
764 if (Bytes.compareTo(first, last) > 0) {
765 throw new IllegalArgumentException(
766 "Invalid range: " + Bytes.toStringBinary(first) +
767 " > " + Bytes.toStringBinary(last));
768 }
769 int idx = Arrays.binarySearch(startEndKeys.getFirst(), first,
770 Bytes.BYTES_COMPARATOR);
771 if (idx < 0) {
772
773
774 idx = -(idx + 1) - 1;
775 }
776 final int indexForCallable = idx;
777
778
779
780
781
782
783 if (indexForCallable < 0) {
784 throw new IOException("The first region info for table "
785 + table.getName()
786 + " can't be found in hbase:meta.Please use hbck tool to fix it first.");
787 } else if ((indexForCallable == startEndKeys.getFirst().length - 1)
788 && !Bytes.equals(startEndKeys.getSecond()[indexForCallable], HConstants.EMPTY_BYTE_ARRAY)) {
789 throw new IOException("The last region info for table "
790 + table.getName()
791 + " can't be found in hbase:meta.Please use hbck tool to fix it first.");
792 } else if (indexForCallable + 1 < startEndKeys.getFirst().length
793 && !(Bytes.compareTo(startEndKeys.getSecond()[indexForCallable],
794 startEndKeys.getFirst()[indexForCallable + 1]) == 0)) {
795 throw new IOException("The endkey of one region for table "
796 + table.getName()
797 + " is not equal to the startkey of the next region in hbase:meta."
798 + "Please use hbck tool to fix it first.");
799 }
800
801 boolean lastKeyInRange =
802 Bytes.compareTo(last, startEndKeys.getSecond()[idx]) < 0 ||
803 Bytes.equals(startEndKeys.getSecond()[idx], HConstants.EMPTY_BYTE_ARRAY);
804 if (!lastKeyInRange) {
805 List<LoadQueueItem> lqis = splitStoreFile(item, table,
806 startEndKeys.getFirst()[indexForCallable],
807 startEndKeys.getSecond()[indexForCallable]);
808 return lqis;
809 }
810
811
812 regionGroups.put(ByteBuffer.wrap(startEndKeys.getFirst()[idx]), item);
813 return null;
814 }
815
816
817
818
819
820
821
822 @Deprecated
823 protected List<LoadQueueItem> tryAtomicRegionLoad(final HConnection conn,
824 final byte [] tableName, final byte[] first, Collection<LoadQueueItem> lqis)
825 throws IOException {
826 return tryAtomicRegionLoad(conn, TableName.valueOf(tableName), first, lqis);
827 }
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842 protected List<LoadQueueItem> tryAtomicRegionLoad(final Connection conn,
843 final TableName tableName, final byte[] first, final Collection<LoadQueueItem> lqis)
844 throws IOException {
845 final List<Pair<byte[], String>> famPaths =
846 new ArrayList<Pair<byte[], String>>(lqis.size());
847 for (LoadQueueItem lqi : lqis) {
848 famPaths.add(Pair.newPair(lqi.family, lqi.hfilePath.toString()));
849 }
850
851 final RegionServerCallable<Boolean> svrCallable =
852 new RegionServerCallable<Boolean>(conn, tableName, first) {
853 @Override
854 public Boolean call(int callTimeout) throws Exception {
855 SecureBulkLoadClient secureClient = null;
856 boolean success = false;
857
858 try {
859 LOG.debug("Going to connect to server " + getLocation() + " for row "
860 + Bytes.toStringBinary(getRow()) + " with hfile group " + famPaths);
861 byte[] regionName = getLocation().getRegionInfo().getRegionName();
862 if (!isSecureBulkLoadEndpointAvailable()) {
863 success = ProtobufUtil.bulkLoadHFile(getStub(), famPaths, regionName, assignSeqIds,
864 clusterIds);
865 } else {
866 try (Table table = conn.getTable(getTableName())) {
867 secureClient = new SecureBulkLoadClient(table);
868 success = secureClient.bulkLoadHFiles(famPaths, fsDelegationToken.getUserToken(),
869 bulkToken, getLocation().getRegionInfo().getStartKey());
870 }
871 }
872 return success;
873 } finally {
874
875
876
877 if(secureClient != null && !success) {
878 FileSystem targetFs = FileSystem.get(getConf());
879
880 if(fs == null) {
881 fs = lqis.iterator().next().hfilePath.getFileSystem(getConf());
882 }
883
884
885
886 if (FSHDFSUtils.isSameHdfs(getConf(), fs, targetFs)) {
887 for(Pair<byte[], String> el : famPaths) {
888 Path hfileStagingPath = null;
889 Path hfileOrigPath = new Path(el.getSecond());
890 try {
891 hfileStagingPath= new Path(secureClient.getStagingPath(bulkToken, el.getFirst()),
892 hfileOrigPath.getName());
893 if(targetFs.rename(hfileStagingPath, hfileOrigPath)) {
894 LOG.debug("Moved back file " + hfileOrigPath + " from " +
895 hfileStagingPath);
896 } else if(targetFs.exists(hfileStagingPath)){
897 LOG.debug("Unable to move back file " + hfileOrigPath + " from " +
898 hfileStagingPath);
899 }
900 } catch(Exception ex) {
901 LOG.debug("Unable to move back file " + hfileOrigPath + " from " +
902 hfileStagingPath, ex);
903 }
904 }
905 }
906 }
907 }
908 }
909 };
910
911 try {
912 List<LoadQueueItem> toRetry = new ArrayList<LoadQueueItem>();
913 Configuration conf = getConf();
914 boolean success = RpcRetryingCallerFactory.instantiate(conf,
915 null).<Boolean> newCaller()
916 .callWithRetries(svrCallable, Integer.MAX_VALUE);
917 if (!success) {
918 LOG.warn("Attempt to bulk load region containing "
919 + Bytes.toStringBinary(first) + " into table "
920 + tableName + " with files " + lqis
921 + " failed. This is recoverable and they will be retried.");
922 toRetry.addAll(lqis);
923 }
924
925 return toRetry;
926 } catch (IOException e) {
927 LOG.error("Encountered unrecoverable error from region server, additional details: "
928 + svrCallable.getExceptionMessageAdditionalDetail(), e);
929 throw e;
930 }
931 }
932
933 private boolean isSecureBulkLoadEndpointAvailable() {
934 String classes = getConf().get(CoprocessorHost.REGION_COPROCESSOR_CONF_KEY, "");
935 return classes.contains("org.apache.hadoop.hbase.security.access.SecureBulkLoadEndpoint");
936 }
937
938
939
940
941
942 static void splitStoreFile(
943 Configuration conf, Path inFile,
944 HColumnDescriptor familyDesc, byte[] splitKey,
945 Path bottomOut, Path topOut) throws IOException
946 {
947
948 Reference topReference = Reference.createTopReference(splitKey);
949 Reference bottomReference = Reference.createBottomReference(splitKey);
950
951 copyHFileHalf(conf, inFile, topOut, topReference, familyDesc);
952 copyHFileHalf(conf, inFile, bottomOut, bottomReference, familyDesc);
953 }
954
955
956
957
958 private static void copyHFileHalf(
959 Configuration conf, Path inFile, Path outFile, Reference reference,
960 HColumnDescriptor familyDescriptor)
961 throws IOException {
962 FileSystem fs = inFile.getFileSystem(conf);
963 CacheConfig cacheConf = new CacheConfig(conf);
964 HalfStoreFileReader halfReader = null;
965 StoreFile.Writer halfWriter = null;
966 try {
967 halfReader = new HalfStoreFileReader(fs, inFile, cacheConf, reference, conf);
968 Map<byte[], byte[]> fileInfo = halfReader.loadFileInfo();
969
970 int blocksize = familyDescriptor.getBlocksize();
971 Algorithm compression = familyDescriptor.getCompression();
972 BloomType bloomFilterType = familyDescriptor.getBloomFilterType();
973 HFileContext hFileContext = new HFileContextBuilder()
974 .withCompression(compression)
975 .withChecksumType(HStore.getChecksumType(conf))
976 .withBytesPerCheckSum(HStore.getBytesPerChecksum(conf))
977 .withBlockSize(blocksize)
978 .withDataBlockEncoding(familyDescriptor.getDataBlockEncoding())
979 .withIncludesTags(true)
980 .build();
981 halfWriter = new StoreFile.WriterBuilder(conf, cacheConf,
982 fs)
983 .withFilePath(outFile)
984 .withBloomType(bloomFilterType)
985 .withFileContext(hFileContext)
986 .build();
987 HFileScanner scanner = halfReader.getScanner(false, false, false);
988 scanner.seekTo();
989 do {
990 halfWriter.append(scanner.getKeyValue());
991 } while (scanner.next());
992
993 for (Map.Entry<byte[],byte[]> entry : fileInfo.entrySet()) {
994 if (shouldCopyHFileMetaKey(entry.getKey())) {
995 halfWriter.appendFileInfo(entry.getKey(), entry.getValue());
996 }
997 }
998 } finally {
999 if (halfWriter != null) halfWriter.close();
1000 if (halfReader != null) halfReader.close(cacheConf.shouldEvictOnClose());
1001 }
1002 }
1003
1004 private static boolean shouldCopyHFileMetaKey(byte[] key) {
1005
1006 if (Bytes.equals(key, HFileDataBlockEncoder.DATA_BLOCK_ENCODING)) {
1007 return false;
1008 }
1009
1010 return !HFile.isReservedFileInfoKey(key);
1011 }
1012
1013 private boolean doesTableExist(TableName tableName) throws Exception {
1014 return hbAdmin.tableExists(tableName);
1015 }
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029 public static byte[][] inferBoundaries(TreeMap<byte[], Integer> bdryMap) {
1030 ArrayList<byte[]> keysArray = new ArrayList<byte[]>();
1031 int runningValue = 0;
1032 byte[] currStartKey = null;
1033 boolean firstBoundary = true;
1034
1035 for (Map.Entry<byte[], Integer> item: bdryMap.entrySet()) {
1036 if (runningValue == 0) currStartKey = item.getKey();
1037 runningValue += item.getValue();
1038 if (runningValue == 0) {
1039 if (!firstBoundary) keysArray.add(currStartKey);
1040 firstBoundary = false;
1041 }
1042 }
1043
1044 return keysArray.toArray(new byte[0][0]);
1045 }
1046
1047
1048
1049
1050
1051 private void createTable(TableName tableName, String dirPath) throws Exception {
1052 final Path hfofDir = new Path(dirPath);
1053 final FileSystem fs = hfofDir.getFileSystem(getConf());
1054
1055
1056
1057 final HTableDescriptor htd = new HTableDescriptor(tableName);
1058 final TreeMap<byte[], Integer> map = new TreeMap<byte[], Integer>(Bytes.BYTES_COMPARATOR);
1059 visitBulkHFiles(fs, hfofDir, new BulkHFileVisitor<HColumnDescriptor>() {
1060 @Override
1061 public HColumnDescriptor bulkFamily(final byte[] familyName) {
1062 HColumnDescriptor hcd = new HColumnDescriptor(familyName);
1063 htd.addFamily(hcd);
1064 return hcd;
1065 }
1066 @Override
1067 public void bulkHFile(final HColumnDescriptor hcd, final FileStatus hfileStatus)
1068 throws IOException {
1069 Path hfile = hfileStatus.getPath();
1070 HFile.Reader reader = HFile.createReader(fs, hfile,
1071 new CacheConfig(getConf()), getConf());
1072 try {
1073 if (hcd.getCompressionType() != reader.getFileContext().getCompression()) {
1074 hcd.setCompressionType(reader.getFileContext().getCompression());
1075 LOG.info("Setting compression " + hcd.getCompressionType().name() +
1076 " for family " + hcd.toString());
1077 }
1078 reader.loadFileInfo();
1079 byte[] first = reader.getFirstRowKey();
1080 byte[] last = reader.getLastRowKey();
1081
1082 LOG.info("Trying to figure out region boundaries hfile=" + hfile +
1083 " first=" + Bytes.toStringBinary(first) +
1084 " last=" + Bytes.toStringBinary(last));
1085
1086
1087 Integer value = map.containsKey(first)? map.get(first):0;
1088 map.put(first, value+1);
1089
1090 value = map.containsKey(last)? map.get(last):0;
1091 map.put(last, value-1);
1092 } finally {
1093 reader.close();
1094 }
1095 }
1096 });
1097
1098 byte[][] keys = LoadIncrementalHFiles.inferBoundaries(map);
1099 this.hbAdmin.createTable(htd,keys);
1100
1101 LOG.info("Table "+ tableName +" is available!!");
1102 }
1103
1104 @Override
1105 public int run(String[] args) throws Exception {
1106 if (args.length != 2) {
1107 usage();
1108 return -1;
1109 }
1110
1111 initialize();
1112
1113 String dirPath = args[0];
1114 TableName tableName = TableName.valueOf(args[1]);
1115
1116 boolean tableExists = this.doesTableExist(tableName);
1117 if (!tableExists) {
1118 if ("yes".equalsIgnoreCase(getConf().get(CREATE_TABLE_CONF_KEY, "yes"))) {
1119 this.createTable(tableName, dirPath);
1120 } else {
1121 String errorMsg = format("Table '%s' does not exist.", tableName);
1122 LOG.error(errorMsg);
1123 throw new TableNotFoundException(errorMsg);
1124 }
1125 }
1126
1127 Path hfofDir = new Path(dirPath);
1128
1129 try (Connection connection = ConnectionFactory.createConnection(getConf());
1130 HTable table = (HTable) connection.getTable(tableName);) {
1131 doBulkLoad(hfofDir, table);
1132 }
1133 return 0;
1134 }
1135
1136 public static void main(String[] args) throws Exception {
1137 Configuration conf = HBaseConfiguration.create();
1138 int ret = ToolRunner.run(conf, new LoadIncrementalHFiles(), args);
1139 System.exit(ret);
1140 }
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151 public void setBulkToken(String stagingDir) {
1152 this.bulkToken = stagingDir;
1153 }
1154
1155 }