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 org.junit.Assert.assertEquals;
22  
23  import com.google.common.base.Joiner;
24  
25  import org.apache.commons.cli.CommandLine;
26  import org.apache.commons.lang.RandomStringUtils;
27  import org.apache.commons.logging.Log;
28  import org.apache.commons.logging.LogFactory;
29  import org.apache.hadoop.conf.Configuration;
30  import org.apache.hadoop.fs.Path;
31  import org.apache.hadoop.hbase.Cell;
32  import org.apache.hadoop.hbase.CellUtil;
33  import org.apache.hadoop.hbase.HBaseConfiguration;
34  import org.apache.hadoop.hbase.HBaseTestingUtility;
35  import org.apache.hadoop.hbase.HTableDescriptor;
36  import org.apache.hadoop.hbase.IntegrationTestBase;
37  import org.apache.hadoop.hbase.IntegrationTestingUtility;
38  import org.apache.hadoop.hbase.KeyValue;
39  import org.apache.hadoop.hbase.TableName;
40  import org.apache.hadoop.hbase.client.Admin;
41  import org.apache.hadoop.hbase.client.Connection;
42  import org.apache.hadoop.hbase.client.ConnectionFactory;
43  import org.apache.hadoop.hbase.client.Consistency;
44  import org.apache.hadoop.hbase.client.RegionLocator;
45  import org.apache.hadoop.hbase.client.Result;
46  import org.apache.hadoop.hbase.client.Scan;
47  import org.apache.hadoop.hbase.client.Table;
48  import org.apache.hadoop.hbase.coprocessor.BaseRegionObserver;
49  import org.apache.hadoop.hbase.coprocessor.ObserverContext;
50  import org.apache.hadoop.hbase.coprocessor.RegionCoprocessorEnvironment;
51  import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
52  import org.apache.hadoop.hbase.regionserver.InternalScanner;
53  import org.apache.hadoop.hbase.regionserver.RegionScanner;
54  import org.apache.hadoop.hbase.testclassification.IntegrationTests;
55  import org.apache.hadoop.hbase.util.Bytes;
56  import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
57  import org.apache.hadoop.hbase.util.RegionSplitter;
58  import org.apache.hadoop.io.LongWritable;
59  import org.apache.hadoop.io.NullWritable;
60  import org.apache.hadoop.io.Writable;
61  import org.apache.hadoop.io.WritableComparable;
62  import org.apache.hadoop.io.WritableComparator;
63  import org.apache.hadoop.io.WritableUtils;
64  import org.apache.hadoop.mapreduce.InputFormat;
65  import org.apache.hadoop.mapreduce.InputSplit;
66  import org.apache.hadoop.mapreduce.Job;
67  import org.apache.hadoop.mapreduce.JobContext;
68  import org.apache.hadoop.mapreduce.Mapper;
69  import org.apache.hadoop.mapreduce.Partitioner;
70  import org.apache.hadoop.mapreduce.RecordReader;
71  import org.apache.hadoop.mapreduce.Reducer;
72  import org.apache.hadoop.mapreduce.TaskAttemptContext;
73  import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
74  import org.apache.hadoop.util.ToolRunner;
75  import org.junit.Test;
76  import org.junit.experimental.categories.Category;
77  
78  import java.io.DataInput;
79  import java.io.DataOutput;
80  import java.io.IOException;
81  import java.util.ArrayList;
82  import java.util.List;
83  import java.util.Map;
84  import java.util.Random;
85  import java.util.Set;
86  import java.util.concurrent.atomic.AtomicLong;
87  
88  /**
89   * Test Bulk Load and MR on a distributed cluster.
90   * It starts an MR job that creates linked chains
91   *
92   * The format of rows is like this:
93   * Row Key -> Long
94   *
95   * L:<< Chain Id >> -> Row Key of the next link in the chain
96   * S:<< Chain Id >> -> The step in the chain that his link is.
97   * D:<< Chain Id >> -> Random Data.
98   *
99   * All chains start on row 0.
100  * All rk's are > 0.
101  *
102  * After creating the linked lists they are walked over using a TableMapper based Mapreduce Job.
103  *
104  * There are a few options exposed:
105  *
106  * hbase.IntegrationTestBulkLoad.chainLength
107  * The number of rows that will be part of each and every chain.
108  *
109  * hbase.IntegrationTestBulkLoad.numMaps
110  * The number of mappers that will be run.  Each mapper creates on linked list chain.
111  *
112  * hbase.IntegrationTestBulkLoad.numImportRounds
113  * How many jobs will be run to create linked lists.
114  *
115  * hbase.IntegrationTestBulkLoad.tableName
116  * The name of the table.
117  *
118  * hbase.IntegrationTestBulkLoad.replicaCount
119  * How many region replicas to configure for the table under test.
120  */
121 @Category(IntegrationTests.class)
122 public class IntegrationTestBulkLoad extends IntegrationTestBase {
123 
124   private static final Log LOG = LogFactory.getLog(IntegrationTestBulkLoad.class);
125 
126   private static final byte[] CHAIN_FAM = Bytes.toBytes("L");
127   private static final byte[] SORT_FAM  = Bytes.toBytes("S");
128   private static final byte[] DATA_FAM  = Bytes.toBytes("D");
129 
130   private static String CHAIN_LENGTH_KEY = "hbase.IntegrationTestBulkLoad.chainLength";
131   private static int CHAIN_LENGTH = 500000;
132 
133   private static String NUM_MAPS_KEY = "hbase.IntegrationTestBulkLoad.numMaps";
134   private static int NUM_MAPS = 1;
135 
136   private static String NUM_IMPORT_ROUNDS_KEY = "hbase.IntegrationTestBulkLoad.numImportRounds";
137   private static int NUM_IMPORT_ROUNDS = 1;
138 
139   private static String ROUND_NUM_KEY = "hbase.IntegrationTestBulkLoad.roundNum";
140 
141   private static String TABLE_NAME_KEY = "hbase.IntegrationTestBulkLoad.tableName";
142   private static String TABLE_NAME = "IntegrationTestBulkLoad";
143 
144   private static String NUM_REPLICA_COUNT_KEY = "hbase.IntegrationTestBulkLoad.replicaCount";
145   private static int NUM_REPLICA_COUNT_DEFAULT = 1;
146 
147   private static final String OPT_LOAD = "load";
148   private static final String OPT_CHECK = "check";
149 
150   private boolean load = false;
151   private boolean check = false;
152 
153   public static class SlowMeCoproScanOperations extends BaseRegionObserver {
154     static final AtomicLong sleepTime = new AtomicLong(2000);
155     Random r = new Random();
156     AtomicLong countOfNext = new AtomicLong(0);
157     AtomicLong countOfOpen = new AtomicLong(0);
158     public SlowMeCoproScanOperations() {}
159     @Override
160     public RegionScanner preScannerOpen(final ObserverContext<RegionCoprocessorEnvironment> e,
161         final Scan scan, final RegionScanner s) throws IOException {
162       if (countOfOpen.incrementAndGet() == 2) { //slowdown openScanner randomly
163         slowdownCode(e);
164       }
165       return s;
166     }
167 
168     @Override
169     public boolean preScannerNext(final ObserverContext<RegionCoprocessorEnvironment> e,
170         final InternalScanner s, final List<Result> results,
171         final int limit, final boolean hasMore) throws IOException {
172       //this will slow down a certain next operation if the conditions are met. The slowness
173       //will allow the call to go to a replica
174       countOfNext.incrementAndGet();
175       if (countOfNext.get() == 0 || countOfNext.get() == 4) {
176         slowdownCode(e);
177       }
178       return true;
179     }
180     protected void slowdownCode(final ObserverContext<RegionCoprocessorEnvironment> e) {
181       if (e.getEnvironment().getRegion().getRegionInfo().getReplicaId() == 0) {
182         try {
183           if (sleepTime.get() > 0) {
184             LOG.info("Sleeping for " + sleepTime.get() + " ms");
185             Thread.sleep(sleepTime.get());
186           }
187         } catch (InterruptedException e1) {
188           LOG.error(e1);
189         }
190       }
191     }
192   }
193 
194   /**
195    * Modify table {@code getTableName()} to carry {@link SlowMeCoproScanOperations}.
196    */
197   private void installSlowingCoproc() throws IOException, InterruptedException {
198     int replicaCount = conf.getInt(NUM_REPLICA_COUNT_KEY, NUM_REPLICA_COUNT_DEFAULT);
199     if (replicaCount == NUM_REPLICA_COUNT_DEFAULT) return;
200 
201     TableName t = getTablename();
202     Admin admin = util.getHBaseAdmin();
203     HTableDescriptor desc = admin.getTableDescriptor(t);
204     desc.addCoprocessor(SlowMeCoproScanOperations.class.getName());
205     HBaseTestingUtility.modifyTableSync(admin, desc);
206     //sleep for sometime. Hope is that the regions are closed/opened before 
207     //the sleep returns. TODO: do this better
208     Thread.sleep(30000);
209   }
210 
211   @Test
212   public void testBulkLoad() throws Exception {
213     runLoad();
214     installSlowingCoproc();
215     runCheck();
216   }
217 
218   public void runLoad() throws Exception {
219     setupTable();
220     int numImportRounds = getConf().getInt(NUM_IMPORT_ROUNDS_KEY, NUM_IMPORT_ROUNDS);
221     LOG.info("Running load with numIterations:" + numImportRounds);
222     for (int i = 0; i < numImportRounds; i++) {
223       runLinkedListMRJob(i);
224     }
225   }
226 
227   private byte[][] getSplits(int numRegions) {
228     RegionSplitter.UniformSplit split = new RegionSplitter.UniformSplit();
229     split.setFirstRow(Bytes.toBytes(0L));
230     split.setLastRow(Bytes.toBytes(Long.MAX_VALUE));
231     return split.split(numRegions);
232   }
233 
234   private void setupTable() throws IOException, InterruptedException {
235     if (util.getHBaseAdmin().tableExists(getTablename())) {
236       util.deleteTable(getTablename());
237     }
238 
239     util.createTable(
240         getTablename().getName(),
241         new byte[][]{CHAIN_FAM, SORT_FAM, DATA_FAM},
242         getSplits(16)
243     );
244 
245     int replicaCount = conf.getInt(NUM_REPLICA_COUNT_KEY, NUM_REPLICA_COUNT_DEFAULT);
246     if (replicaCount == NUM_REPLICA_COUNT_DEFAULT) return;
247 
248     TableName t = getTablename();
249     HBaseTestingUtility.setReplicas(util.getHBaseAdmin(), t, replicaCount);
250   }
251 
252   private void runLinkedListMRJob(int iteration) throws Exception {
253     String jobName =  IntegrationTestBulkLoad.class.getSimpleName() + " - " +
254         EnvironmentEdgeManager.currentTime();
255     Configuration conf = new Configuration(util.getConfiguration());
256     Path p = util.getDataTestDirOnTestFS(getTablename() +  "-" + iteration);
257 
258     conf.setBoolean("mapreduce.map.speculative", false);
259     conf.setBoolean("mapreduce.reduce.speculative", false);
260     conf.setInt(ROUND_NUM_KEY, iteration);
261 
262     Job job = new Job(conf);
263 
264     job.setJobName(jobName);
265 
266     // set the input format so that we can create map tasks with no data input.
267     job.setInputFormatClass(ITBulkLoadInputFormat.class);
268 
269     // Set the mapper classes.
270     job.setMapperClass(LinkedListCreationMapper.class);
271     job.setMapOutputKeyClass(ImmutableBytesWritable.class);
272     job.setMapOutputValueClass(KeyValue.class);
273 
274     // Use the identity reducer
275     // So nothing to do here.
276 
277     // Set this jar.
278     job.setJarByClass(getClass());
279 
280     // Set where to place the hfiles.
281     FileOutputFormat.setOutputPath(job, p);
282     try (Connection conn = ConnectionFactory.createConnection(conf);
283         Admin admin = conn.getAdmin();
284         Table table = conn.getTable(getTablename());
285         RegionLocator regionLocator = conn.getRegionLocator(getTablename())) {
286       
287       // Configure the partitioner and other things needed for HFileOutputFormat.
288       HFileOutputFormat2.configureIncrementalLoad(job, table.getTableDescriptor(), regionLocator);
289 
290       // Run the job making sure it works.
291       assertEquals(true, job.waitForCompletion(true));
292 
293       // Create a new loader.
294       LoadIncrementalHFiles loader = new LoadIncrementalHFiles(conf);
295 
296       // Load the HFiles in.
297       loader.doBulkLoad(p, admin, table, regionLocator);
298     }
299 
300     // Delete the files.
301     util.getTestFileSystem().delete(p, true);
302   }
303 
304   public static class EmptySplit extends InputSplit implements Writable {
305     @Override
306     public void write(DataOutput out) throws IOException { }
307     @Override
308     public void readFields(DataInput in) throws IOException { }
309     @Override
310     public long getLength() { return 0L; }
311     @Override
312     public String[] getLocations() { return new String[0]; }
313   }
314 
315   public static class FixedRecordReader<K, V> extends RecordReader<K, V> {
316     private int index = -1;
317     private K[] keys;
318     private V[] values;
319 
320     public FixedRecordReader(K[] keys, V[] values) {
321       this.keys = keys;
322       this.values = values;
323     }
324     @Override
325     public void initialize(InputSplit split, TaskAttemptContext context) throws IOException,
326     InterruptedException { }
327     @Override
328     public boolean nextKeyValue() throws IOException, InterruptedException {
329       return ++index < keys.length;
330     }
331     @Override
332     public K getCurrentKey() throws IOException, InterruptedException {
333       return keys[index];
334     }
335     @Override
336     public V getCurrentValue() throws IOException, InterruptedException {
337       return values[index];
338     }
339     @Override
340     public float getProgress() throws IOException, InterruptedException {
341       return (float)index / keys.length;
342     }
343     @Override
344     public void close() throws IOException {
345     }
346   }
347 
348   public static class ITBulkLoadInputFormat extends InputFormat<LongWritable, LongWritable> {
349     @Override
350     public List<InputSplit> getSplits(JobContext context) throws IOException, InterruptedException {
351       int numSplits = context.getConfiguration().getInt(NUM_MAPS_KEY, NUM_MAPS);
352       ArrayList<InputSplit> ret = new ArrayList<InputSplit>(numSplits);
353       for (int i = 0; i < numSplits; ++i) {
354         ret.add(new EmptySplit());
355       }
356       return ret;
357     }
358 
359     @Override
360     public RecordReader<LongWritable, LongWritable> createRecordReader(InputSplit split,
361       TaskAttemptContext context)
362           throws IOException, InterruptedException {
363       int taskId = context.getTaskAttemptID().getTaskID().getId();
364       int numMapTasks = context.getConfiguration().getInt(NUM_MAPS_KEY, NUM_MAPS);
365       int numIterations = context.getConfiguration().getInt(NUM_IMPORT_ROUNDS_KEY, NUM_IMPORT_ROUNDS);
366       int iteration = context.getConfiguration().getInt(ROUND_NUM_KEY, 0);
367 
368       taskId = taskId + iteration * numMapTasks;
369       numMapTasks = numMapTasks * numIterations;
370 
371       long chainId = Math.abs(new Random().nextLong());
372       chainId = chainId - (chainId % numMapTasks) + taskId; // ensure that chainId is unique per task and across iterations
373       LongWritable[] keys = new LongWritable[] {new LongWritable(chainId)};
374 
375       return new FixedRecordReader<LongWritable, LongWritable>(keys, keys);
376     }
377   }
378 
379   /**
380    * Mapper that creates a linked list of KeyValues.
381    *
382    * Each map task generates one linked list.
383    * All lists start on row key 0L.
384    * All lists should be CHAIN_LENGTH long.
385    */
386   public static class LinkedListCreationMapper
387       extends Mapper<LongWritable, LongWritable, ImmutableBytesWritable, KeyValue> {
388 
389     private Random rand = new Random();
390 
391     @Override
392     protected void map(LongWritable key, LongWritable value, Context context)
393         throws IOException, InterruptedException {
394       long chainId = value.get();
395       LOG.info("Starting mapper with chainId:" + chainId);
396 
397       byte[] chainIdArray = Bytes.toBytes(chainId);
398       long currentRow = 0;
399 
400       long chainLength = context.getConfiguration().getLong(CHAIN_LENGTH_KEY, CHAIN_LENGTH);
401       long nextRow = getNextRow(0, chainLength);
402 
403       for (long i = 0; i < chainLength; i++) {
404         byte[] rk = Bytes.toBytes(currentRow);
405 
406         // Next link in the chain.
407         KeyValue linkKv = new KeyValue(rk, CHAIN_FAM, chainIdArray, Bytes.toBytes(nextRow));
408         // What link in the chain this is.
409         KeyValue sortKv = new KeyValue(rk, SORT_FAM, chainIdArray, Bytes.toBytes(i));
410         // Added data so that large stores are created.
411         KeyValue dataKv = new KeyValue(rk, DATA_FAM, chainIdArray,
412           Bytes.toBytes(RandomStringUtils.randomAlphabetic(50))
413         );
414 
415         // Emit the key values.
416         context.write(new ImmutableBytesWritable(rk), linkKv);
417         context.write(new ImmutableBytesWritable(rk), sortKv);
418         context.write(new ImmutableBytesWritable(rk), dataKv);
419         // Move to the next row.
420         currentRow = nextRow;
421         nextRow = getNextRow(i+1, chainLength);
422       }
423     }
424 
425     /** Returns a unique row id within this chain for this index */
426     private long getNextRow(long index, long chainLength) {
427       long nextRow = Math.abs(rand.nextLong());
428       // use significant bits from the random number, but pad with index to ensure it is unique
429       // this also ensures that we do not reuse row = 0
430       // row collisions from multiple mappers are fine, since we guarantee unique chainIds
431       nextRow = nextRow - (nextRow % chainLength) + index;
432       return nextRow;
433     }
434   }
435 
436   /**
437    * Writable class used as the key to group links in the linked list.
438    *
439    * Used as the key emited from a pass over the table.
440    */
441   public static class LinkKey implements WritableComparable<LinkKey> {
442 
443     private Long chainId;
444 
445     public Long getOrder() {
446       return order;
447     }
448 
449     public Long getChainId() {
450       return chainId;
451     }
452 
453     private Long order;
454 
455     public LinkKey() {}
456 
457     public LinkKey(long chainId, long order) {
458       this.chainId = chainId;
459       this.order = order;
460     }
461 
462     @Override
463     public int compareTo(LinkKey linkKey) {
464       int res = getChainId().compareTo(linkKey.getChainId());
465       if (res == 0) {
466         res = getOrder().compareTo(linkKey.getOrder());
467       }
468       return res;
469     }
470 
471     @Override
472     public void write(DataOutput dataOutput) throws IOException {
473       WritableUtils.writeVLong(dataOutput, chainId);
474       WritableUtils.writeVLong(dataOutput, order);
475     }
476 
477     @Override
478     public void readFields(DataInput dataInput) throws IOException {
479       chainId = WritableUtils.readVLong(dataInput);
480       order = WritableUtils.readVLong(dataInput);
481     }
482   }
483 
484   /**
485    * Writable used as the value emitted from a pass over the hbase table.
486    */
487   public static class LinkChain implements WritableComparable<LinkChain> {
488 
489     public Long getNext() {
490       return next;
491     }
492 
493     public Long getRk() {
494       return rk;
495     }
496 
497     public LinkChain() {}
498 
499     public LinkChain(Long rk, Long next) {
500       this.rk = rk;
501       this.next = next;
502     }
503 
504     private Long rk;
505     private Long next;
506 
507     @Override
508     public int compareTo(LinkChain linkChain) {
509       int res = getRk().compareTo(linkChain.getRk());
510       if (res == 0) {
511         res = getNext().compareTo(linkChain.getNext());
512       }
513       return res;
514     }
515 
516     @Override
517     public void write(DataOutput dataOutput) throws IOException {
518       WritableUtils.writeVLong(dataOutput, rk);
519       WritableUtils.writeVLong(dataOutput, next);
520     }
521 
522     @Override
523     public void readFields(DataInput dataInput) throws IOException {
524       rk = WritableUtils.readVLong(dataInput);
525       next = WritableUtils.readVLong(dataInput);
526     }
527   }
528 
529   /**
530    * Class to figure out what partition to send a link in the chain to.  This is based upon
531    * the linkKey's ChainId.
532    */
533   public static class NaturalKeyPartitioner extends Partitioner<LinkKey, LinkChain> {
534     @Override
535     public int getPartition(LinkKey linkKey,
536                             LinkChain linkChain,
537                             int numPartitions) {
538       int hash = linkKey.getChainId().hashCode();
539       return Math.abs(hash % numPartitions);
540     }
541   }
542 
543   /**
544    * Comparator used to figure out if a linkKey should be grouped together.  This is based upon the
545    * linkKey's ChainId.
546    */
547   public static class NaturalKeyGroupingComparator extends WritableComparator {
548 
549     protected NaturalKeyGroupingComparator() {
550       super(LinkKey.class, true);
551     }
552 
553     @Override
554     public int compare(WritableComparable w1, WritableComparable w2) {
555       LinkKey k1 = (LinkKey) w1;
556       LinkKey k2 = (LinkKey) w2;
557 
558       return k1.getChainId().compareTo(k2.getChainId());
559     }
560   }
561 
562   /**
563    * Comparator used to order linkKeys so that they are passed to a reducer in order.  This is based
564    * upon linkKey ChainId and Order.
565    */
566   public static class CompositeKeyComparator extends WritableComparator {
567 
568     protected CompositeKeyComparator() {
569       super(LinkKey.class, true);
570     }
571 
572     @Override
573     public int compare(WritableComparable w1, WritableComparable w2) {
574       LinkKey k1 = (LinkKey) w1;
575       LinkKey k2 = (LinkKey) w2;
576 
577       return k1.compareTo(k2);
578     }
579   }
580 
581   /**
582    * Mapper to pass over the table.
583    *
584    * For every row there could be multiple chains that landed on this row. So emit a linkKey
585    * and value for each.
586    */
587   public static class LinkedListCheckingMapper extends TableMapper<LinkKey, LinkChain> {
588     @Override
589     protected void map(ImmutableBytesWritable key, Result value, Context context)
590         throws IOException, InterruptedException {
591       long longRk = Bytes.toLong(value.getRow());
592 
593       for (Map.Entry<byte[], byte[]> entry : value.getFamilyMap(CHAIN_FAM).entrySet()) {
594         long chainId = Bytes.toLong(entry.getKey());
595         long next = Bytes.toLong(entry.getValue());
596         Cell c = value.getColumnCells(SORT_FAM, entry.getKey()).get(0);
597         long order = Bytes.toLong(CellUtil.cloneValue(c));
598         context.write(new LinkKey(chainId, order), new LinkChain(longRk, next));
599       }
600     }
601   }
602 
603   /**
604    * Class that does the actual checking of the links.
605    *
606    * All links in the chain should be grouped and sorted when sent to this class.  Then the chain
607    * will be traversed making sure that no link is missing and that the chain is the correct length.
608    *
609    * This will throw an exception if anything is not correct.  That causes the job to fail if any
610    * data is corrupt.
611    */
612   public static class LinkedListCheckingReducer
613       extends Reducer<LinkKey, LinkChain, NullWritable, NullWritable> {
614     @Override
615     protected void reduce(LinkKey key, Iterable<LinkChain> values, Context context)
616         throws java.io.IOException, java.lang.InterruptedException {
617       long next = -1L;
618       long prev = -1L;
619       long count = 0L;
620 
621       for (LinkChain lc : values) {
622 
623         if (next == -1) {
624           if (lc.getRk() != 0L) {
625             String msg = "Chains should all start at rk 0, but read rk " + lc.getRk()
626                 + ". Chain:" + key.chainId + ", order:" + key.order;
627             logError(msg, context);
628             throw new RuntimeException(msg);
629           }
630           next = lc.getNext();
631         } else {
632           if (next != lc.getRk()) {
633             String msg = "Missing a link in the chain. Prev rk " + prev + " was, expecting "
634                 + next + " but got " + lc.getRk() + ". Chain:" + key.chainId
635                 + ", order:" + key.order;
636             logError(msg, context);
637             throw new RuntimeException(msg);
638           }
639           prev = lc.getRk();
640           next = lc.getNext();
641         }
642         count++;
643       }
644 
645       int expectedChainLen = context.getConfiguration().getInt(CHAIN_LENGTH_KEY, CHAIN_LENGTH);
646       if (count != expectedChainLen) {
647         String msg = "Chain wasn't the correct length.  Expected " + expectedChainLen + " got "
648             + count + ". Chain:" + key.chainId + ", order:" + key.order;
649         logError(msg, context);
650         throw new RuntimeException(msg);
651       }
652     }
653 
654     private static void logError(String msg, Context context) throws IOException {
655       HBaseTestingUtility util = new HBaseTestingUtility(context.getConfiguration());
656       TableName table = getTableName(context.getConfiguration());
657 
658       LOG.error("Failure in chain verification: " + msg);
659       LOG.error("cluster status:\n" + util.getHBaseClusterInterface().getClusterStatus());
660       LOG.error("table regions:\n"
661           + Joiner.on("\n").join(util.getHBaseAdmin().getTableRegions(table)));
662     }
663   }
664 
665   /**
666    * After adding data to the table start a mr job to
667    * @throws IOException
668    * @throws ClassNotFoundException
669    * @throws InterruptedException
670    */
671   private void runCheck() throws IOException, ClassNotFoundException, InterruptedException {
672     LOG.info("Running check");
673     Configuration conf = getConf();
674     String jobName = getTablename() + "_check" + EnvironmentEdgeManager.currentTime();
675     Path p = util.getDataTestDirOnTestFS(jobName);
676 
677     Job job = new Job(conf);
678     job.setJarByClass(getClass());
679     job.setJobName(jobName);
680 
681     job.setPartitionerClass(NaturalKeyPartitioner.class);
682     job.setGroupingComparatorClass(NaturalKeyGroupingComparator.class);
683     job.setSortComparatorClass(CompositeKeyComparator.class);
684 
685     Scan scan = new Scan();
686     scan.addFamily(CHAIN_FAM);
687     scan.addFamily(SORT_FAM);
688     scan.setMaxVersions(1);
689     scan.setCacheBlocks(false);
690     scan.setBatch(1000);
691 
692     int replicaCount = conf.getInt(NUM_REPLICA_COUNT_KEY, NUM_REPLICA_COUNT_DEFAULT);
693     if (replicaCount != NUM_REPLICA_COUNT_DEFAULT) {
694       scan.setConsistency(Consistency.TIMELINE);
695     }
696 
697     TableMapReduceUtil.initTableMapperJob(
698         getTablename().getName(),
699         scan,
700         LinkedListCheckingMapper.class,
701         LinkKey.class,
702         LinkChain.class,
703         job
704     );
705 
706     job.setReducerClass(LinkedListCheckingReducer.class);
707     job.setOutputKeyClass(NullWritable.class);
708     job.setOutputValueClass(NullWritable.class);
709 
710     FileOutputFormat.setOutputPath(job, p);
711 
712     assertEquals(true, job.waitForCompletion(true));
713 
714     // Delete the files.
715     util.getTestFileSystem().delete(p, true);
716   }
717 
718   @Override
719   public void setUpCluster() throws Exception {
720     util = getTestingUtil(getConf());
721     util.initializeCluster(1);
722     int replicaCount = getConf().getInt(NUM_REPLICA_COUNT_KEY, NUM_REPLICA_COUNT_DEFAULT);
723     if (LOG.isDebugEnabled() && replicaCount != NUM_REPLICA_COUNT_DEFAULT) {
724       LOG.debug("Region Replicas enabled: " + replicaCount);
725     }
726 
727     // Scale this up on a real cluster
728     if (util.isDistributedCluster()) {
729       util.getConfiguration().setIfUnset(NUM_MAPS_KEY,
730           Integer.toString(util.getHBaseAdmin().getClusterStatus().getServersSize() * 10)
731       );
732       util.getConfiguration().setIfUnset(NUM_IMPORT_ROUNDS_KEY, "5");
733     } else {
734       util.startMiniMapReduceCluster();
735     }
736   }
737 
738   @Override
739   protected void addOptions() {
740     super.addOptions();
741     super.addOptNoArg(OPT_CHECK, "Run check only");
742     super.addOptNoArg(OPT_LOAD, "Run load only");
743   }
744 
745   @Override
746   protected void processOptions(CommandLine cmd) {
747     super.processOptions(cmd);
748     check = cmd.hasOption(OPT_CHECK);
749     load = cmd.hasOption(OPT_LOAD);
750   }
751 
752   @Override
753   public int runTestFromCommandLine() throws Exception {
754     if (load) {
755       runLoad();
756     } else if (check) {
757       installSlowingCoproc();
758       runCheck();
759     } else {
760       testBulkLoad();
761     }
762     return 0;
763   }
764 
765   @Override
766   public TableName getTablename() {
767     return getTableName(getConf());
768   }
769 
770   public static TableName getTableName(Configuration conf) {
771     return TableName.valueOf(conf.get(TABLE_NAME_KEY, TABLE_NAME));
772   }
773 
774   @Override
775   protected Set<String> getColumnFamilies() {
776     return null;
777   }
778 
779   public static void main(String[] args) throws Exception {
780     Configuration conf = HBaseConfiguration.create();
781     IntegrationTestingUtility.setUseDistributedCluster(conf);
782     int status =  ToolRunner.run(conf, new IntegrationTestBulkLoad(), args);
783     System.exit(status);
784   }
785 }