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