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