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.util;
20  
21  import java.io.IOException;
22  import java.math.BigInteger;
23  import java.util.Arrays;
24  import java.util.Collections;
25  import java.util.Comparator;
26  import java.util.LinkedList;
27  import java.util.List;
28  import java.util.Map;
29  import java.util.Set;
30  import java.util.TreeMap;
31  
32  import org.apache.commons.cli.CommandLine;
33  import org.apache.commons.cli.GnuParser;
34  import org.apache.commons.cli.HelpFormatter;
35  import org.apache.commons.cli.OptionBuilder;
36  import org.apache.commons.cli.Options;
37  import org.apache.commons.cli.ParseException;
38  import org.apache.commons.lang.ArrayUtils;
39  import org.apache.commons.lang.StringUtils;
40  import org.apache.commons.logging.Log;
41  import org.apache.commons.logging.LogFactory;
42  import org.apache.hadoop.classification.InterfaceAudience;
43  import org.apache.hadoop.conf.Configuration;
44  import org.apache.hadoop.fs.FSDataInputStream;
45  import org.apache.hadoop.fs.FSDataOutputStream;
46  import org.apache.hadoop.fs.FileSystem;
47  import org.apache.hadoop.fs.Path;
48  import org.apache.hadoop.hbase.HBaseConfiguration;
49  import org.apache.hadoop.hbase.HColumnDescriptor;
50  import org.apache.hadoop.hbase.HRegionInfo;
51  import org.apache.hadoop.hbase.HRegionLocation;
52  import org.apache.hadoop.hbase.HTableDescriptor;
53  import org.apache.hadoop.hbase.ServerName;
54  import org.apache.hadoop.hbase.TableName;
55  import org.apache.hadoop.hbase.MetaTableAccessor;
56  import org.apache.hadoop.hbase.client.HBaseAdmin;
57  import org.apache.hadoop.hbase.client.HTable;
58  import org.apache.hadoop.hbase.client.NoServerForRegionException;
59  import org.apache.hadoop.hbase.regionserver.HRegionFileSystem;
60  
61  import com.google.common.base.Preconditions;
62  import com.google.common.collect.Lists;
63  import com.google.common.collect.Maps;
64  import com.google.common.collect.Sets;
65  
66  /**
67   * The {@link RegionSplitter} class provides several utilities to help in the
68   * administration lifecycle for developers who choose to manually split regions
69   * instead of having HBase handle that automatically. The most useful utilities
70   * are:
71   * <p>
72   * <ul>
73   * <li>Create a table with a specified number of pre-split regions
74   * <li>Execute a rolling split of all regions on an existing table
75   * </ul>
76   * <p>
77   * Both operations can be safely done on a live server.
78   * <p>
79   * <b>Question:</b> How do I turn off automatic splitting? <br>
80   * <b>Answer:</b> Automatic splitting is determined by the configuration value
81   * <i>HConstants.HREGION_MAX_FILESIZE</i>. It is not recommended that you set this
82   * to Long.MAX_VALUE in case you forget about manual splits. A suggested setting
83   * is 100GB, which would result in > 1hr major compactions if reached.
84   * <p>
85   * <b>Question:</b> Why did the original authors decide to manually split? <br>
86   * <b>Answer:</b> Specific workload characteristics of our use case allowed us
87   * to benefit from a manual split system.
88   * <p>
89   * <ul>
90   * <li>Data (~1k) that would grow instead of being replaced
91   * <li>Data growth was roughly uniform across all regions
92   * <li>OLTP workload. Data loss is a big deal.
93   * </ul>
94   * <p>
95   * <b>Question:</b> Why is manual splitting good for this workload? <br>
96   * <b>Answer:</b> Although automated splitting is not a bad option, there are
97   * benefits to manual splitting.
98   * <p>
99   * <ul>
100  * <li>With growing amounts of data, splits will continually be needed. Since
101  * you always know exactly what regions you have, long-term debugging and
102  * profiling is much easier with manual splits. It is hard to trace the logs to
103  * understand region level problems if it keeps splitting and getting renamed.
104  * <li>Data offlining bugs + unknown number of split regions == oh crap! If an
105  * HLog or StoreFile was mistakenly unprocessed by HBase due to a weird bug and
106  * you notice it a day or so later, you can be assured that the regions
107  * specified in these files are the same as the current regions and you have
108  * less headaches trying to restore/replay your data.
109  * <li>You can finely tune your compaction algorithm. With roughly uniform data
110  * growth, it's easy to cause split / compaction storms as the regions all
111  * roughly hit the same data size at the same time. With manual splits, you can
112  * let staggered, time-based major compactions spread out your network IO load.
113  * </ul>
114  * <p>
115  * <b>Question:</b> What's the optimal number of pre-split regions to create? <br>
116  * <b>Answer:</b> Mileage will vary depending upon your application.
117  * <p>
118  * The short answer for our application is that we started with 10 pre-split
119  * regions / server and watched our data growth over time. It's better to err on
120  * the side of too little regions and rolling split later.
121  * <p>
122  * The more complicated answer is that this depends upon the largest storefile
123  * in your region. With a growing data size, this will get larger over time. You
124  * want the largest region to be just big enough that the
125  * {@link org.apache.hadoop.hbase.regionserver.HStore} compact
126  * selection algorithm only compacts it due to a timed major. If you don't, your
127  * cluster can be prone to compaction storms as the algorithm decides to run
128  * major compactions on a large series of regions all at once. Note that
129  * compaction storms are due to the uniform data growth, not the manual split
130  * decision.
131  * <p>
132  * If you pre-split your regions too thin, you can increase the major compaction
133  * interval by configuring HConstants.MAJOR_COMPACTION_PERIOD. If your data size
134  * grows too large, use this script to perform a network IO safe rolling split
135  * of all regions.
136  */
137 @InterfaceAudience.Private
138 public class RegionSplitter {
139   static final Log LOG = LogFactory.getLog(RegionSplitter.class);
140 
141   /**
142    * A generic interface for the RegionSplitter code to use for all it's
143    * functionality. Note that the original authors of this code use
144    * {@link HexStringSplit} to partition their table and set it as default, but
145    * provided this for your custom algorithm. To use, create a new derived class
146    * from this interface and call {@link RegionSplitter#createPresplitTable} or
147    * {@link RegionSplitter#rollingSplit(String, SplitAlgorithm, Configuration)} with the
148    * argument splitClassName giving the name of your class.
149    */
150   public interface SplitAlgorithm {
151     /**
152      * Split a pre-existing region into 2 regions.
153      *
154      * @param start
155      *          first row (inclusive)
156      * @param end
157      *          last row (exclusive)
158      * @return the split row to use
159      */
160     byte[] split(byte[] start, byte[] end);
161 
162     /**
163      * Split an entire table.
164      *
165      * @param numRegions
166      *          number of regions to split the table into
167      *
168      * @throws RuntimeException
169      *           user input is validated at this time. may throw a runtime
170      *           exception in response to a parse failure
171      * @return array of split keys for the initial regions of the table. The
172      *         length of the returned array should be numRegions-1.
173      */
174     byte[][] split(int numRegions);
175 
176     /**
177      * In HBase, the first row is represented by an empty byte array. This might
178      * cause problems with your split algorithm or row printing. All your APIs
179      * will be passed firstRow() instead of empty array.
180      *
181      * @return your representation of your first row
182      */
183     byte[] firstRow();
184 
185     /**
186      * In HBase, the last row is represented by an empty byte array. This might
187      * cause problems with your split algorithm or row printing. All your APIs
188      * will be passed firstRow() instead of empty array.
189      *
190      * @return your representation of your last row
191      */
192     byte[] lastRow();
193 
194     /**
195      * In HBase, the last row is represented by an empty byte array. Set this
196      * value to help the split code understand how to evenly divide the first
197      * region.
198      *
199      * @param userInput
200      *          raw user input (may throw RuntimeException on parse failure)
201      */
202     void setFirstRow(String userInput);
203 
204     /**
205      * In HBase, the last row is represented by an empty byte array. Set this
206      * value to help the split code understand how to evenly divide the last
207      * region. Note that this last row is inclusive for all rows sharing the
208      * same prefix.
209      *
210      * @param userInput
211      *          raw user input (may throw RuntimeException on parse failure)
212      */
213     void setLastRow(String userInput);
214 
215     /**
216      * @param input
217      *          user or file input for row
218      * @return byte array representation of this row for HBase
219      */
220     byte[] strToRow(String input);
221 
222     /**
223      * @param row
224      *          byte array representing a row in HBase
225      * @return String to use for debug & file printing
226      */
227     String rowToStr(byte[] row);
228 
229     /**
230      * @return the separator character to use when storing / printing the row
231      */
232     String separator();
233 
234     /**
235      * Set the first row
236      * @param userInput byte array of the row key.
237      */
238     void setFirstRow(byte[] userInput);
239 
240     /**
241      * Set the last row
242      * @param userInput byte array of the row key.
243      */
244     void setLastRow(byte[] userInput);
245   }
246 
247   /**
248    * The main function for the RegionSplitter application. Common uses:
249    * <p>
250    * <ul>
251    * <li>create a table named 'myTable' with 60 pre-split regions containing 2
252    * column families 'test' & 'rs', assuming the keys are hex-encoded ASCII:
253    * <ul>
254    * <li>bin/hbase org.apache.hadoop.hbase.util.RegionSplitter -c 60 -f test:rs
255    * myTable HexStringSplit
256    * </ul>
257    * <li>perform a rolling split of 'myTable' (i.e. 60 => 120 regions), # 2
258    * outstanding splits at a time, assuming keys are uniformly distributed
259    * bytes:
260    * <ul>
261    * <li>bin/hbase org.apache.hadoop.hbase.util.RegionSplitter -r -o 2 myTable
262    * UniformSplit
263    * </ul>
264    * </ul>
265    *
266    * There are two SplitAlgorithms built into RegionSplitter, HexStringSplit
267    * and UniformSplit. These are different strategies for choosing region
268    * boundaries. See their source code for details.
269    *
270    * @param args
271    *          Usage: RegionSplitter &lt;TABLE&gt; &lt;SPLITALGORITHM&gt;
272    *          &lt;-c &lt;# regions&gt; -f &lt;family:family:...&gt; | -r
273    *          [-o &lt;# outstanding splits&gt;]&gt;
274    *          [-D &lt;conf.param=value&gt;]
275    * @throws IOException
276    *           HBase IO problem
277    * @throws InterruptedException
278    *           user requested exit
279    * @throws ParseException
280    *           problem parsing user input
281    */
282   @SuppressWarnings("static-access")
283   public static void main(String[] args) throws IOException,
284       InterruptedException, ParseException {
285     Configuration conf = HBaseConfiguration.create();
286 
287     // parse user input
288     Options opt = new Options();
289     opt.addOption(OptionBuilder.withArgName("property=value").hasArg()
290         .withDescription("Override HBase Configuration Settings").create("D"));
291     opt.addOption(OptionBuilder.withArgName("region count").hasArg()
292         .withDescription(
293             "Create a new table with a pre-split number of regions")
294         .create("c"));
295     opt.addOption(OptionBuilder.withArgName("family:family:...").hasArg()
296         .withDescription(
297             "Column Families to create with new table.  Required with -c")
298         .create("f"));
299     opt.addOption("h", false, "Print this usage help");
300     opt.addOption("r", false, "Perform a rolling split of an existing region");
301     opt.addOption(OptionBuilder.withArgName("count").hasArg().withDescription(
302         "Max outstanding splits that have unfinished major compactions")
303         .create("o"));
304     opt.addOption(null, "firstrow", true,
305         "First Row in Table for Split Algorithm");
306     opt.addOption(null, "lastrow", true,
307         "Last Row in Table for Split Algorithm");
308     opt.addOption(null, "risky", false,
309         "Skip verification steps to complete quickly."
310             + "STRONGLY DISCOURAGED for production systems.  ");
311     CommandLine cmd = new GnuParser().parse(opt, args);
312 
313     if (cmd.hasOption("D")) {
314       for (String confOpt : cmd.getOptionValues("D")) {
315         String[] kv = confOpt.split("=", 2);
316         if (kv.length == 2) {
317           conf.set(kv[0], kv[1]);
318           LOG.debug("-D configuration override: " + kv[0] + "=" + kv[1]);
319         } else {
320           throw new ParseException("-D option format invalid: " + confOpt);
321         }
322       }
323     }
324 
325     if (cmd.hasOption("risky")) {
326       conf.setBoolean("split.verify", false);
327     }
328 
329     boolean createTable = cmd.hasOption("c") && cmd.hasOption("f");
330     boolean rollingSplit = cmd.hasOption("r");
331     boolean oneOperOnly = createTable ^ rollingSplit;
332 
333     if (2 != cmd.getArgList().size() || !oneOperOnly || cmd.hasOption("h")) {
334       new HelpFormatter().printHelp("RegionSplitter <TABLE> <SPLITALGORITHM>\n"+
335 		  "SPLITALGORITHM is a java class name of a class implementing " +
336 		  "SplitAlgorithm, or one of the special strings HexStringSplit " +
337 		  "or UniformSplit, which are built-in split algorithms. " +
338 		  "HexStringSplit treats keys as hexadecimal ASCII, and " +
339 		  "UniformSplit treats keys as arbitrary bytes.", opt);
340       return;
341     }
342     String tableName = cmd.getArgs()[0];
343     String splitClass = cmd.getArgs()[1];
344     SplitAlgorithm splitAlgo = newSplitAlgoInstance(conf, splitClass);
345 
346     if (cmd.hasOption("firstrow")) {
347       splitAlgo.setFirstRow(cmd.getOptionValue("firstrow"));
348     }
349     if (cmd.hasOption("lastrow")) {
350       splitAlgo.setLastRow(cmd.getOptionValue("lastrow"));
351     }
352 
353     if (createTable) {
354       conf.set("split.count", cmd.getOptionValue("c"));
355       createPresplitTable(tableName, splitAlgo, cmd.getOptionValue("f").split(":"), conf);
356     }
357 
358     if (rollingSplit) {
359       if (cmd.hasOption("o")) {
360         conf.set("split.outstanding", cmd.getOptionValue("o"));
361       }
362       rollingSplit(tableName, splitAlgo, conf);
363     }
364   }
365 
366   static void createPresplitTable(String tableName, SplitAlgorithm splitAlgo,
367           String[] columnFamilies, Configuration conf) throws IOException,
368           InterruptedException {
369     final int splitCount = conf.getInt("split.count", 0);
370     Preconditions.checkArgument(splitCount > 1, "Split count must be > 1");
371 
372     Preconditions.checkArgument(columnFamilies.length > 0,
373         "Must specify at least one column family. ");
374     LOG.debug("Creating table " + tableName + " with " + columnFamilies.length
375         + " column families.  Presplitting to " + splitCount + " regions");
376 
377     HTableDescriptor desc = new HTableDescriptor(TableName.valueOf(tableName));
378     for (String cf : columnFamilies) {
379       desc.addFamily(new HColumnDescriptor(Bytes.toBytes(cf)));
380     }
381     HBaseAdmin admin = new HBaseAdmin(conf);
382     Preconditions.checkArgument(!admin.tableExists(tableName),
383         "Table already exists: " + tableName);
384     admin.createTable(desc, splitAlgo.split(splitCount));
385     admin.close();
386     LOG.debug("Table created!  Waiting for regions to show online in META...");
387     if (!conf.getBoolean("split.verify", true)) {
388       // NOTE: createTable is synchronous on the table, but not on the regions
389       int onlineRegions = 0;
390       while (onlineRegions < splitCount) {
391         onlineRegions = MetaTableAccessor.getRegionCount(conf, tableName);
392         LOG.debug(onlineRegions + " of " + splitCount + " regions online...");
393         if (onlineRegions < splitCount) {
394           Thread.sleep(10 * 1000); // sleep
395         }
396       }
397     }
398 
399     LOG.debug("Finished creating table with " + splitCount + " regions");
400   }
401 
402   static void rollingSplit(String tableName, SplitAlgorithm splitAlgo,
403           Configuration conf) throws IOException, InterruptedException {
404     final int minOS = conf.getInt("split.outstanding", 2);
405 
406     HTable table = new HTable(conf, tableName);
407 
408     // max outstanding splits. default == 50% of servers
409     final int MAX_OUTSTANDING =
410         Math.max(table.getConnection().getCurrentNrHRS() / 2, minOS);
411 
412     Path hbDir = FSUtils.getRootDir(conf);
413     Path tableDir = FSUtils.getTableDir(hbDir, table.getName());
414     Path splitFile = new Path(tableDir, "_balancedSplit");
415     FileSystem fs = FileSystem.get(conf);
416 
417     // get a list of daughter regions to create
418     LinkedList<Pair<byte[], byte[]>> tmpRegionSet = getSplits(table, splitAlgo);
419     LinkedList<Pair<byte[], byte[]>> outstanding = Lists.newLinkedList();
420     int splitCount = 0;
421     final int origCount = tmpRegionSet.size();
422 
423     // all splits must compact & we have 1 compact thread, so 2 split
424     // requests to the same RS can stall the outstanding split queue.
425     // To fix, group the regions into an RS pool and round-robin through it
426     LOG.debug("Bucketing regions by regionserver...");
427     TreeMap<String, LinkedList<Pair<byte[], byte[]>>> daughterRegions =
428       Maps.newTreeMap();
429     for (Pair<byte[], byte[]> dr : tmpRegionSet) {
430       String rsLocation = table.getRegionLocation(dr.getSecond()).
431         getHostnamePort();
432       if (!daughterRegions.containsKey(rsLocation)) {
433         LinkedList<Pair<byte[], byte[]>> entry = Lists.newLinkedList();
434         daughterRegions.put(rsLocation, entry);
435       }
436       daughterRegions.get(rsLocation).add(dr);
437     }
438     LOG.debug("Done with bucketing.  Split time!");
439     long startTime = System.currentTimeMillis();
440 
441     // open the split file and modify it as splits finish
442     FSDataInputStream tmpIn = fs.open(splitFile);
443     byte[] rawData = new byte[tmpIn.available()];
444     tmpIn.readFully(rawData);
445     tmpIn.close();
446     FSDataOutputStream splitOut = fs.create(splitFile);
447     splitOut.write(rawData);
448 
449     try {
450       // *** split code ***
451       while (!daughterRegions.isEmpty()) {
452         LOG.debug(daughterRegions.size() + " RS have regions to splt.");
453 
454         // Get RegionServer : region count mapping
455         final TreeMap<ServerName, Integer> rsSizes = Maps.newTreeMap();
456         Map<HRegionInfo, ServerName> regionsInfo = table.getRegionLocations();
457         for (ServerName rs : regionsInfo.values()) {
458           if (rsSizes.containsKey(rs)) {
459             rsSizes.put(rs, rsSizes.get(rs) + 1);
460           } else {
461             rsSizes.put(rs, 1);
462           }
463         }
464 
465         // sort the RS by the number of regions they have
466         List<String> serversLeft = Lists.newArrayList(daughterRegions .keySet());
467         Collections.sort(serversLeft, new Comparator<String>() {
468           public int compare(String o1, String o2) {
469             return rsSizes.get(o1).compareTo(rsSizes.get(o2));
470           }
471         });
472 
473         // round-robin through the RS list. Choose the lightest-loaded servers
474         // first to keep the master from load-balancing regions as we split.
475         for (String rsLoc : serversLeft) {
476           Pair<byte[], byte[]> dr = null;
477 
478           // find a region in the RS list that hasn't been moved
479           LOG.debug("Finding a region on " + rsLoc);
480           LinkedList<Pair<byte[], byte[]>> regionList = daughterRegions
481               .get(rsLoc);
482           while (!regionList.isEmpty()) {
483             dr = regionList.pop();
484 
485             // get current region info
486             byte[] split = dr.getSecond();
487             HRegionLocation regionLoc = table.getRegionLocation(split);
488 
489             // if this region moved locations
490             String newRs = regionLoc.getHostnamePort();
491             if (newRs.compareTo(rsLoc) != 0) {
492               LOG.debug("Region with " + splitAlgo.rowToStr(split)
493                   + " moved to " + newRs + ". Relocating...");
494               // relocate it, don't use it right now
495               if (!daughterRegions.containsKey(newRs)) {
496                 LinkedList<Pair<byte[], byte[]>> entry = Lists.newLinkedList();
497                 daughterRegions.put(newRs, entry);
498               }
499               daughterRegions.get(newRs).add(dr);
500               dr = null;
501               continue;
502             }
503 
504             // make sure this region wasn't already split
505             byte[] sk = regionLoc.getRegionInfo().getStartKey();
506             if (sk.length != 0) {
507               if (Bytes.equals(split, sk)) {
508                 LOG.debug("Region already split on "
509                     + splitAlgo.rowToStr(split) + ".  Skipping this region...");
510                 ++splitCount;
511                 dr = null;
512                 continue;
513               }
514               byte[] start = dr.getFirst();
515               Preconditions.checkArgument(Bytes.equals(start, sk), splitAlgo
516                   .rowToStr(start) + " != " + splitAlgo.rowToStr(sk));
517             }
518 
519             // passed all checks! found a good region
520             break;
521           }
522           if (regionList.isEmpty()) {
523             daughterRegions.remove(rsLoc);
524           }
525           if (dr == null)
526             continue;
527 
528           // we have a good region, time to split!
529           byte[] split = dr.getSecond();
530           LOG.debug("Splitting at " + splitAlgo.rowToStr(split));
531           HBaseAdmin admin = new HBaseAdmin(table.getConfiguration());
532           admin.split(table.getTableName(), split);
533 
534           LinkedList<Pair<byte[], byte[]>> finished = Lists.newLinkedList();
535           LinkedList<Pair<byte[], byte[]>> local_finished = Lists.newLinkedList();
536           if (conf.getBoolean("split.verify", true)) {
537             // we need to verify and rate-limit our splits
538             outstanding.addLast(dr);
539             // with too many outstanding splits, wait for some to finish
540             while (outstanding.size() >= MAX_OUTSTANDING) {
541               LOG.debug("Wait for outstanding splits " + outstanding.size());
542               local_finished = splitScan(outstanding, table, splitAlgo);
543               if (local_finished.isEmpty()) {
544                 Thread.sleep(30 * 1000);
545               } else {
546                 finished.addAll(local_finished);
547                 outstanding.removeAll(local_finished);
548                 LOG.debug(local_finished.size() + " outstanding splits finished");
549               }
550             }
551           } else {
552             finished.add(dr);
553           }
554 
555           // mark each finished region as successfully split.
556           for (Pair<byte[], byte[]> region : finished) {
557             splitOut.writeChars("- " + splitAlgo.rowToStr(region.getFirst())
558                 + " " + splitAlgo.rowToStr(region.getSecond()) + "\n");
559             splitCount++;
560             if (splitCount % 10 == 0) {
561               long tDiff = (System.currentTimeMillis() - startTime)
562                   / splitCount;
563               LOG.debug("STATUS UPDATE: " + splitCount + " / " + origCount
564                   + ". Avg Time / Split = "
565                   + org.apache.hadoop.util.StringUtils.formatTime(tDiff));
566             }
567           }
568         }
569       }
570       if (conf.getBoolean("split.verify", true)) {
571         while (!outstanding.isEmpty()) {
572           LOG.debug("Finally Wait for outstanding splits " + outstanding.size());
573           LinkedList<Pair<byte[], byte[]>> finished = splitScan(outstanding,
574               table, splitAlgo);
575           if (finished.isEmpty()) {
576             Thread.sleep(30 * 1000);
577           } else {
578             outstanding.removeAll(finished);
579             for (Pair<byte[], byte[]> region : finished) {
580               splitOut.writeChars("- " + splitAlgo.rowToStr(region.getFirst())
581                   + " " + splitAlgo.rowToStr(region.getSecond()) + "\n");
582               splitCount++;
583             }
584             LOG.debug("Finally " + finished.size() + " outstanding splits finished");
585           }
586         }
587       }
588       LOG.debug("All regions have been successfully split!");
589     } finally {
590       long tDiff = System.currentTimeMillis() - startTime;
591       LOG.debug("TOTAL TIME = "
592           + org.apache.hadoop.util.StringUtils.formatTime(tDiff));
593       LOG.debug("Splits = " + splitCount);
594       if (0 < splitCount) {
595         LOG.debug("Avg Time / Split = "
596             + org.apache.hadoop.util.StringUtils.formatTime(tDiff / splitCount));
597       }
598 
599       splitOut.close();
600       if (table != null){
601         table.close();
602       }
603     }
604     fs.delete(splitFile, false);
605   }
606 
607   /**
608    * @throws IOException if the specified SplitAlgorithm class couldn't be
609    * instantiated
610    */
611   public static SplitAlgorithm newSplitAlgoInstance(Configuration conf,
612           String splitClassName) throws IOException {
613     Class<?> splitClass;
614 
615     // For split algorithms builtin to RegionSplitter, the user can specify
616     // their simple class name instead of a fully qualified class name.
617     if(splitClassName.equals(HexStringSplit.class.getSimpleName())) {
618       splitClass = HexStringSplit.class;
619     } else if (splitClassName.equals(UniformSplit.class.getSimpleName())) {
620       splitClass = UniformSplit.class;
621     } else {
622       try {
623         splitClass = conf.getClassByName(splitClassName);
624       } catch (ClassNotFoundException e) {
625         throw new IOException("Couldn't load split class " + splitClassName, e);
626       }
627       if(splitClass == null) {
628         throw new IOException("Failed loading split class " + splitClassName);
629       }
630       if(!SplitAlgorithm.class.isAssignableFrom(splitClass)) {
631         throw new IOException(
632                 "Specified split class doesn't implement SplitAlgorithm");
633       }
634     }
635     try {
636       return splitClass.asSubclass(SplitAlgorithm.class).newInstance();
637     } catch (Exception e) {
638       throw new IOException("Problem loading split algorithm: ", e);
639     }
640   }
641 
642   static LinkedList<Pair<byte[], byte[]>> splitScan(
643       LinkedList<Pair<byte[], byte[]>> regionList, HTable table,
644       SplitAlgorithm splitAlgo)
645       throws IOException, InterruptedException {
646     LinkedList<Pair<byte[], byte[]>> finished = Lists.newLinkedList();
647     LinkedList<Pair<byte[], byte[]>> logicalSplitting = Lists.newLinkedList();
648     LinkedList<Pair<byte[], byte[]>> physicalSplitting = Lists.newLinkedList();
649 
650     // get table info
651     Path rootDir = FSUtils.getRootDir(table.getConfiguration());
652     Path tableDir = FSUtils.getTableDir(rootDir, table.getName());
653     FileSystem fs = tableDir.getFileSystem(table.getConfiguration());
654     HTableDescriptor htd = table.getTableDescriptor();
655 
656     // clear the cache to forcibly refresh region information
657     table.clearRegionCache();
658 
659     // for every region that hasn't been verified as a finished split
660     for (Pair<byte[], byte[]> region : regionList) {
661       byte[] start = region.getFirst();
662       byte[] split = region.getSecond();
663 
664       // see if the new split daughter region has come online
665       try {
666         HRegionInfo dri = table.getRegionLocation(split).getRegionInfo();
667         if (dri.isOffline() || !Bytes.equals(dri.getStartKey(), split)) {
668           logicalSplitting.add(region);
669           continue;
670         }
671       } catch (NoServerForRegionException nsfre) {
672         // NSFRE will occur if the old hbase:meta entry has no server assigned
673         LOG.info(nsfre);
674         logicalSplitting.add(region);
675         continue;
676       }
677 
678       try {
679         // when a daughter region is opened, a compaction is triggered
680         // wait until compaction completes for both daughter regions
681         LinkedList<HRegionInfo> check = Lists.newLinkedList();
682         check.add(table.getRegionLocation(start).getRegionInfo());
683         check.add(table.getRegionLocation(split).getRegionInfo());
684         for (HRegionInfo hri : check.toArray(new HRegionInfo[] {})) {
685           byte[] sk = hri.getStartKey();
686           if (sk.length == 0)
687             sk = splitAlgo.firstRow();
688           String startKey = splitAlgo.rowToStr(sk);
689 
690           HRegionFileSystem regionFs = HRegionFileSystem.openRegionFromFileSystem(
691               table.getConfiguration(), fs, tableDir, hri, true);
692 
693           // check every Column Family for that region
694           boolean refFound = false;
695           for (HColumnDescriptor c : htd.getFamilies()) {
696             if ((refFound = regionFs.hasReferences(htd.getTableName().getNameAsString()))) {
697               break;
698             }
699           }
700 
701           // compaction is completed when all reference files are gone
702           if (!refFound) {
703             check.remove(hri);
704           }
705         }
706         if (check.isEmpty()) {
707           finished.add(region);
708         } else {
709           physicalSplitting.add(region);
710         }
711       } catch (NoServerForRegionException nsfre) {
712         LOG.debug("No Server Exception thrown for: " + splitAlgo.rowToStr(start));
713         physicalSplitting.add(region);
714         table.clearRegionCache();
715       }
716     }
717 
718     LOG.debug("Split Scan: " + finished.size() + " finished / "
719         + logicalSplitting.size() + " split wait / "
720         + physicalSplitting.size() + " reference wait");
721 
722     return finished;
723   }
724 
725   static LinkedList<Pair<byte[], byte[]>> getSplits(HTable table,
726       SplitAlgorithm splitAlgo) throws IOException {
727     Path hbDir = FSUtils.getRootDir(table.getConfiguration());
728     Path tableDir = FSUtils.getTableDir(hbDir, table.getName());
729     Path splitFile = new Path(tableDir, "_balancedSplit");
730     FileSystem fs = tableDir.getFileSystem(table.getConfiguration());
731 
732     // using strings because (new byte[]{0}).equals(new byte[]{0}) == false
733     Set<Pair<String, String>> daughterRegions = Sets.newHashSet();
734 
735     // does a split file exist?
736     if (!fs.exists(splitFile)) {
737       // NO = fresh start. calculate splits to make
738       LOG.debug("No _balancedSplit file.  Calculating splits...");
739 
740       // query meta for all regions in the table
741       Set<Pair<byte[], byte[]>> rows = Sets.newHashSet();
742       Pair<byte[][], byte[][]> tmp = table.getStartEndKeys();
743       Preconditions.checkArgument(
744           tmp.getFirst().length == tmp.getSecond().length,
745           "Start and End rows should be equivalent");
746       for (int i = 0; i < tmp.getFirst().length; ++i) {
747         byte[] start = tmp.getFirst()[i], end = tmp.getSecond()[i];
748         if (start.length == 0)
749           start = splitAlgo.firstRow();
750         if (end.length == 0)
751           end = splitAlgo.lastRow();
752         rows.add(Pair.newPair(start, end));
753       }
754       LOG.debug("Table " + Bytes.toString(table.getTableName()) + " has "
755           + rows.size() + " regions that will be split.");
756 
757       // prepare the split file
758       Path tmpFile = new Path(tableDir, "_balancedSplit_prepare");
759       FSDataOutputStream tmpOut = fs.create(tmpFile);
760 
761       // calculate all the splits == [daughterRegions] = [(start, splitPoint)]
762       for (Pair<byte[], byte[]> r : rows) {
763         byte[] splitPoint = splitAlgo.split(r.getFirst(), r.getSecond());
764         String startStr = splitAlgo.rowToStr(r.getFirst());
765         String splitStr = splitAlgo.rowToStr(splitPoint);
766         daughterRegions.add(Pair.newPair(startStr, splitStr));
767         LOG.debug("Will Split [" + startStr + " , "
768             + splitAlgo.rowToStr(r.getSecond()) + ") at " + splitStr);
769         tmpOut.writeChars("+ " + startStr + splitAlgo.separator() + splitStr
770             + "\n");
771       }
772       tmpOut.close();
773       fs.rename(tmpFile, splitFile);
774     } else {
775       LOG.debug("_balancedSplit file found. Replay log to restore state...");
776       FSUtils.getInstance(fs, table.getConfiguration())
777         .recoverFileLease(fs, splitFile, table.getConfiguration(), null);
778 
779       // parse split file and process remaining splits
780       FSDataInputStream tmpIn = fs.open(splitFile);
781       StringBuilder sb = new StringBuilder(tmpIn.available());
782       while (tmpIn.available() > 0) {
783         sb.append(tmpIn.readChar());
784       }
785       tmpIn.close();
786       for (String line : sb.toString().split("\n")) {
787         String[] cmd = line.split(splitAlgo.separator());
788         Preconditions.checkArgument(3 == cmd.length);
789         byte[] start = splitAlgo.strToRow(cmd[1]);
790         String startStr = splitAlgo.rowToStr(start);
791         byte[] splitPoint = splitAlgo.strToRow(cmd[2]);
792         String splitStr = splitAlgo.rowToStr(splitPoint);
793         Pair<String, String> r = Pair.newPair(startStr, splitStr);
794         if (cmd[0].equals("+")) {
795           LOG.debug("Adding: " + r);
796           daughterRegions.add(r);
797         } else {
798           LOG.debug("Removing: " + r);
799           Preconditions.checkArgument(cmd[0].equals("-"),
800               "Unknown option: " + cmd[0]);
801           Preconditions.checkState(daughterRegions.contains(r),
802               "Missing row: " + r);
803           daughterRegions.remove(r);
804         }
805       }
806       LOG.debug("Done reading. " + daughterRegions.size() + " regions left.");
807     }
808     LinkedList<Pair<byte[], byte[]>> ret = Lists.newLinkedList();
809     for (Pair<String, String> r : daughterRegions) {
810       ret.add(Pair.newPair(splitAlgo.strToRow(r.getFirst()), splitAlgo
811           .strToRow(r.getSecond())));
812     }
813     return ret;
814   }
815 
816   /**
817    * HexStringSplit is a well-known {@link SplitAlgorithm} for choosing region
818    * boundaries. The format of a HexStringSplit region boundary is the ASCII
819    * representation of an MD5 checksum, or any other uniformly distributed
820    * hexadecimal value. Row are hex-encoded long values in the range
821    * <b>"00000000" => "FFFFFFFF"</b> and are left-padded with zeros to keep the
822    * same order lexicographically as if they were binary.
823    *
824    * Since this split algorithm uses hex strings as keys, it is easy to read &
825    * write in the shell but takes up more space and may be non-intuitive.
826    */
827   public static class HexStringSplit implements SplitAlgorithm {
828     final static String DEFAULT_MIN_HEX = "00000000";
829     final static String DEFAULT_MAX_HEX = "FFFFFFFF";
830 
831     String firstRow = DEFAULT_MIN_HEX;
832     BigInteger firstRowInt = BigInteger.ZERO;
833     String lastRow = DEFAULT_MAX_HEX;
834     BigInteger lastRowInt = new BigInteger(lastRow, 16);
835     int rowComparisonLength = lastRow.length();
836 
837     public byte[] split(byte[] start, byte[] end) {
838       BigInteger s = convertToBigInteger(start);
839       BigInteger e = convertToBigInteger(end);
840       Preconditions.checkArgument(!e.equals(BigInteger.ZERO));
841       return convertToByte(split2(s, e));
842     }
843 
844     public byte[][] split(int n) {
845       Preconditions.checkArgument(lastRowInt.compareTo(firstRowInt) > 0,
846           "last row (%s) is configured less than first row (%s)", lastRow,
847           firstRow);
848       // +1 to range because the last row is inclusive
849       BigInteger range = lastRowInt.subtract(firstRowInt).add(BigInteger.ONE);
850       Preconditions.checkState(range.compareTo(BigInteger.valueOf(n)) >= 0,
851           "split granularity (%s) is greater than the range (%s)", n, range);
852 
853       BigInteger[] splits = new BigInteger[n - 1];
854       BigInteger sizeOfEachSplit = range.divide(BigInteger.valueOf(n));
855       for (int i = 1; i < n; i++) {
856         // NOTE: this means the last region gets all the slop.
857         // This is not a big deal if we're assuming n << MAXHEX
858         splits[i - 1] = firstRowInt.add(sizeOfEachSplit.multiply(BigInteger
859             .valueOf(i)));
860       }
861       return convertToBytes(splits);
862     }
863 
864     public byte[] firstRow() {
865       return convertToByte(firstRowInt);
866     }
867 
868     public byte[] lastRow() {
869       return convertToByte(lastRowInt);
870     }
871 
872     public void setFirstRow(String userInput) {
873       firstRow = userInput;
874       firstRowInt = new BigInteger(firstRow, 16);
875     }
876 
877     public void setLastRow(String userInput) {
878       lastRow = userInput;
879       lastRowInt = new BigInteger(lastRow, 16);
880       // Precondition: lastRow > firstRow, so last's length is the greater
881       rowComparisonLength = lastRow.length();
882     }
883 
884     public byte[] strToRow(String in) {
885       return convertToByte(new BigInteger(in, 16));
886     }
887 
888     public String rowToStr(byte[] row) {
889       return Bytes.toStringBinary(row);
890     }
891 
892     public String separator() {
893       return " ";
894     }
895 
896     @Override
897     public void setFirstRow(byte[] userInput) {
898       firstRow = Bytes.toString(userInput);
899     }
900 
901     @Override
902     public void setLastRow(byte[] userInput) {
903       lastRow = Bytes.toString(userInput);
904     }
905 
906     /**
907      * Divide 2 numbers in half (for split algorithm)
908      *
909      * @param a number #1
910      * @param b number #2
911      * @return the midpoint of the 2 numbers
912      */
913     public BigInteger split2(BigInteger a, BigInteger b) {
914       return a.add(b).divide(BigInteger.valueOf(2)).abs();
915     }
916 
917     /**
918      * Returns an array of bytes corresponding to an array of BigIntegers
919      *
920      * @param bigIntegers numbers to convert
921      * @return bytes corresponding to the bigIntegers
922      */
923     public byte[][] convertToBytes(BigInteger[] bigIntegers) {
924       byte[][] returnBytes = new byte[bigIntegers.length][];
925       for (int i = 0; i < bigIntegers.length; i++) {
926         returnBytes[i] = convertToByte(bigIntegers[i]);
927       }
928       return returnBytes;
929     }
930 
931     /**
932      * Returns the bytes corresponding to the BigInteger
933      *
934      * @param bigInteger number to convert
935      * @param pad padding length
936      * @return byte corresponding to input BigInteger
937      */
938     public static byte[] convertToByte(BigInteger bigInteger, int pad) {
939       String bigIntegerString = bigInteger.toString(16);
940       bigIntegerString = StringUtils.leftPad(bigIntegerString, pad, '0');
941       return Bytes.toBytes(bigIntegerString);
942     }
943 
944     /**
945      * Returns the bytes corresponding to the BigInteger
946      *
947      * @param bigInteger number to convert
948      * @return corresponding bytes
949      */
950     public byte[] convertToByte(BigInteger bigInteger) {
951       return convertToByte(bigInteger, rowComparisonLength);
952     }
953 
954     /**
955      * Returns the BigInteger represented by the byte array
956      *
957      * @param row byte array representing row
958      * @return the corresponding BigInteger
959      */
960     public BigInteger convertToBigInteger(byte[] row) {
961       return (row.length > 0) ? new BigInteger(Bytes.toString(row), 16)
962           : BigInteger.ZERO;
963     }
964 
965     @Override
966     public String toString() {
967       return this.getClass().getSimpleName() + " [" + rowToStr(firstRow())
968           + "," + rowToStr(lastRow()) + "]";
969     }
970   }
971 
972   /**
973    * A SplitAlgorithm that divides the space of possible keys evenly. Useful
974    * when the keys are approximately uniform random bytes (e.g. hashes). Rows
975    * are raw byte values in the range <b>00 => FF</b> and are right-padded with
976    * zeros to keep the same memcmp() order. This is the natural algorithm to use
977    * for a byte[] environment and saves space, but is not necessarily the
978    * easiest for readability.
979    */
980   public static class UniformSplit implements SplitAlgorithm {
981     static final byte xFF = (byte) 0xFF;
982     byte[] firstRowBytes = ArrayUtils.EMPTY_BYTE_ARRAY;
983     byte[] lastRowBytes =
984             new byte[] {xFF, xFF, xFF, xFF, xFF, xFF, xFF, xFF};
985     public byte[] split(byte[] start, byte[] end) {
986       return Bytes.split(start, end, 1)[1];
987     }
988 
989     @Override
990     public byte[][] split(int numRegions) {
991       Preconditions.checkArgument(
992           Bytes.compareTo(lastRowBytes, firstRowBytes) > 0,
993           "last row (%s) is configured less than first row (%s)",
994           Bytes.toStringBinary(lastRowBytes),
995           Bytes.toStringBinary(firstRowBytes));
996 
997       byte[][] splits = Bytes.split(firstRowBytes, lastRowBytes, true,
998           numRegions - 1);
999       Preconditions.checkState(splits != null,
1000           "Could not split region with given user input: " + this);
1001 
1002       // remove endpoints, which are included in the splits list
1003       return Arrays.copyOfRange(splits, 1, splits.length - 1);
1004     }
1005 
1006     @Override
1007     public byte[] firstRow() {
1008       return firstRowBytes;
1009     }
1010 
1011     @Override
1012     public byte[] lastRow() {
1013       return lastRowBytes;
1014     }
1015 
1016     @Override
1017     public void setFirstRow(String userInput) {
1018       firstRowBytes = Bytes.toBytesBinary(userInput);
1019     }
1020 
1021     @Override
1022     public void setLastRow(String userInput) {
1023       lastRowBytes = Bytes.toBytesBinary(userInput);
1024     }
1025 
1026 
1027     @Override
1028     public void setFirstRow(byte[] userInput) {
1029       firstRowBytes = userInput;
1030     }
1031 
1032     @Override
1033     public void setLastRow(byte[] userInput) {
1034       lastRowBytes = userInput;
1035     }
1036 
1037     @Override
1038     public byte[] strToRow(String input) {
1039       return Bytes.toBytesBinary(input);
1040     }
1041 
1042     @Override
1043     public String rowToStr(byte[] row) {
1044       return Bytes.toStringBinary(row);
1045     }
1046 
1047     @Override
1048     public String separator() {
1049       return ",";
1050     }
1051 
1052     @Override
1053     public String toString() {
1054       return this.getClass().getSimpleName() + " [" + rowToStr(firstRow())
1055           + "," + rowToStr(lastRow()) + "]";
1056     }
1057   }
1058 }