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