View Javadoc

1   /**
2    *
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *     http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing, software
14   * distributed under the License is distributed on an "AS IS" BASIS,
15   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16   * See the License for the specific language governing permissions and
17   * limitations under the License.
18   */
19  package org.apache.hadoop.hbase.mapreduce;
20  
21  import 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.Connection;
68  import org.apache.hadoop.hbase.client.ConnectionFactory;
69  import org.apache.hadoop.hbase.client.RegionLocator;
70  import org.apache.hadoop.hbase.client.RegionServerCallable;
71  import org.apache.hadoop.hbase.client.RpcRetryingCallerFactory;
72  import org.apache.hadoop.hbase.client.SecureBulkLoadClient;
73  import org.apache.hadoop.hbase.client.Table;
74  import org.apache.hadoop.hbase.coprocessor.CoprocessorHost;
75  import org.apache.hadoop.hbase.io.HFileLink;
76  import org.apache.hadoop.hbase.io.HalfStoreFileReader;
77  import org.apache.hadoop.hbase.io.Reference;
78  import org.apache.hadoop.hbase.io.compress.Compression.Algorithm;
79  import org.apache.hadoop.hbase.io.hfile.CacheConfig;
80  import org.apache.hadoop.hbase.io.hfile.HFile;
81  import org.apache.hadoop.hbase.io.hfile.HFileContext;
82  import org.apache.hadoop.hbase.io.hfile.HFileContextBuilder;
83  import org.apache.hadoop.hbase.io.hfile.HFileDataBlockEncoder;
84  import org.apache.hadoop.hbase.io.hfile.HFileScanner;
85  import org.apache.hadoop.hbase.ipc.RpcControllerFactory;
86  import org.apache.hadoop.hbase.regionserver.BloomType;
87  import org.apache.hadoop.hbase.regionserver.HStore;
88  import org.apache.hadoop.hbase.regionserver.StoreFileInfo;
89  import org.apache.hadoop.hbase.regionserver.StoreFileWriter;
90  import org.apache.hadoop.hbase.security.UserProvider;
91  import org.apache.hadoop.hbase.security.token.FsDelegationToken;
92  import org.apache.hadoop.hbase.util.Bytes;
93  import org.apache.hadoop.hbase.util.FSHDFSUtils;
94  import org.apache.hadoop.hbase.util.Pair;
95  import org.apache.hadoop.util.Tool;
96  import org.apache.hadoop.util.ToolRunner;
97
98  import com.google.common.collect.HashMultimap;
99  import com.google.common.collect.Multimap;
100 import com.google.common.collect.Multimaps;
101 import com.google.common.util.concurrent.ThreadFactoryBuilder;
102
103 /**
104  * Tool to load the output of HFileOutputFormat into an existing table.
105  */
106 @InterfaceAudience.Public
107 @InterfaceStability.Stable
108 public class LoadIncrementalHFiles extends Configured implements Tool {
109   private static final Log LOG = LogFactory.getLog(LoadIncrementalHFiles.class);
110   private boolean initalized = false;
111
112   public static final String NAME = "completebulkload";
113   public static final String MAX_FILES_PER_REGION_PER_FAMILY
114     = "hbase.mapreduce.bulkload.max.hfiles.perRegion.perFamily";
115   private static final String ASSIGN_SEQ_IDS = "hbase.mapreduce.bulkload.assign.sequenceNumbers";
116   public final static String CREATE_TABLE_CONF_KEY = "create.table";
117
118   // We use a '.' prefix which is ignored when walking directory trees
119   // above. It is invalid family name.
120   final static String TMP_DIR = ".tmp";
121
122   private int maxFilesPerRegionPerFamily;
123   private boolean assignSeqIds;
124
125   // Source filesystem
126   private FileSystem fs;
127   // Source delegation token
128   private FsDelegationToken fsDelegationToken;
129   private String bulkToken;
130   private UserProvider userProvider;
131   private int nrThreads;
132   private RpcControllerFactory rpcControllerFactory;
133
134   private LoadIncrementalHFiles() {}
135
136   public LoadIncrementalHFiles(Configuration conf) throws Exception {
137     super(conf);
138     this.rpcControllerFactory = new RpcControllerFactory(conf);
139     initialize();
140   }
141
142   private void initialize() throws Exception {
143     if (initalized) {
144       return;
145     }
146     // make a copy, just to be sure we're not overriding someone else's config
147     setConf(HBaseConfiguration.create(getConf()));
148     Configuration conf = getConf();
149     // disable blockcache for tool invocation, see HBASE-10500
150     conf.setFloat(HConstants.HFILE_BLOCK_CACHE_SIZE_KEY, 0);
151     this.userProvider = UserProvider.instantiate(conf);
152     this.fsDelegationToken = new FsDelegationToken(userProvider, "renewer");
153     assignSeqIds = conf.getBoolean(ASSIGN_SEQ_IDS, true);
154     maxFilesPerRegionPerFamily = conf.getInt(MAX_FILES_PER_REGION_PER_FAMILY, 32);
155     nrThreads = conf.getInt("hbase.loadincremental.threads.max",
156       Runtime.getRuntime().availableProcessors());
157     initalized = true;
158   }
159
160   private void usage() {
161     System.err.println("usage: " + NAME + " /path/to/hfileoutputformat-output tablename" + "\n -D"
162         + CREATE_TABLE_CONF_KEY + "=no - can be used to avoid creation of table by this tool\n"
163         + "  Note: if you set this to 'no', then the target table must already exist in HBase\n"
164         + "\n");
165   }
166
167   private interface BulkHFileVisitor<TFamily> {
168     TFamily bulkFamily(final byte[] familyName)
169       throws IOException;
170     void bulkHFile(final TFamily family, final FileStatus hfileStatus)
171       throws IOException;
172   }
173
174   /**
175    * Iterate over the bulkDir hfiles.
176    * Skip reference, HFileLink, files starting with "_" and non-valid hfiles.
177    */
178   private static <TFamily> void visitBulkHFiles(final FileSystem fs, final Path bulkDir,
179     final BulkHFileVisitor<TFamily> visitor) throws IOException {
180     visitBulkHFiles(fs, bulkDir, visitor, true);
181   }
182
183   /**
184    * Iterate over the bulkDir hfiles.
185    * Skip reference, HFileLink, files starting with "_".
186    * Check and skip non-valid hfiles by default, or skip this validation by setting
187    * 'hbase.loadincremental.validate.hfile' to false.
188    */
189   private static <TFamily> void visitBulkHFiles(final FileSystem fs, final Path bulkDir,
190     final BulkHFileVisitor<TFamily> visitor, final boolean validateHFile) throws IOException {
191     if (!fs.exists(bulkDir)) {
192       throw new FileNotFoundException("Bulkload dir " + bulkDir + " not found");
193     }
194
195     FileStatus[] familyDirStatuses = fs.listStatus(bulkDir);
196     if (familyDirStatuses == null) {
197       throw new FileNotFoundException("No families found in " + bulkDir);
198     }
199
200     for (FileStatus familyStat : familyDirStatuses) {
201       if (!familyStat.isDirectory()) {
202         LOG.warn("Skipping non-directory " + familyStat.getPath());
203         continue;
204       }
205       Path familyDir = familyStat.getPath();
206       byte[] familyName = familyDir.getName().getBytes();
207       // Skip invalid family
208       try {
209         HColumnDescriptor.isLegalFamilyName(familyName);
210       }
211       catch (IllegalArgumentException e) {
212         LOG.warn("Skipping invalid " + familyStat.getPath());
213         continue;
214       }
215       TFamily family = visitor.bulkFamily(familyName);
216
217       FileStatus[] hfileStatuses = fs.listStatus(familyDir);
218       for (FileStatus hfileStatus : hfileStatuses) {
219         if (!fs.isFile(hfileStatus.getPath())) {
220           LOG.warn("Skipping non-file " + hfileStatus);
221           continue;
222         }
223
224         Path hfile = hfileStatus.getPath();
225         // Skip "_", reference, HFileLink
226         String fileName = hfile.getName();
227         if (fileName.startsWith("_")) {
228           continue;
229         }
230         if (StoreFileInfo.isReference(fileName)) {
231           LOG.warn("Skipping reference " + fileName);
232           continue;
233         }
234         if (HFileLink.isHFileLink(fileName)) {
235           LOG.warn("Skipping HFileLink " + fileName);
236           continue;
237         }
238
239         // Validate HFile Format if needed
240         if (validateHFile) {
241           try {
242             if (!HFile.isHFileFormat(fs, hfile)) {
243               LOG.warn("the file " + hfile + " doesn't seems to be an hfile. skipping");
244               continue;
245             }
246           } catch (FileNotFoundException e) {
247             LOG.warn("the file " + hfile + " was removed");
248             continue;
249           }
250 	}
251
252         visitor.bulkHFile(family, hfileStatus);
253       }
254     }
255   }
256
257   /**
258    * Represents an HFile waiting to be loaded. An queue is used
259    * in this class in order to support the case where a region has
260    * split during the process of the load. When this happens,
261    * the HFile is split into two physical parts across the new
262    * region boundary, and each part is added back into the queue.
263    * The import process finishes when the queue is empty.
264    */
265   public static class LoadQueueItem {
266     final byte[] family;
267     final Path hfilePath;
268
269     public LoadQueueItem(byte[] family, Path hfilePath) {
270       this.family = family;
271       this.hfilePath = hfilePath;
272     }
273
274     @Override
275     public String toString() {
276       return "family:"+ Bytes.toString(family) + " path:" + hfilePath.toString();
277     }
278   }
279
280   /**
281    * Walk the given directory for all HFiles, and return a Queue
282    * containing all such files.
283    */
284   private void discoverLoadQueue(final Deque<LoadQueueItem> ret, final Path hfofDir,
285     final boolean validateHFile) throws IOException {
286     fs = hfofDir.getFileSystem(getConf());
287     visitBulkHFiles(fs, hfofDir, new BulkHFileVisitor<byte[]>() {
288       @Override
289       public byte[] bulkFamily(final byte[] familyName) {
290         return familyName;
291       }
292       @Override
293       public void bulkHFile(final byte[] family, final FileStatus hfile) throws IOException {
294         long length = hfile.getLen();
295         if (length > getConf().getLong(HConstants.HREGION_MAX_FILESIZE,
296             HConstants.DEFAULT_MAX_FILE_SIZE)) {
297           LOG.warn("Trying to bulk load hfile " + hfile.getPath() + " with size: " +
298               length + " bytes can be problematic as it may lead to oversplitting.");
299         }
300         ret.add(new LoadQueueItem(family, hfile.getPath()));
301       }
302     }, validateHFile);
303   }
304
305   /**
306    * Perform a bulk load of the given directory into the given
307    * pre-existing table.  This method is not threadsafe.
308    *
309    * @param hfofDir the directory that was provided as the output path
310    *   of a job using HFileOutputFormat
311    * @param table the table to load into
312    * @throws TableNotFoundException if table does not yet exist
313    */
314   public void doBulkLoad(Path hfofDir, final Admin admin, Table table,
315       RegionLocator regionLocator) throws TableNotFoundException, IOException  {
316
317     if (!admin.isTableAvailable(regionLocator.getName())) {
318       throw new TableNotFoundException("Table " + table.getName() + " is not currently available.");
319     }
320
321     ExecutorService pool = createExecutorService();
322
323     // LQI queue does not need to be threadsafe -- all operations on this queue
324     // happen in this thread
325     Deque<LoadQueueItem> queue = new LinkedList<>();
326     SecureBulkLoadClient secureClient =  new SecureBulkLoadClient(table.getConfiguration(), table);
327
328     try {
329       /*
330        * Checking hfile format is a time-consuming operation, we should have an option to skip
331        * this step when bulkloading millions of HFiles. See HBASE-13985.
332        */
333       boolean validateHFile = getConf().getBoolean("hbase.loadincremental.validate.hfile", true);
334       if(!validateHFile) {
335 	LOG.warn("You are skipping HFiles validation, it might cause some data loss if files " +
336 	    "are not correct. If you fail to read data from your table after using this " +
337 	    "option, consider removing the files and bulkload again without this option. " +
338 	    "See HBASE-13985");
339       }
340       prepareHFileQueue(hfofDir, table, queue, validateHFile);
341
342       int count = 0;
343
344       if (queue.isEmpty()) {
345         LOG.warn("Bulk load operation did not find any files to load in " +
346             "directory " + hfofDir.toUri() + ".  Does it contain files in " +
347             "subdirectories that correspond to column family names?");
348         return;
349       }
350
351       if(isSecureBulkLoadEndpointAvailable()) {
352         LOG.warn("SecureBulkLoadEndpoint is deprecated. It will be removed in future releases.");
353         LOG.warn("Secure bulk load has been integrated into HBase core.");
354       }
355
356       //If using secure bulk load, get source delegation token, and
357       //prepare staging directory and token
358       // fs is the source filesystem
359       fsDelegationToken.acquireDelegationToken(fs);
360       bulkToken = secureClient.prepareBulkLoad(admin.getConnection());
361
362       // Assumes that region splits can happen while this occurs.
363       while (!queue.isEmpty()) {
364         // need to reload split keys each iteration.
365         final Pair<byte[][], byte[][]> startEndKeys = regionLocator.getStartEndKeys();
366         if (count != 0) {
367           LOG.info("Split occured while grouping HFiles, retry attempt " +
368               + count + " with " + queue.size() + " files remaining to group or split");
369         }
370
371         int maxRetries = getConf().getInt(HConstants.BULKLOAD_MAX_RETRIES_NUMBER, 10);
372         maxRetries = Math.max(maxRetries, startEndKeys.getFirst().length + 1);
373         if (maxRetries != 0 && count >= maxRetries) {
374           throw new IOException("Retry attempted " + count +
375             " times without completing, bailing out");
376         }
377         count++;
378
379         // Using ByteBuffer for byte[] equality semantics
380         Multimap<ByteBuffer, LoadQueueItem> regionGroups = groupOrSplitPhase(table,
381             pool, queue, startEndKeys);
382
383         if (!checkHFilesCountPerRegionPerFamily(regionGroups)) {
384           // Error is logged inside checkHFilesCountPerRegionPerFamily.
385           throw new IOException("Trying to load more than " + maxFilesPerRegionPerFamily
386             + " hfiles to one family of one region");
387         }
388
389         bulkLoadPhase(table, admin.getConnection(), pool, queue, regionGroups);
390
391         // NOTE: The next iteration's split / group could happen in parallel to
392         // atomic bulkloads assuming that there are splits and no merges, and
393         // that we can atomically pull out the groups we want to retry.
394       }
395
396     } finally {
397       fsDelegationToken.releaseDelegationToken();
398       if(bulkToken != null) {
399         secureClient.cleanupBulkLoad(admin.getConnection(), bulkToken);
400       }
401       pool.shutdown();
402       if (queue != null && !queue.isEmpty()) {
403         StringBuilder err = new StringBuilder();
404         err.append("-------------------------------------------------\n");
405         err.append("Bulk load aborted with some files not yet loaded:\n");
406         err.append("-------------------------------------------------\n");
407         for (LoadQueueItem q : queue) {
408           err.append("  ").append(q.hfilePath).append('\n');
409         }
410         LOG.error(err);
411       }
412     }
413
414     if (queue != null && !queue.isEmpty()) {
415       throw new RuntimeException("Bulk load aborted with some files not yet loaded."
416         + "Please check log for more details.");
417     }
418   }
419
420   /**
421    * Prepare a collection of {@link LoadQueueItem} from list of source hfiles contained in the
422    * passed directory and validates whether the prepared queue has all the valid table column
423    * families in it.
424    * @param hfilesDir directory containing list of hfiles to be loaded into the table
425    * @param table table to which hfiles should be loaded
426    * @param queue queue which needs to be loaded into the table
427    * @param validateHFile if true hfiles will be validated for its format
428    * @throws IOException If any I/O or network error occurred
429    */
430   public void prepareHFileQueue(Path hfilesDir, Table table, Deque<LoadQueueItem> queue,
431       boolean validateHFile) throws IOException {
432     discoverLoadQueue(queue, hfilesDir, validateHFile);
433     validateFamiliesInHFiles(table, queue);
434   }
435
436   // Initialize a thread pool
437   private ExecutorService createExecutorService() {
438     ThreadFactoryBuilder builder = new ThreadFactoryBuilder();
439     builder.setNameFormat("LoadIncrementalHFiles-%1$d");
440     ExecutorService pool = new ThreadPoolExecutor(nrThreads, nrThreads, 60, TimeUnit.SECONDS,
441         new LinkedBlockingQueue<Runnable>(), builder.build());
442     ((ThreadPoolExecutor) pool).allowCoreThreadTimeOut(true);
443     return pool;
444   }
445
446   /**
447    * Checks whether there is any invalid family name in HFiles to be bulk loaded.
448    */
449   private void validateFamiliesInHFiles(Table table, Deque<LoadQueueItem> queue)
450       throws IOException {
451     Collection<HColumnDescriptor> families = table.getTableDescriptor().getFamilies();
452     List<String> familyNames = new ArrayList<>(families.size());
453     for (HColumnDescriptor family : families) {
454       familyNames.add(family.getNameAsString());
455     }
456     List<String> unmatchedFamilies = new ArrayList<String>();
457     Iterator<LoadQueueItem> queueIter = queue.iterator();
458     while (queueIter.hasNext()) {
459       LoadQueueItem lqi = queueIter.next();
460       String familyNameInHFile = Bytes.toString(lqi.family);
461       if (!familyNames.contains(familyNameInHFile)) {
462         unmatchedFamilies.add(familyNameInHFile);
463       }
464     }
465     if (unmatchedFamilies.size() > 0) {
466       String msg =
467           "Unmatched family names found: unmatched family names in HFiles to be bulkloaded: "
468               + unmatchedFamilies + "; valid family names of table " + table.getName() + " are: "
469               + familyNames;
470       LOG.error(msg);
471       throw new IOException(msg);
472     }
473   }
474
475   /**
476    * Used by the replication sink to load the hfiles from the source cluster. It does the following,
477    * <ol>
478    * <li>LoadIncrementalHFiles#groupOrSplitPhase(Table, ExecutorService, Deque, Pair)}</li>
479    * <li>LoadIncrementalHFiles#bulkLoadPhase(Table, Connection, ExecutorService, Deque, Multimap)
480    * </li>
481    * </ol>
482    * @param table Table to which these hfiles should be loaded to
483    * @param conn Connection to use
484    * @param queue {@link LoadQueueItem} has hfiles yet to be loaded
485    * @param startEndKeys starting and ending row keys of the region
486    */
487   public void loadHFileQueue(final Table table, final Connection conn, Deque<LoadQueueItem> queue,
488       Pair<byte[][], byte[][]> startEndKeys) throws IOException {
489     ExecutorService pool = null;
490     try {
491       pool = createExecutorService();
492       Multimap<ByteBuffer, LoadQueueItem> regionGroups =
493           groupOrSplitPhase(table, pool, queue, startEndKeys);
494       bulkLoadPhase(table, conn, pool, queue, regionGroups);
495     } finally {
496       if (pool != null) {
497         pool.shutdown();
498       }
499     }
500   }
501
502   /**
503    * This takes the LQI's grouped by likely regions and attempts to bulk load
504    * them.  Any failures are re-queued for another pass with the
505    * groupOrSplitPhase.
506    */
507   protected void bulkLoadPhase(final Table table, final Connection conn,
508       ExecutorService pool, Deque<LoadQueueItem> queue,
509       final Multimap<ByteBuffer, LoadQueueItem> regionGroups) throws IOException {
510     // atomically bulk load the groups.
511     Set<Future<List<LoadQueueItem>>> loadingFutures = new HashSet<>();
512     for (Entry<ByteBuffer, ? extends Collection<LoadQueueItem>> e: regionGroups.asMap().entrySet()){
513       final byte[] first = e.getKey().array();
514       final Collection<LoadQueueItem> lqis =  e.getValue();
515
516       final Callable<List<LoadQueueItem>> call = new Callable<List<LoadQueueItem>>() {
517         @Override
518         public List<LoadQueueItem> call() throws Exception {
519           List<LoadQueueItem> toRetry =
520               tryAtomicRegionLoad(conn, table.getName(), first, lqis);
521           return toRetry;
522         }
523       };
524       loadingFutures.add(pool.submit(call));
525     }
526
527     // get all the results.
528     for (Future<List<LoadQueueItem>> future : loadingFutures) {
529       try {
530         List<LoadQueueItem> toRetry = future.get();
531
532         // LQIs that are requeued to be regrouped.
533         queue.addAll(toRetry);
534
535       } catch (ExecutionException e1) {
536         Throwable t = e1.getCause();
537         if (t instanceof IOException) {
538           // At this point something unrecoverable has happened.
539           // TODO Implement bulk load recovery
540           throw new IOException("BulkLoad encountered an unrecoverable problem", t);
541         }
542         LOG.error("Unexpected execution exception during bulk load", e1);
543         throw new IllegalStateException(t);
544       } catch (InterruptedException e1) {
545         LOG.error("Unexpected interrupted exception during bulk load", e1);
546         throw (InterruptedIOException)new InterruptedIOException().initCause(e1);
547       }
548     }
549   }
550
551   private boolean checkHFilesCountPerRegionPerFamily(
552       final Multimap<ByteBuffer, LoadQueueItem> regionGroups) {
553     for (Entry<ByteBuffer,
554       ? extends Collection<LoadQueueItem>> e: regionGroups.asMap().entrySet()) {
555       final Collection<LoadQueueItem> lqis =  e.getValue();
556       HashMap<byte[], MutableInt> filesMap = new HashMap<>();
557       for (LoadQueueItem lqi: lqis) {
558         MutableInt count = filesMap.get(lqi.family);
559         if (count == null) {
560           count = new MutableInt();
561           filesMap.put(lqi.family, count);
562         }
563         count.increment();
564         if (count.intValue() > maxFilesPerRegionPerFamily) {
565           LOG.error("Trying to load more than " + maxFilesPerRegionPerFamily
566             + " hfiles to family " + Bytes.toStringBinary(lqi.family)
567             + " of region with start key "
568             + Bytes.toStringBinary(e.getKey()));
569           return false;
570         }
571       }
572     }
573     return true;
574   }
575
576   /**
577    * @return A map that groups LQI by likely bulk load region targets.
578    */
579   private Multimap<ByteBuffer, LoadQueueItem> groupOrSplitPhase(final Table table,
580       ExecutorService pool, Deque<LoadQueueItem> queue,
581       final Pair<byte[][], byte[][]> startEndKeys) throws IOException {
582     // <region start key, LQI> need synchronized only within this scope of this
583     // phase because of the puts that happen in futures.
584     Multimap<ByteBuffer, LoadQueueItem> rgs = HashMultimap.create();
585     final Multimap<ByteBuffer, LoadQueueItem> regionGroups = Multimaps.synchronizedMultimap(rgs);
586
587     // drain LQIs and figure out bulk load groups
588     Set<Future<List<LoadQueueItem>>> splittingFutures = new HashSet<>();
589     while (!queue.isEmpty()) {
590       final LoadQueueItem item = queue.remove();
591
592       final Callable<List<LoadQueueItem>> call = new Callable<List<LoadQueueItem>>() {
593         @Override
594         public List<LoadQueueItem> call() throws Exception {
595           List<LoadQueueItem> splits = groupOrSplit(regionGroups, item, table, startEndKeys);
596           return splits;
597         }
598       };
599       splittingFutures.add(pool.submit(call));
600     }
601     // get all the results.  All grouping and splitting must finish before
602     // we can attempt the atomic loads.
603     for (Future<List<LoadQueueItem>> lqis : splittingFutures) {
604       try {
605         List<LoadQueueItem> splits = lqis.get();
606         if (splits != null) {
607           queue.addAll(splits);
608         }
609       } catch (ExecutionException e1) {
610         Throwable t = e1.getCause();
611         if (t instanceof IOException) {
612           LOG.error("IOException during splitting", e1);
613           throw (IOException)t; // would have been thrown if not parallelized,
614         }
615         LOG.error("Unexpected execution exception during splitting", e1);
616         throw new IllegalStateException(t);
617       } catch (InterruptedException e1) {
618         LOG.error("Unexpected interrupted exception during splitting", e1);
619         throw (InterruptedIOException)new InterruptedIOException().initCause(e1);
620       }
621     }
622     return regionGroups;
623   }
624
625   // unique file name for the table
626   private String getUniqueName() {
627     return UUID.randomUUID().toString().replaceAll("-", "");
628   }
629
630   protected List<LoadQueueItem> splitStoreFile(final LoadQueueItem item,
631       final Table table, byte[] startKey,
632       byte[] splitKey) throws IOException {
633     final Path hfilePath = item.hfilePath;
634
635     Path tmpDir = item.hfilePath.getParent();
636     if (!tmpDir.getName().equals(TMP_DIR)) {
637       tmpDir = new Path(tmpDir, TMP_DIR);
638     }
639
640     LOG.info("HFile at " + hfilePath + " no longer fits inside a single " +
641       "region. Splitting...");
642
643     String uniqueName = getUniqueName();
644     HColumnDescriptor familyDesc = table.getTableDescriptor().getFamily(item.family);
645
646     Path botOut = new Path(tmpDir, uniqueName + ".bottom");
647     Path topOut = new Path(tmpDir, uniqueName + ".top");
648     splitStoreFile(getConf(), hfilePath, familyDesc, splitKey, botOut, topOut);
649
650     FileSystem fs = tmpDir.getFileSystem(getConf());
651     fs.setPermission(tmpDir, FsPermission.valueOf("-rwxrwxrwx"));
652     fs.setPermission(botOut, FsPermission.valueOf("-rwxrwxrwx"));
653     fs.setPermission(topOut, FsPermission.valueOf("-rwxrwxrwx"));
654
655     // Add these back at the *front* of the queue, so there's a lower
656     // chance that the region will just split again before we get there.
657     List<LoadQueueItem> lqis = new ArrayList<LoadQueueItem>(2);
658     lqis.add(new LoadQueueItem(item.family, botOut));
659     lqis.add(new LoadQueueItem(item.family, topOut));
660
661     // If the current item is already the result of previous splits,
662     // we don't need it anymore. Clean up to save space.
663     // It is not part of the original input files.
664     try {
665       tmpDir = item.hfilePath.getParent();
666       if (tmpDir.getName().equals(TMP_DIR)) {
667         fs.delete(item.hfilePath, false);
668       }
669     } catch (IOException e) {
670       LOG.warn("Unable to delete temporary split file " + item.hfilePath);
671     }
672     LOG.info("Successfully split into new HFiles " + botOut + " and " + topOut);
673     return lqis;
674   }
675
676   /**
677    * Attempt to assign the given load queue item into its target region group.
678    * If the hfile boundary no longer fits into a region, physically splits
679    * the hfile such that the new bottom half will fit and returns the list of
680    * LQI's corresponding to the resultant hfiles.
681    *
682    * protected for testing
683    * @throws IOException if an IO failure is encountered
684    */
685   protected List<LoadQueueItem> groupOrSplit(Multimap<ByteBuffer, LoadQueueItem> regionGroups,
686       final LoadQueueItem item, final Table table,
687       final Pair<byte[][], byte[][]> startEndKeys)
688       throws IOException {
689     final Path hfilePath = item.hfilePath;
690     // fs is the source filesystem
691     if (fs == null) {
692       fs = hfilePath.getFileSystem(getConf());
693     }
694     HFile.Reader hfr = HFile.createReader(fs, hfilePath,
695         new CacheConfig(getConf()), getConf());
696     final byte[] first, last;
697     try {
698       hfr.loadFileInfo();
699       first = hfr.getFirstRowKey();
700       last = hfr.getLastRowKey();
701     }  finally {
702       hfr.close();
703     }
704
705     LOG.info("Trying to load hfile=" + hfilePath +
706         " first=" + Bytes.toStringBinary(first) +
707         " last="  + Bytes.toStringBinary(last));
708     if (first == null || last == null) {
709       assert first == null && last == null;
710       // TODO what if this is due to a bad HFile?
711       LOG.info("hfile " + hfilePath + " has no entries, skipping");
712       return null;
713     }
714     if (Bytes.compareTo(first, last) > 0) {
715       throw new IllegalArgumentException(
716       "Invalid range: " + Bytes.toStringBinary(first) +
717       " > " + Bytes.toStringBinary(last));
718     }
719     int idx = Arrays.binarySearch(startEndKeys.getFirst(), first,
720         Bytes.BYTES_COMPARATOR);
721     if (idx < 0) {
722       // not on boundary, returns -(insertion index).  Calculate region it
723       // would be in.
724       idx = -(idx + 1) - 1;
725     }
726     final int indexForCallable = idx;
727
728     /**
729      * we can consider there is a region hole in following conditions. 1) if idx < 0,then first
730      * region info is lost. 2) if the endkey of a region is not equal to the startkey of the next
731      * region. 3) if the endkey of the last region is not empty.
732      */
733     if (indexForCallable < 0) {
734       throw new IOException("The first region info for table "
735           + table.getName()
736           + " cann't be found in hbase:meta.Please use hbck tool to fix it first.");
737     } else if ((indexForCallable == startEndKeys.getFirst().length - 1)
738         && !Bytes.equals(startEndKeys.getSecond()[indexForCallable], HConstants.EMPTY_BYTE_ARRAY)) {
739       throw new IOException("The last region info for table "
740           + table.getName()
741           + " cann't be found in hbase:meta.Please use hbck tool to fix it first.");
742     } else if (indexForCallable + 1 < startEndKeys.getFirst().length
743         && !(Bytes.compareTo(startEndKeys.getSecond()[indexForCallable],
744           startEndKeys.getFirst()[indexForCallable + 1]) == 0)) {
745       throw new IOException("The endkey of one region for table "
746           + table.getName()
747           + " is not equal to the startkey of the next region in hbase:meta."
748           + "Please use hbck tool to fix it first.");
749     }
750
751     boolean lastKeyInRange =
752       Bytes.compareTo(last, startEndKeys.getSecond()[idx]) < 0 ||
753       Bytes.equals(startEndKeys.getSecond()[idx], HConstants.EMPTY_BYTE_ARRAY);
754     if (!lastKeyInRange) {
755       List<LoadQueueItem> lqis = splitStoreFile(item, table,
756           startEndKeys.getFirst()[indexForCallable],
757           startEndKeys.getSecond()[indexForCallable]);
758       return lqis;
759     }
760
761     // group regions.
762     regionGroups.put(ByteBuffer.wrap(startEndKeys.getFirst()[idx]), item);
763     return null;
764   }
765
766   /**
767    * Attempts to do an atomic load of many hfiles into a region.  If it fails,
768    * it returns a list of hfiles that need to be retried.  If it is successful
769    * it will return an empty list.
770    *
771    * NOTE: To maintain row atomicity guarantees, region server callable should
772    * succeed atomically and fails atomically.
773    *
774    * Protected for testing.
775    *
776    * @return empty list if success, list of items to retry on recoverable
777    *   failure
778    */
779   protected List<LoadQueueItem> tryAtomicRegionLoad(final Connection conn,
780       final TableName tableName, final byte[] first, final Collection<LoadQueueItem> lqis)
781   throws IOException {
782     final List<Pair<byte[], String>> famPaths = new ArrayList<>(lqis.size());
783     for (LoadQueueItem lqi : lqis) {
784       famPaths.add(Pair.newPair(lqi.family, lqi.hfilePath.toString()));
785     }
786     final RegionServerCallable<Boolean> svrCallable = new RegionServerCallable<Boolean>(conn,
787         rpcControllerFactory, tableName, first) {
788       @Override
789       protected Boolean rpcCall() throws Exception {
790         SecureBulkLoadClient secureClient = null;
791         boolean success = false;
792         try {
793           LOG.debug("Going to connect to server " + getLocation() + " for row "
794               + Bytes.toStringBinary(getRow()) + " with hfile group " + famPaths);
795           byte[] regionName = getLocation().getRegionInfo().getRegionName();
796           try (Table table = conn.getTable(getTableName())) {
797             secureClient = new SecureBulkLoadClient(getConf(), table);
798             success = secureClient.secureBulkLoadHFiles(getStub(), famPaths, regionName,
799                   assignSeqIds, fsDelegationToken.getUserToken(), bulkToken);
800           }
801           return success;
802         } finally {
803           //Best effort copying of files that might not have been imported
804           //from the staging directory back to original location
805           //in user directory
806           if (secureClient != null && !success) {
807             FileSystem targetFs = FileSystem.get(getConf());
808          // fs is the source filesystem
809             if(fs == null) {
810               fs = lqis.iterator().next().hfilePath.getFileSystem(getConf());
811             }
812             // Check to see if the source and target filesystems are the same
813             // If they are the same filesystem, we will try move the files back
814             // because previously we moved them to the staging directory.
815             if (FSHDFSUtils.isSameHdfs(getConf(), fs, targetFs)) {
816               for(Pair<byte[], String> el : famPaths) {
817                 Path hfileStagingPath = null;
818                 Path hfileOrigPath = new Path(el.getSecond());
819                 try {
820                   hfileStagingPath= new Path(new Path(bulkToken, Bytes.toString(el.getFirst())),
821                     hfileOrigPath.getName());
822                   if(targetFs.rename(hfileStagingPath, hfileOrigPath)) {
823                     LOG.debug("Moved back file " + hfileOrigPath + " from " +
824                         hfileStagingPath);
825                   } else if(targetFs.exists(hfileStagingPath)){
826                     LOG.debug("Unable to move back file " + hfileOrigPath + " from " +
827                         hfileStagingPath);
828                   }
829                 } catch(Exception ex) {
830                   LOG.debug("Unable to move back file " + hfileOrigPath + " from " +
831                       hfileStagingPath, ex);
832                 }
833               }
834             }
835           }
836         }
837       }
838     };
839
840     try {
841       List<LoadQueueItem> toRetry = new ArrayList<>();
842       Configuration conf = getConf();
843       boolean success = RpcRetryingCallerFactory.instantiate(conf,
844           null).<Boolean> newCaller()
845           .callWithRetries(svrCallable, Integer.MAX_VALUE);
846       if (!success) {
847         LOG.warn("Attempt to bulk load region containing "
848             + Bytes.toStringBinary(first) + " into table "
849             + tableName  + " with files " + lqis
850             + " failed.  This is recoverable and they will be retried.");
851         toRetry.addAll(lqis); // return lqi's to retry
852       }
853       // success
854       return toRetry;
855     } catch (IOException e) {
856       LOG.error("Encountered unrecoverable error from region server, additional details: "
857           + svrCallable.getExceptionMessageAdditionalDetail(), e);
858       throw e;
859     }
860   }
861
862   private boolean isSecureBulkLoadEndpointAvailable() {
863     String classes = getConf().get(CoprocessorHost.REGION_COPROCESSOR_CONF_KEY, "");
864     return classes.contains("org.apache.hadoop.hbase.security.access.SecureBulkLoadEndpoint");
865   }
866
867   /**
868    * Split a storefile into a top and bottom half, maintaining
869    * the metadata, recreating bloom filters, etc.
870    */
871   static void splitStoreFile(
872       Configuration conf, Path inFile,
873       HColumnDescriptor familyDesc, byte[] splitKey,
874       Path bottomOut, Path topOut) throws IOException {
875     // Open reader with no block cache, and not in-memory
876     Reference topReference = Reference.createTopReference(splitKey);
877     Reference bottomReference = Reference.createBottomReference(splitKey);
878
879     copyHFileHalf(conf, inFile, topOut, topReference, familyDesc);
880     copyHFileHalf(conf, inFile, bottomOut, bottomReference, familyDesc);
881   }
882
883   /**
884    * Copy half of an HFile into a new HFile.
885    */
886   private static void copyHFileHalf(
887       Configuration conf, Path inFile, Path outFile, Reference reference,
888       HColumnDescriptor familyDescriptor)
889   throws IOException {
890     FileSystem fs = inFile.getFileSystem(conf);
891     CacheConfig cacheConf = new CacheConfig(conf);
892     HalfStoreFileReader halfReader = null;
893     StoreFileWriter halfWriter = null;
894     try {
895       halfReader = new HalfStoreFileReader(fs, inFile, cacheConf, reference, conf);
896       Map<byte[], byte[]> fileInfo = halfReader.loadFileInfo();
897
898       int blocksize = familyDescriptor.getBlocksize();
899       Algorithm compression = familyDescriptor.getCompressionType();
900       BloomType bloomFilterType = familyDescriptor.getBloomFilterType();
901       HFileContext hFileContext = new HFileContextBuilder()
902                                   .withCompression(compression)
903                                   .withChecksumType(HStore.getChecksumType(conf))
904                                   .withBytesPerCheckSum(HStore.getBytesPerChecksum(conf))
905                                   .withBlockSize(blocksize)
906                                   .withDataBlockEncoding(familyDescriptor.getDataBlockEncoding())
907                                   .withIncludesTags(true)
908                                   .build();
909       halfWriter = new StoreFileWriter.Builder(conf, cacheConf,
910           fs)
911               .withFilePath(outFile)
912               .withBloomType(bloomFilterType)
913               .withFileContext(hFileContext)
914               .build();
915       HFileScanner scanner = halfReader.getScanner(false, false, false);
916       scanner.seekTo();
917       do {
918         halfWriter.append(scanner.getCell());
919       } while (scanner.next());
920
921       for (Map.Entry<byte[],byte[]> entry : fileInfo.entrySet()) {
922         if (shouldCopyHFileMetaKey(entry.getKey())) {
923           halfWriter.appendFileInfo(entry.getKey(), entry.getValue());
924         }
925       }
926     } finally {
927       if (halfWriter != null) {
928         halfWriter.close();
929       }
930       if (halfReader != null) {
931         halfReader.close(cacheConf.shouldEvictOnClose());
932       }
933     }
934   }
935
936   private static boolean shouldCopyHFileMetaKey(byte[] key) {
937     // skip encoding to keep hfile meta consistent with data block info, see HBASE-15085
938     if (Bytes.equals(key, HFileDataBlockEncoder.DATA_BLOCK_ENCODING)) {
939       return false;
940     }
941
942     return !HFile.isReservedFileInfoKey(key);
943   }
944
945   /*
946    * Infers region boundaries for a new table.
947    * Parameter:
948    *   bdryMap is a map between keys to an integer belonging to {+1, -1}
949    *     If a key is a start key of a file, then it maps to +1
950    *     If a key is an end key of a file, then it maps to -1
951    * Algo:
952    * 1) Poll on the keys in order:
953    *    a) Keep adding the mapped values to these keys (runningSum)
954    *    b) Each time runningSum reaches 0, add the start Key from when the runningSum had started to
955    *       a boundary list.
956    * 2) Return the boundary list.
957    */
958   public static byte[][] inferBoundaries(TreeMap<byte[], Integer> bdryMap) {
959     ArrayList<byte[]> keysArray = new ArrayList<>();
960     int runningValue = 0;
961     byte[] currStartKey = null;
962     boolean firstBoundary = true;
963
964     for (Map.Entry<byte[], Integer> item: bdryMap.entrySet()) {
965       if (runningValue == 0) {
966         currStartKey = item.getKey();
967       }
968       runningValue += item.getValue();
969       if (runningValue == 0) {
970         if (!firstBoundary) {
971           keysArray.add(currStartKey);
972         }
973         firstBoundary = false;
974       }
975     }
976
977     return keysArray.toArray(new byte[0][0]);
978   }
979
980   /*
981    * If the table is created for the first time, then "completebulkload" reads the files twice.
982    * More modifications necessary if we want to avoid doing it.
983    */
984   private void createTable(TableName tableName, String dirPath, Admin admin) throws Exception {
985     final Path hfofDir = new Path(dirPath);
986     final FileSystem fs = hfofDir.getFileSystem(getConf());
987
988     // Add column families
989     // Build a set of keys
990     final HTableDescriptor htd = new HTableDescriptor(tableName);
991     final TreeMap<byte[], Integer> map = new TreeMap<>(Bytes.BYTES_COMPARATOR);
992     visitBulkHFiles(fs, hfofDir, new BulkHFileVisitor<HColumnDescriptor>() {
993       @Override
994       public HColumnDescriptor bulkFamily(final byte[] familyName) {
995         HColumnDescriptor hcd = new HColumnDescriptor(familyName);
996         htd.addFamily(hcd);
997         return hcd;
998       }
999       @Override
1000       public void bulkHFile(final HColumnDescriptor hcd, final FileStatus hfileStatus)
1001           throws IOException {
1002         Path hfile = hfileStatus.getPath();
1003         HFile.Reader reader = HFile.createReader(fs, hfile,
1004             new CacheConfig(getConf()), getConf());
1005         try {
1006           if (hcd.getCompressionType() != reader.getFileContext().getCompression()) {
1007             hcd.setCompressionType(reader.getFileContext().getCompression());
1008             LOG.info("Setting compression " + hcd.getCompressionType().name() +
1009                      " for family " + hcd.toString());
1010           }
1011           reader.loadFileInfo();
1012           byte[] first = reader.getFirstRowKey();
1013           byte[] last  = reader.getLastRowKey();
1014
1015           LOG.info("Trying to figure out region boundaries hfile=" + hfile +
1016             " first=" + Bytes.toStringBinary(first) +
1017             " last="  + Bytes.toStringBinary(last));
1018
1019           // To eventually infer start key-end key boundaries
1020           Integer value = map.containsKey(first)? map.get(first):0;
1021           map.put(first, value+1);
1022
1023           value = map.containsKey(last)? map.get(last):0;
1024           map.put(last, value-1);
1025         } finally {
1026           reader.close();
1027         }
1028       }
1029     });
1030
1031     byte[][] keys = LoadIncrementalHFiles.inferBoundaries(map);
1032     admin.createTable(htd, keys);
1033
1034     LOG.info("Table "+ tableName +" is available!!");
1035   }
1036
1037   @Override
1038   public int run(String[] args) throws Exception {
1039     if (args.length != 2) {
1040       usage();
1041       return -1;
1042     }
1043
1044     initialize();
1045     try (Connection connection = ConnectionFactory.createConnection(getConf());
1046         Admin admin = connection.getAdmin()) {
1047       String dirPath = args[0];
1048       TableName tableName = TableName.valueOf(args[1]);
1049
1050       boolean tableExists = admin.tableExists(tableName);
1051       if (!tableExists) {
1052         if ("yes".equalsIgnoreCase(getConf().get(CREATE_TABLE_CONF_KEY, "yes"))) {
1053           this.createTable(tableName, dirPath, admin);
1054         } else {
1055           String errorMsg = format("Table '%s' does not exist.", tableName);
1056           LOG.error(errorMsg);
1057           throw new TableNotFoundException(errorMsg);
1058         }
1059       }
1060
1061       Path hfofDir = new Path(dirPath);
1062
1063       try (Table table = connection.getTable(tableName);
1064         RegionLocator locator = connection.getRegionLocator(tableName)) {
1065         doBulkLoad(hfofDir, admin, table, locator);
1066       }
1067     }
1068
1069     return 0;
1070   }
1071
1072   public static void main(String[] args) throws Exception {
1073     Configuration conf = HBaseConfiguration.create();
1074     int ret = ToolRunner.run(conf, new LoadIncrementalHFiles(), args);
1075     System.exit(ret);
1076   }
1077
1078   /**
1079    * Called from replication sink, where it manages bulkToken(staging directory) by itself. This is
1080    * used only when SecureBulkLoadEndpoint is configured in hbase.coprocessor.region.classes
1081    * property. This directory is used as a temporary directory where all files are initially
1082    * copied/moved from user given directory, set all the required file permissions and then from
1083    * their it is finally loaded into a table. This should be set only when, one would like to manage
1084    * the staging directory by itself. Otherwise this tool will handle this by itself.
1085    * @param stagingDir staging directory path
1086    */
1087   public void setBulkToken(String stagingDir) {
1088     this.bulkToken = stagingDir;
1089   }
1090 }