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