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