1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.hadoop.hbase.test;
20
21 import java.io.DataInput;
22 import java.io.DataOutput;
23 import java.io.FileNotFoundException;
24 import java.io.IOException;
25 import java.io.InterruptedIOException;
26 import java.security.SecureRandom;
27 import java.util.ArrayList;
28 import java.util.Arrays;
29 import java.util.Iterator;
30 import java.util.List;
31 import java.util.Random;
32 import java.util.Set;
33 import java.util.SortedSet;
34 import java.util.TreeSet;
35 import java.util.UUID;
36 import java.util.concurrent.ThreadLocalRandom;
37 import java.util.concurrent.atomic.AtomicInteger;
38
39 import org.apache.commons.cli.CommandLine;
40 import org.apache.commons.cli.GnuParser;
41 import org.apache.commons.cli.HelpFormatter;
42 import org.apache.commons.cli.Options;
43 import org.apache.commons.cli.ParseException;
44 import org.apache.commons.logging.Log;
45 import org.apache.commons.logging.LogFactory;
46 import org.apache.hadoop.conf.Configuration;
47 import org.apache.hadoop.conf.Configured;
48 import org.apache.hadoop.fs.FileSystem;
49 import org.apache.hadoop.fs.LocatedFileStatus;
50 import org.apache.hadoop.fs.Path;
51 import org.apache.hadoop.fs.RemoteIterator;
52 import org.apache.hadoop.hbase.Cell;
53 import org.apache.hadoop.hbase.HBaseConfiguration;
54 import org.apache.hadoop.hbase.HBaseTestingUtility;
55 import org.apache.hadoop.hbase.HColumnDescriptor;
56 import org.apache.hadoop.hbase.HConstants;
57 import org.apache.hadoop.hbase.HRegionLocation;
58 import org.apache.hadoop.hbase.HTableDescriptor;
59 import org.apache.hadoop.hbase.client.HTable;
60 import org.apache.hadoop.hbase.client.Table;
61 import org.apache.hadoop.hbase.IntegrationTestBase;
62 import org.apache.hadoop.hbase.IntegrationTestingUtility;
63 import org.apache.hadoop.hbase.testclassification.IntegrationTests;
64 import org.apache.hadoop.hbase.fs.HFileSystem;
65 import org.apache.hadoop.hbase.MasterNotRunningException;
66 import org.apache.hadoop.hbase.TableName;
67 import org.apache.hadoop.hbase.client.Admin;
68 import org.apache.hadoop.hbase.client.BufferedMutator;
69 import org.apache.hadoop.hbase.client.BufferedMutatorParams;
70 import org.apache.hadoop.hbase.client.Connection;
71 import org.apache.hadoop.hbase.client.ConnectionFactory;
72 import org.apache.hadoop.hbase.client.Get;
73 import org.apache.hadoop.hbase.client.Mutation;
74 import org.apache.hadoop.hbase.client.Put;
75 import org.apache.hadoop.hbase.client.RegionLocator;
76 import org.apache.hadoop.hbase.client.Result;
77 import org.apache.hadoop.hbase.client.ResultScanner;
78 import org.apache.hadoop.hbase.client.Scan;
79 import org.apache.hadoop.hbase.client.ScannerCallable;
80 import org.apache.hadoop.hbase.client.Table;
81 import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
82 import org.apache.hadoop.hbase.mapreduce.TableMapReduceUtil;
83 import org.apache.hadoop.hbase.mapreduce.TableMapper;
84 import org.apache.hadoop.hbase.mapreduce.TableRecordReaderImpl;
85 import org.apache.hadoop.hbase.mapreduce.WALPlayer;
86 import org.apache.hadoop.hbase.regionserver.FlushLargeStoresPolicy;
87 import org.apache.hadoop.hbase.regionserver.FlushPolicyFactory;
88 import org.apache.hadoop.hbase.regionserver.wal.WALEdit;
89 import org.apache.hadoop.hbase.testclassification.IntegrationTests;
90 import org.apache.hadoop.hbase.util.AbstractHBaseTool;
91 import org.apache.hadoop.hbase.util.Bytes;
92 import org.apache.hadoop.hbase.util.RegionSplitter;
93 import org.apache.hadoop.hbase.wal.WALKey;
94 import org.apache.hadoop.io.BytesWritable;
95 import org.apache.hadoop.io.NullWritable;
96 import org.apache.hadoop.io.Writable;
97 import org.apache.hadoop.mapreduce.Counter;
98 import org.apache.hadoop.mapreduce.CounterGroup;
99 import org.apache.hadoop.mapreduce.Counters;
100 import org.apache.hadoop.mapreduce.InputFormat;
101 import org.apache.hadoop.mapreduce.InputSplit;
102 import org.apache.hadoop.mapreduce.Job;
103 import org.apache.hadoop.mapreduce.JobContext;
104 import org.apache.hadoop.mapreduce.Mapper;
105 import org.apache.hadoop.mapreduce.RecordReader;
106 import org.apache.hadoop.mapreduce.Reducer;
107 import org.apache.hadoop.mapreduce.TaskAttemptContext;
108 import org.apache.hadoop.mapreduce.TaskAttemptID;
109 import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
110 import org.apache.hadoop.mapreduce.lib.input.FileSplit;
111 import org.apache.hadoop.mapreduce.lib.input.SequenceFileAsBinaryInputFormat;
112 import org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat;
113 import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
114 import org.apache.hadoop.mapreduce.lib.output.NullOutputFormat;
115 import org.apache.hadoop.mapreduce.lib.output.SequenceFileAsBinaryOutputFormat;
116 import org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat;
117 import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
118 import org.apache.hadoop.mapreduce.task.TaskAttemptContextImpl;
119 import org.apache.hadoop.util.Tool;
120 import org.apache.hadoop.util.ToolRunner;
121 import org.junit.Test;
122 import org.junit.experimental.categories.Category;
123
124 import com.google.common.collect.Sets;
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189 @Category(IntegrationTests.class)
190 public class IntegrationTestBigLinkedList extends IntegrationTestBase {
191 protected static final byte[] NO_KEY = new byte[1];
192
193 protected static String TABLE_NAME_KEY = "IntegrationTestBigLinkedList.table";
194
195 protected static String DEFAULT_TABLE_NAME = "IntegrationTestBigLinkedList";
196
197 protected static byte[] FAMILY_NAME = Bytes.toBytes("meta");
198 private static byte[] BIG_FAMILY_NAME = Bytes.toBytes("big");
199 private static byte[] TINY_FAMILY_NAME = Bytes.toBytes("tiny");
200
201
202 protected static final byte[] COLUMN_PREV = Bytes.toBytes("prev");
203
204
205 protected static final byte[] COLUMN_CLIENT = Bytes.toBytes("client");
206
207
208 protected static final byte[] COLUMN_COUNT = Bytes.toBytes("count");
209
210
211 private static final String GENERATOR_NUM_ROWS_PER_MAP_KEY
212 = "IntegrationTestBigLinkedList.generator.num_rows";
213
214 private static final String GENERATOR_NUM_MAPPERS_KEY
215 = "IntegrationTestBigLinkedList.generator.map.tasks";
216
217 private static final String GENERATOR_WIDTH_KEY
218 = "IntegrationTestBigLinkedList.generator.width";
219
220 private static final String GENERATOR_WRAP_KEY
221 = "IntegrationTestBigLinkedList.generator.wrap";
222
223 protected int NUM_SLAVES_BASE = 3;
224
225 private static final int MISSING_ROWS_TO_LOG = 50;
226
227 private static final int WIDTH_DEFAULT = 1000000;
228 private static final int WRAP_DEFAULT = 25;
229 private static final int ROWKEY_LENGTH = 16;
230
231 protected String toRun;
232 protected String[] otherArgs;
233
234 static class CINode {
235 byte[] key;
236 byte[] prev;
237 String client;
238 long count;
239 }
240
241
242
243
244 static class Generator extends Configured implements Tool {
245
246 private static final Log LOG = LogFactory.getLog(Generator.class);
247
248
249
250
251
252
253
254
255
256
257
258
259 public static final String MULTIPLE_UNEVEN_COLUMNFAMILIES_KEY =
260 "generator.multiple.columnfamilies";
261
262 static class GeneratorInputFormat extends InputFormat<BytesWritable,NullWritable> {
263 static class GeneratorInputSplit extends InputSplit implements Writable {
264 @Override
265 public long getLength() throws IOException, InterruptedException {
266 return 1;
267 }
268 @Override
269 public String[] getLocations() throws IOException, InterruptedException {
270 return new String[0];
271 }
272 @Override
273 public void readFields(DataInput arg0) throws IOException {
274 }
275 @Override
276 public void write(DataOutput arg0) throws IOException {
277 }
278 }
279
280 static class GeneratorRecordReader extends RecordReader<BytesWritable,NullWritable> {
281 private long count;
282 private long numNodes;
283 private Random rand;
284
285 @Override
286 public void close() throws IOException {
287 }
288
289 @Override
290 public BytesWritable getCurrentKey() throws IOException, InterruptedException {
291 byte[] bytes = new byte[ROWKEY_LENGTH];
292 rand.nextBytes(bytes);
293 return new BytesWritable(bytes);
294 }
295
296 @Override
297 public NullWritable getCurrentValue() throws IOException, InterruptedException {
298 return NullWritable.get();
299 }
300
301 @Override
302 public float getProgress() throws IOException, InterruptedException {
303 return (float)(count / (double)numNodes);
304 }
305
306 @Override
307 public void initialize(InputSplit arg0, TaskAttemptContext context)
308 throws IOException, InterruptedException {
309 numNodes = context.getConfiguration().getLong(GENERATOR_NUM_ROWS_PER_MAP_KEY, 25000000);
310
311 rand = new SecureRandom();
312 }
313
314 @Override
315 public boolean nextKeyValue() throws IOException, InterruptedException {
316 return count++ < numNodes;
317 }
318
319 }
320
321 @Override
322 public RecordReader<BytesWritable,NullWritable> createRecordReader(
323 InputSplit split, TaskAttemptContext context) throws IOException, InterruptedException {
324 GeneratorRecordReader rr = new GeneratorRecordReader();
325 rr.initialize(split, context);
326 return rr;
327 }
328
329 @Override
330 public List<InputSplit> getSplits(JobContext job) throws IOException, InterruptedException {
331 int numMappers = job.getConfiguration().getInt(GENERATOR_NUM_MAPPERS_KEY, 1);
332
333 ArrayList<InputSplit> splits = new ArrayList<InputSplit>(numMappers);
334
335 for (int i = 0; i < numMappers; i++) {
336 splits.add(new GeneratorInputSplit());
337 }
338
339 return splits;
340 }
341 }
342
343
344 static class OneFilePerMapperSFIF<K, V> extends SequenceFileInputFormat<K, V> {
345 @Override
346 protected boolean isSplitable(JobContext context, Path filename) {
347 return false;
348 }
349 }
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377 static class GeneratorMapper
378 extends Mapper<BytesWritable, NullWritable, NullWritable, NullWritable> {
379
380 byte[][] first = null;
381 byte[][] prev = null;
382 byte[][] current = null;
383 byte[] id;
384 long count = 0;
385 int i;
386 BufferedMutator mutator;
387 Connection connection;
388 long numNodes;
389 long wrap;
390 int width;
391 boolean multipleUnevenColumnFamilies;
392 byte[] tinyValue = new byte[] { 't' };
393 byte[] bigValue = null;
394
395 @Override
396 protected void setup(Context context) throws IOException, InterruptedException {
397 id = Bytes.toBytes("Job: "+context.getJobID() + " Task: " + context.getTaskAttemptID());
398 Configuration conf = context.getConfiguration();
399 connection = ConnectionFactory.createConnection(conf);
400 instantiateHTable();
401 this.width = context.getConfiguration().getInt(GENERATOR_WIDTH_KEY, WIDTH_DEFAULT);
402 current = new byte[this.width][];
403 int wrapMultiplier = context.getConfiguration().getInt(GENERATOR_WRAP_KEY, WRAP_DEFAULT);
404 this.wrap = (long)wrapMultiplier * width;
405 this.numNodes = context.getConfiguration().getLong(
406 GENERATOR_NUM_ROWS_PER_MAP_KEY, (long)WIDTH_DEFAULT * WRAP_DEFAULT);
407 if (this.numNodes < this.wrap) {
408 this.wrap = this.numNodes;
409 }
410 this.multipleUnevenColumnFamilies =
411 context.getConfiguration().getBoolean(MULTIPLE_UNEVEN_COLUMNFAMILIES_KEY, false);
412 }
413
414 protected void instantiateHTable() throws IOException {
415 mutator = connection.getBufferedMutator(
416 new BufferedMutatorParams(getTableName(connection.getConfiguration()))
417 .writeBufferSize(4 * 1024 * 1024));
418 }
419
420 @Override
421 protected void cleanup(Context context) throws IOException ,InterruptedException {
422 mutator.close();
423 connection.close();
424 }
425
426 @Override
427 protected void map(BytesWritable key, NullWritable value, Context output) throws IOException {
428 current[i] = new byte[key.getLength()];
429 System.arraycopy(key.getBytes(), 0, current[i], 0, key.getLength());
430 if (++i == current.length) {
431 LOG.info("Persisting current.length=" + current.length + ", count=" + count + ", id=" +
432 Bytes.toStringBinary(id) + ", current=" + Bytes.toStringBinary(current[0]) +
433 ", i=" + i);
434 persist(output, count, prev, current, id);
435 i = 0;
436
437 if (first == null) {
438 first = current;
439 }
440 prev = current;
441 current = new byte[this.width][];
442
443 count += current.length;
444 output.setStatus("Count " + count);
445
446 if (count % wrap == 0) {
447
448
449 circularLeftShift(first);
450
451 persist(output, -1, prev, first, null);
452
453 first = null;
454 prev = null;
455 }
456 }
457 }
458
459 private static <T> void circularLeftShift(T[] first) {
460 T ez = first[0];
461 System.arraycopy(first, 1, first, 0, first.length - 1);
462 first[first.length - 1] = ez;
463 }
464
465 protected void persist(Context output, long count, byte[][] prev, byte[][] current, byte[] id)
466 throws IOException {
467 for (int i = 0; i < current.length; i++) {
468 Put put = new Put(current[i]);
469 put.addColumn(FAMILY_NAME, COLUMN_PREV, prev == null ? NO_KEY : prev[i]);
470
471 if (count >= 0) {
472 put.addColumn(FAMILY_NAME, COLUMN_COUNT, Bytes.toBytes(count + i));
473 }
474 if (id != null) {
475 put.addColumn(FAMILY_NAME, COLUMN_CLIENT, id);
476 }
477
478 if (this.multipleUnevenColumnFamilies) {
479
480 put.addColumn(TINY_FAMILY_NAME, TINY_FAMILY_NAME, this.tinyValue);
481
482 if (this.bigValue == null) {
483 this.bigValue = new byte[current[i].length * 10];
484 ThreadLocalRandom.current().nextBytes(this.bigValue);
485 }
486
487 put.addColumn(BIG_FAMILY_NAME, BIG_FAMILY_NAME, this.bigValue);
488 }
489 mutator.mutate(put);
490
491 if (i % 1000 == 0) {
492
493 output.progress();
494 }
495 }
496
497 mutator.flush();
498 }
499 }
500
501 @Override
502 public int run(String[] args) throws Exception {
503 if (args.length < 3) {
504 System.out.println("Usage : " + Generator.class.getSimpleName() +
505 " <num mappers> <num nodes per map> <tmp output dir> [<width> <wrap multiplier>]");
506 System.out.println(" where <num nodes per map> should be a multiple of " +
507 " width*wrap multiplier, 25M by default");
508 return 0;
509 }
510
511 int numMappers = Integer.parseInt(args[0]);
512 long numNodes = Long.parseLong(args[1]);
513 Path tmpOutput = new Path(args[2]);
514 Integer width = (args.length < 4) ? null : Integer.parseInt(args[3]);
515 Integer wrapMuplitplier = (args.length < 5) ? null : Integer.parseInt(args[4]);
516 return run(numMappers, numNodes, tmpOutput, width, wrapMuplitplier);
517 }
518
519 protected void createSchema() throws IOException {
520 Configuration conf = getConf();
521 TableName tableName = getTableName(conf);
522 try (Connection conn = ConnectionFactory.createConnection(conf);
523 Admin admin = conn.getAdmin()) {
524 if (!admin.tableExists(tableName)) {
525 HTableDescriptor htd = new HTableDescriptor(getTableName(getConf()));
526 htd.addFamily(new HColumnDescriptor(FAMILY_NAME));
527
528 htd.addFamily(new HColumnDescriptor(BIG_FAMILY_NAME));
529 htd.addFamily(new HColumnDescriptor(TINY_FAMILY_NAME));
530 int numberOfServers = admin.getClusterStatus().getServers().size();
531 if (numberOfServers == 0) {
532 throw new IllegalStateException("No live regionservers");
533 }
534 int regionsPerServer = conf.getInt(HBaseTestingUtility.REGIONS_PER_SERVER_KEY,
535 HBaseTestingUtility.DEFAULT_REGIONS_PER_SERVER);
536 int totalNumberOfRegions = numberOfServers * regionsPerServer;
537 LOG.info("Number of live regionservers: " + numberOfServers + ", " +
538 "pre-splitting table into " + totalNumberOfRegions + " regions " +
539 "(default regions per server: " + regionsPerServer + ")");
540
541 byte[][] splits = new RegionSplitter.UniformSplit().split(totalNumberOfRegions);
542
543 admin.createTable(htd, splits);
544 }
545 } catch (MasterNotRunningException e) {
546 LOG.error("Master not running", e);
547 throw new IOException(e);
548 }
549 }
550
551 public int runRandomInputGenerator(int numMappers, long numNodes, Path tmpOutput,
552 Integer width, Integer wrapMuplitplier) throws Exception {
553 LOG.info("Running RandomInputGenerator with numMappers=" + numMappers
554 + ", numNodes=" + numNodes);
555 Job job = Job.getInstance(getConf());
556
557 job.setJobName("Random Input Generator");
558 job.setNumReduceTasks(0);
559 job.setJarByClass(getClass());
560
561 job.setInputFormatClass(GeneratorInputFormat.class);
562 job.setOutputKeyClass(BytesWritable.class);
563 job.setOutputValueClass(NullWritable.class);
564
565 setJobConf(job, numMappers, numNodes, width, wrapMuplitplier);
566
567 job.setMapperClass(Mapper.class);
568
569 FileOutputFormat.setOutputPath(job, tmpOutput);
570 job.setOutputFormatClass(SequenceFileOutputFormat.class);
571
572 boolean success = jobCompletion(job);
573
574 return success ? 0 : 1;
575 }
576
577 public int runGenerator(int numMappers, long numNodes, Path tmpOutput,
578 Integer width, Integer wrapMuplitplier) throws Exception {
579 LOG.info("Running Generator with numMappers=" + numMappers +", numNodes=" + numNodes);
580 createSchema();
581 Job job = Job.getInstance(getConf());
582
583 job.setJobName("Link Generator");
584 job.setNumReduceTasks(0);
585 job.setJarByClass(getClass());
586
587 FileInputFormat.setInputPaths(job, tmpOutput);
588 job.setInputFormatClass(OneFilePerMapperSFIF.class);
589 job.setOutputKeyClass(NullWritable.class);
590 job.setOutputValueClass(NullWritable.class);
591
592 setJobConf(job, numMappers, numNodes, width, wrapMuplitplier);
593
594 setMapperForGenerator(job);
595
596 job.setOutputFormatClass(NullOutputFormat.class);
597
598 job.getConfiguration().setBoolean("mapreduce.map.speculative", false);
599 String multipleUnevenColumnFamiliesStr = System.getProperty(MULTIPLE_UNEVEN_COLUMNFAMILIES_KEY);
600 if (multipleUnevenColumnFamiliesStr != null) {
601 job.getConfiguration().setBoolean(MULTIPLE_UNEVEN_COLUMNFAMILIES_KEY,
602 Boolean.parseBoolean(multipleUnevenColumnFamiliesStr));
603 }
604 TableMapReduceUtil.addDependencyJars(job);
605 TableMapReduceUtil.addDependencyJars(job.getConfiguration(), AbstractHBaseTool.class);
606 TableMapReduceUtil.initCredentials(job);
607
608 boolean success = jobCompletion(job);
609
610 return success ? 0 : 1;
611 }
612
613 protected boolean jobCompletion(Job job) throws IOException, InterruptedException,
614 ClassNotFoundException {
615 boolean success = job.waitForCompletion(true);
616 return success;
617 }
618
619 protected void setMapperForGenerator(Job job) {
620 job.setMapperClass(GeneratorMapper.class);
621 }
622
623 public int run(int numMappers, long numNodes, Path tmpOutput,
624 Integer width, Integer wrapMuplitplier) throws Exception {
625 int ret = runRandomInputGenerator(numMappers, numNodes, tmpOutput, width, wrapMuplitplier);
626 if (ret > 0) {
627 return ret;
628 }
629 return runGenerator(numMappers, numNodes, tmpOutput, width, wrapMuplitplier);
630 }
631 }
632
633
634
635
636
637
638
639 static class Search extends Configured implements Tool {
640 private static final Log LOG = LogFactory.getLog(Search.class);
641 protected Job job;
642
643 private static void printUsage(final String error) {
644 if (error != null && error.length() > 0) System.out.println("ERROR: " + error);
645 System.err.println("Usage: search <KEYS_DIR> [<MAPPERS_COUNT>]");
646 }
647
648 @Override
649 public int run(String[] args) throws Exception {
650 if (args.length < 1 || args.length > 2) {
651 printUsage(null);
652 return 1;
653 }
654 Path inputDir = new Path(args[0]);
655 int numMappers = 1;
656 if (args.length > 1) {
657 numMappers = Integer.parseInt(args[1]);
658 }
659 return run(inputDir, numMappers);
660 }
661
662
663
664
665 public static class WALSearcher extends WALPlayer {
666 public WALSearcher(Configuration conf) {
667 super(conf);
668 }
669
670
671
672
673 public static class WALMapperSearcher extends WALMapper {
674 private SortedSet<byte []> keysToFind;
675
676 @Override
677 public void setup(Mapper<WALKey, WALEdit, ImmutableBytesWritable, Mutation>.Context context)
678 throws IOException {
679 super.setup(context);
680 try {
681 this.keysToFind = readKeysToSearch(context.getConfiguration());
682 LOG.info("Loaded keys to find: count=" + this.keysToFind.size());
683 } catch (InterruptedException e) {
684 throw new InterruptedIOException(e.toString());
685 }
686 }
687
688 @Override
689 protected boolean filter(Context context, Cell cell) {
690
691 byte [] row = new byte [cell.getRowLength()];
692 System.arraycopy(cell.getRowArray(), cell.getRowOffset(), row, 0, cell.getRowLength());
693 boolean b = this.keysToFind.contains(row);
694 if (b) {
695 String keyStr = Bytes.toStringBinary(row);
696 LOG.info("Found cell=" + cell);
697 context.getCounter(FOUND_GROUP_KEY, keyStr).increment(1);
698 }
699 return b;
700 }
701 }
702
703
704 @Override
705 public Job createSubmittableJob(String[] args) throws IOException {
706 Job job = super.createSubmittableJob(args);
707
708 job.setJarByClass(WALMapperSearcher.class);
709 job.setMapperClass(WALMapperSearcher.class);
710 job.setOutputFormatClass(NullOutputFormat.class);
711 return job;
712 }
713 }
714
715 static final String FOUND_GROUP_KEY = "Found";
716 static final String SEARCHER_INPUTDIR_KEY = "searcher.keys.inputdir";
717
718 public int run(Path inputDir, int numMappers) throws Exception {
719 getConf().set(SEARCHER_INPUTDIR_KEY, inputDir.toString());
720 SortedSet<byte []> keys = readKeysToSearch(getConf());
721 if (keys.isEmpty()) throw new RuntimeException("No keys to find");
722 LOG.info("Count of keys to find: " + keys.size());
723 for(byte [] key: keys) LOG.info("Key: " + Bytes.toStringBinary(key));
724 Path hbaseDir = new Path(getConf().get(HConstants.HBASE_DIR));
725
726 Path walsDir = new Path(hbaseDir, HConstants.HREGION_LOGDIR_NAME);
727 Path oldWalsDir = new Path(hbaseDir, HConstants.HREGION_OLDLOGDIR_NAME);
728 LOG.info("Running Search with keys inputDir=" + inputDir +", numMappers=" + numMappers +
729 " against " + getConf().get(HConstants.HBASE_DIR));
730 int ret = ToolRunner.run(new WALSearcher(getConf()), new String [] {walsDir.toString(), ""});
731 if (ret != 0) return ret;
732 return ToolRunner.run(new WALSearcher(getConf()), new String [] {oldWalsDir.toString(), ""});
733 }
734
735 static SortedSet<byte []> readKeysToSearch(final Configuration conf)
736 throws IOException, InterruptedException {
737 Path keysInputDir = new Path(conf.get(SEARCHER_INPUTDIR_KEY));
738 FileSystem fs = FileSystem.get(conf);
739 SortedSet<byte []> result = new TreeSet<byte []>(Bytes.BYTES_COMPARATOR);
740 if (!fs.exists(keysInputDir)) {
741 throw new FileNotFoundException(keysInputDir.toString());
742 }
743 if (!fs.isDirectory(keysInputDir)) {
744 throw new UnsupportedOperationException("TODO");
745 } else {
746 RemoteIterator<LocatedFileStatus> iterator = fs.listFiles(keysInputDir, false);
747 while(iterator.hasNext()) {
748 LocatedFileStatus keyFileStatus = iterator.next();
749
750 if (keyFileStatus.getPath().getName().startsWith("_")) continue;
751 result.addAll(readFileToSearch(conf, fs, keyFileStatus));
752 }
753 }
754 return result;
755 }
756
757 private static SortedSet<byte[]> readFileToSearch(final Configuration conf,
758 final FileSystem fs, final LocatedFileStatus keyFileStatus) throws IOException,
759 InterruptedException {
760 SortedSet<byte []> result = new TreeSet<byte []>(Bytes.BYTES_COMPARATOR);
761
762
763 TaskAttemptContext context = new TaskAttemptContextImpl(conf, new TaskAttemptID());
764 try (SequenceFileAsBinaryInputFormat.SequenceFileAsBinaryRecordReader rr =
765 new SequenceFileAsBinaryInputFormat.SequenceFileAsBinaryRecordReader()) {
766 InputSplit is =
767 new FileSplit(keyFileStatus.getPath(), 0, keyFileStatus.getLen(), new String [] {});
768 rr.initialize(is, context);
769 while (rr.nextKeyValue()) {
770 rr.getCurrentKey();
771 BytesWritable bw = rr.getCurrentValue();
772 if (Verify.VerifyReducer.whichType(bw.getBytes()) == Verify.Counts.UNDEFINED) {
773 byte[] key = new byte[rr.getCurrentKey().getLength()];
774 System.arraycopy(rr.getCurrentKey().getBytes(), 0, key, 0, rr.getCurrentKey()
775 .getLength());
776 result.add(key);
777 }
778 }
779 }
780 return result;
781 }
782 }
783
784
785
786
787
788 static class Verify extends Configured implements Tool {
789
790 private static final Log LOG = LogFactory.getLog(Verify.class);
791 protected static final BytesWritable DEF = new BytesWritable(new byte[] { 0 });
792 protected static final BytesWritable DEF_LOST_FAMILIES = new BytesWritable(new byte[] { 1 });
793
794 protected Job job;
795
796 public static class VerifyMapper extends TableMapper<BytesWritable, BytesWritable> {
797 private BytesWritable row = new BytesWritable();
798 private BytesWritable ref = new BytesWritable();
799
800 private boolean multipleUnevenColumnFamilies;
801
802 @Override
803 protected void setup(
804 Mapper<ImmutableBytesWritable, Result, BytesWritable, BytesWritable>.Context context)
805 throws IOException, InterruptedException {
806 this.multipleUnevenColumnFamilies =
807 context.getConfiguration().getBoolean(Generator.MULTIPLE_UNEVEN_COLUMNFAMILIES_KEY,
808 false);
809 }
810
811 @Override
812 protected void map(ImmutableBytesWritable key, Result value, Context context)
813 throws IOException ,InterruptedException {
814 byte[] rowKey = key.get();
815 row.set(rowKey, 0, rowKey.length);
816 if (multipleUnevenColumnFamilies
817 && (!value.containsColumn(BIG_FAMILY_NAME, BIG_FAMILY_NAME) || !value.containsColumn(
818 TINY_FAMILY_NAME, TINY_FAMILY_NAME))) {
819 context.write(row, DEF_LOST_FAMILIES);
820 } else {
821 context.write(row, DEF);
822 }
823 byte[] prev = value.getValue(FAMILY_NAME, COLUMN_PREV);
824 if (prev != null && prev.length > 0) {
825 ref.set(prev, 0, prev.length);
826 context.write(ref, row);
827 } else {
828 LOG.warn(String.format("Prev is not set for: %s", Bytes.toStringBinary(rowKey)));
829 }
830 }
831 }
832
833
834
835
836
837 public static enum Counts {
838 UNREFERENCED, UNDEFINED, REFERENCED, CORRUPT, EXTRAREFERENCES, EXTRA_UNDEF_REFERENCES,
839 LOST_FAMILIES
840 }
841
842
843
844
845
846
847 public static class VerifyReducer extends
848 Reducer<BytesWritable, BytesWritable, BytesWritable, BytesWritable> {
849 private ArrayList<byte[]> refs = new ArrayList<byte[]>();
850 private final BytesWritable UNREF = new BytesWritable(addPrefixFlag(
851 Counts.UNREFERENCED.ordinal(), new byte[] {}));
852 private final BytesWritable LOSTFAM = new BytesWritable(addPrefixFlag(
853 Counts.LOST_FAMILIES.ordinal(), new byte[] {}));
854
855 private AtomicInteger rows = new AtomicInteger(0);
856 private Connection connection;
857
858 @Override
859 protected void setup(Reducer<BytesWritable, BytesWritable, BytesWritable, BytesWritable>.Context context)
860 throws IOException, InterruptedException {
861 super.setup(context);
862 this.connection = ConnectionFactory.createConnection(context.getConfiguration());
863 }
864
865 @Override
866 protected void cleanup(
867 Reducer<BytesWritable, BytesWritable, BytesWritable, BytesWritable>.Context context)
868 throws IOException, InterruptedException {
869 if (this.connection != null) {
870 this.connection.close();
871 }
872 super.cleanup(context);
873 }
874
875
876
877
878
879
880
881 public static byte[] addPrefixFlag(final int ordinal, final byte [] r) {
882 byte[] prefix = Bytes.toBytes((short)ordinal);
883 if (prefix.length != Bytes.SIZEOF_SHORT) {
884 throw new RuntimeException("Unexpected size: " + prefix.length);
885 }
886 byte[] result = new byte[prefix.length + r.length];
887 System.arraycopy(prefix, 0, result, 0, prefix.length);
888 System.arraycopy(r, 0, result, prefix.length, r.length);
889 return result;
890 }
891
892
893
894
895
896
897 public static Counts whichType(final byte [] bs) {
898 int ordinal = Bytes.toShort(bs, 0, Bytes.SIZEOF_SHORT);
899 return Counts.values()[ordinal];
900 }
901
902
903
904
905
906 public static byte[] getRowOnly(BytesWritable bw) {
907 byte[] bytes = new byte [bw.getLength() - Bytes.SIZEOF_SHORT];
908 System.arraycopy(bw.getBytes(), Bytes.SIZEOF_SHORT, bytes, 0, bytes.length);
909 return bytes;
910 }
911
912 @Override
913 public void reduce(BytesWritable key, Iterable<BytesWritable> values, Context context)
914 throws IOException, InterruptedException {
915 int defCount = 0;
916 boolean lostFamilies = false;
917 refs.clear();
918 for (BytesWritable type : values) {
919 if (type.getLength() == DEF.getLength()) {
920 defCount++;
921 if (type.getBytes()[0] == 1) {
922 lostFamilies = true;
923 }
924 } else {
925 byte[] bytes = new byte[type.getLength()];
926 System.arraycopy(type.getBytes(), 0, bytes, 0, type.getLength());
927 refs.add(bytes);
928 }
929 }
930
931
932 StringBuilder refsSb = null;
933 String keyString = Bytes.toStringBinary(key.getBytes(), 0, key.getLength());
934 if (defCount == 0 || refs.size() != 1) {
935 refsSb = dumpExtraInfoOnRefs(key, context, refs);
936 LOG.error("LinkedListError: key=" + keyString + ", reference(s)=" +
937 (refsSb != null? refsSb.toString(): ""));
938 }
939 if (lostFamilies) {
940 LOG.error("LinkedListError: key=" + keyString + ", lost big or tiny families");
941 context.getCounter(Counts.LOST_FAMILIES).increment(1);
942 context.write(key, LOSTFAM);
943 }
944
945 if (defCount == 0 && refs.size() > 0) {
946
947
948
949 for (int i = 0; i < refs.size(); i++) {
950 byte[] bs = refs.get(i);
951 int ordinal;
952 if (i <= 0) {
953 ordinal = Counts.UNDEFINED.ordinal();
954 context.write(key, new BytesWritable(addPrefixFlag(ordinal, bs)));
955 context.getCounter(Counts.UNDEFINED).increment(1);
956 } else {
957 ordinal = Counts.EXTRA_UNDEF_REFERENCES.ordinal();
958 context.write(key, new BytesWritable(addPrefixFlag(ordinal, bs)));
959 }
960 }
961 if (rows.addAndGet(1) < MISSING_ROWS_TO_LOG) {
962
963
964
965
966 context.getCounter("undef", keyString).increment(1);
967 }
968 } else if (defCount > 0 && refs.size() == 0) {
969
970 context.write(key, UNREF);
971 context.getCounter(Counts.UNREFERENCED).increment(1);
972 if (rows.addAndGet(1) < MISSING_ROWS_TO_LOG) {
973 context.getCounter("unref", keyString).increment(1);
974 }
975 } else {
976 if (refs.size() > 1) {
977
978 for (int i = 1; i < refs.size(); i++) {
979 context.write(key,
980 new BytesWritable(addPrefixFlag(Counts.EXTRAREFERENCES.ordinal(), refs.get(i))));
981 }
982 context.getCounter(Counts.EXTRAREFERENCES).increment(refs.size() - 1);
983 }
984
985 context.getCounter(Counts.REFERENCED).increment(1);
986 }
987 }
988
989
990
991
992
993
994 private StringBuilder dumpExtraInfoOnRefs(final BytesWritable key, final Context context,
995 final List<byte []> refs)
996 throws IOException {
997 StringBuilder refsSb = null;
998 if (refs.isEmpty()) return refsSb;
999 refsSb = new StringBuilder();
1000 String comma = "";
1001
1002
1003
1004 TableName tn = getTableName(context.getConfiguration());
1005 try (Table t = this.connection.getTable(tn)) {
1006 for (byte [] ref : refs) {
1007 Result r = t.get(new Get(ref));
1008 List<Cell> cells = r.listCells();
1009 String ts = (cells != null && !cells.isEmpty())?
1010 new java.util.Date(cells.get(0).getTimestamp()).toString(): "";
1011 byte [] b = r.getValue(FAMILY_NAME, COLUMN_CLIENT);
1012 String jobStr = (b != null && b.length > 0)? Bytes.toString(b): "";
1013 b = r.getValue(FAMILY_NAME, COLUMN_COUNT);
1014 long count = (b != null && b.length > 0)? Bytes.toLong(b): -1;
1015 b = r.getValue(FAMILY_NAME, COLUMN_PREV);
1016 String refRegionLocation = "";
1017 String keyRegionLocation = "";
1018 if (b != null && b.length > 0) {
1019 try (RegionLocator rl = this.connection.getRegionLocator(tn)) {
1020 HRegionLocation hrl = rl.getRegionLocation(b);
1021 if (hrl != null) refRegionLocation = hrl.toString();
1022
1023 hrl = rl.getRegionLocation(key.getBytes());
1024 if (hrl != null) keyRegionLocation = hrl.toString();
1025 }
1026 }
1027 LOG.error("Extras on ref without a def, ref=" + Bytes.toStringBinary(ref) +
1028 ", refPrevEqualsKey=" +
1029 (Bytes.compareTo(key.getBytes(), 0, key.getLength(), b, 0, b.length) == 0) +
1030 ", key=" + Bytes.toStringBinary(key.getBytes(), 0, key.getLength()) +
1031 ", ref row date=" + ts + ", jobStr=" + jobStr +
1032 ", ref row count=" + count +
1033 ", ref row regionLocation=" + refRegionLocation +
1034 ", key row regionLocation=" + keyRegionLocation);
1035 refsSb.append(comma);
1036 comma = ",";
1037 refsSb.append(Bytes.toStringBinary(ref));
1038 }
1039 }
1040 return refsSb;
1041 }
1042 }
1043
1044 @Override
1045 public int run(String[] args) throws Exception {
1046 if (args.length != 2) {
1047 System.out.println("Usage : " + Verify.class.getSimpleName()
1048 + " <output dir> <num reducers>");
1049 return 0;
1050 }
1051
1052 String outputDir = args[0];
1053 int numReducers = Integer.parseInt(args[1]);
1054
1055 return run(outputDir, numReducers);
1056 }
1057
1058 public int run(String outputDir, int numReducers) throws Exception {
1059 return run(new Path(outputDir), numReducers);
1060 }
1061
1062 public int run(Path outputDir, int numReducers) throws Exception {
1063 LOG.info("Running Verify with outputDir=" + outputDir +", numReducers=" + numReducers);
1064
1065 job = Job.getInstance(getConf());
1066
1067 job.setJobName("Link Verifier");
1068 job.setNumReduceTasks(numReducers);
1069 job.setJarByClass(getClass());
1070
1071 setJobScannerConf(job);
1072
1073 Scan scan = new Scan();
1074 scan.addColumn(FAMILY_NAME, COLUMN_PREV);
1075 scan.setCaching(10000);
1076 scan.setCacheBlocks(false);
1077 if (isMultiUnevenColumnFamilies()) {
1078 scan.addColumn(BIG_FAMILY_NAME, BIG_FAMILY_NAME);
1079 scan.addColumn(TINY_FAMILY_NAME, TINY_FAMILY_NAME);
1080 job.getConfiguration().setBoolean(Generator.MULTIPLE_UNEVEN_COLUMNFAMILIES_KEY, true);
1081 }
1082
1083 TableMapReduceUtil.initTableMapperJob(getTableName(getConf()).getName(), scan,
1084 VerifyMapper.class, BytesWritable.class, BytesWritable.class, job);
1085 TableMapReduceUtil.addDependencyJars(job.getConfiguration(), AbstractHBaseTool.class);
1086
1087 job.getConfiguration().setBoolean("mapreduce.map.speculative", false);
1088
1089 job.setReducerClass(VerifyReducer.class);
1090 job.setOutputFormatClass(SequenceFileAsBinaryOutputFormat.class);
1091 job.setOutputKeyClass(BytesWritable.class);
1092 job.setOutputValueClass(BytesWritable.class);
1093 TextOutputFormat.setOutputPath(job, outputDir);
1094
1095 boolean success = job.waitForCompletion(true);
1096
1097 return success ? 0 : 1;
1098 }
1099
1100 public boolean verify(long expectedReferenced) throws Exception {
1101 if (job == null) {
1102 throw new IllegalStateException("You should call run() first");
1103 }
1104
1105 Counters counters = job.getCounters();
1106
1107 Counter referenced = counters.findCounter(Counts.REFERENCED);
1108 Counter unreferenced = counters.findCounter(Counts.UNREFERENCED);
1109 Counter undefined = counters.findCounter(Counts.UNDEFINED);
1110 Counter multiref = counters.findCounter(Counts.EXTRAREFERENCES);
1111 Counter lostfamilies = counters.findCounter(Counts.LOST_FAMILIES);
1112
1113 boolean success = true;
1114
1115 if (expectedReferenced != referenced.getValue()) {
1116 LOG.error("Expected referenced count does not match with actual referenced count. " +
1117 "expected referenced=" + expectedReferenced + " ,actual=" + referenced.getValue());
1118 success = false;
1119 }
1120
1121 if (unreferenced.getValue() > 0) {
1122 boolean couldBeMultiRef = (multiref.getValue() == unreferenced.getValue());
1123 LOG.error("Unreferenced nodes were not expected. Unreferenced count=" + unreferenced.getValue()
1124 + (couldBeMultiRef ? "; could be due to duplicate random numbers" : ""));
1125 success = false;
1126 }
1127
1128 if (undefined.getValue() > 0) {
1129 LOG.error("Found an undefined node. Undefined count=" + undefined.getValue());
1130 success = false;
1131 }
1132
1133 if (lostfamilies.getValue() > 0) {
1134 LOG.error("Found nodes which lost big or tiny families, count=" + lostfamilies.getValue());
1135 success = false;
1136 }
1137
1138 if (!success) {
1139 handleFailure(counters);
1140 }
1141 return success;
1142 }
1143
1144 protected void handleFailure(Counters counters) throws IOException {
1145 Configuration conf = job.getConfiguration();
1146 TableName tableName = getTableName(conf);
1147 try (Connection conn = ConnectionFactory.createConnection(conf)) {
1148 try (RegionLocator rl = conn.getRegionLocator(tableName)) {
1149 CounterGroup g = counters.getGroup("undef");
1150 Iterator<Counter> it = g.iterator();
1151 while (it.hasNext()) {
1152 String keyString = it.next().getName();
1153 byte[] key = Bytes.toBytes(keyString);
1154 HRegionLocation loc = rl.getRegionLocation(key, true);
1155 LOG.error("undefined row " + keyString + ", " + loc);
1156 }
1157 g = counters.getGroup("unref");
1158 it = g.iterator();
1159 while (it.hasNext()) {
1160 String keyString = it.next().getName();
1161 byte[] key = Bytes.toBytes(keyString);
1162 HRegionLocation loc = rl.getRegionLocation(key, true);
1163 LOG.error("unreferred row " + keyString + ", " + loc);
1164 }
1165 }
1166 }
1167 }
1168 }
1169
1170
1171
1172
1173
1174 static class Loop extends Configured implements Tool {
1175
1176 private static final Log LOG = LogFactory.getLog(Loop.class);
1177
1178 IntegrationTestBigLinkedList it;
1179
1180 protected void runGenerator(int numMappers, long numNodes,
1181 String outputDir, Integer width, Integer wrapMuplitplier) throws Exception {
1182 Path outputPath = new Path(outputDir);
1183 UUID uuid = UUID.randomUUID();
1184 Path generatorOutput = new Path(outputPath, uuid.toString());
1185
1186 Generator generator = new Generator();
1187 generator.setConf(getConf());
1188 int retCode = generator.run(numMappers, numNodes, generatorOutput, width, wrapMuplitplier);
1189 if (retCode > 0) {
1190 throw new RuntimeException("Generator failed with return code: " + retCode);
1191 }
1192 }
1193
1194 protected void runVerify(String outputDir,
1195 int numReducers, long expectedNumNodes) throws Exception {
1196 Path outputPath = new Path(outputDir);
1197 UUID uuid = UUID.randomUUID();
1198 Path iterationOutput = new Path(outputPath, uuid.toString());
1199
1200 Verify verify = new Verify();
1201 verify.setConf(getConf());
1202 int retCode = verify.run(iterationOutput, numReducers);
1203 if (retCode > 0) {
1204 throw new RuntimeException("Verify.run failed with return code: " + retCode);
1205 }
1206
1207 if (!verify.verify(expectedNumNodes)) {
1208 throw new RuntimeException("Verify.verify failed");
1209 }
1210
1211 LOG.info("Verify finished with succees. Total nodes=" + expectedNumNodes);
1212 }
1213
1214 @Override
1215 public int run(String[] args) throws Exception {
1216 if (args.length < 5) {
1217 System.err.println("Usage: Loop <num iterations> <num mappers> <num nodes per mapper> <output dir> <num reducers> [<width> <wrap multiplier>]");
1218 return 1;
1219 }
1220 LOG.info("Running Loop with args:" + Arrays.deepToString(args));
1221
1222 int numIterations = Integer.parseInt(args[0]);
1223 int numMappers = Integer.parseInt(args[1]);
1224 long numNodes = Long.parseLong(args[2]);
1225 String outputDir = args[3];
1226 int numReducers = Integer.parseInt(args[4]);
1227 Integer width = (args.length < 6) ? null : Integer.parseInt(args[5]);
1228 Integer wrapMuplitplier = (args.length < 7) ? null : Integer.parseInt(args[6]);
1229
1230 long expectedNumNodes = 0;
1231
1232 if (numIterations < 0) {
1233 numIterations = Integer.MAX_VALUE;
1234 }
1235
1236 for (int i = 0; i < numIterations; i++) {
1237 LOG.info("Starting iteration = " + i);
1238 runGenerator(numMappers, numNodes, outputDir, width, wrapMuplitplier);
1239 expectedNumNodes += numMappers * numNodes;
1240
1241 runVerify(outputDir, numReducers, expectedNumNodes);
1242 }
1243
1244 return 0;
1245 }
1246 }
1247
1248
1249
1250
1251 private static class Print extends Configured implements Tool {
1252 @Override
1253 public int run(String[] args) throws Exception {
1254 Options options = new Options();
1255 options.addOption("s", "start", true, "start key");
1256 options.addOption("e", "end", true, "end key");
1257 options.addOption("l", "limit", true, "number to print");
1258
1259 GnuParser parser = new GnuParser();
1260 CommandLine cmd = null;
1261 try {
1262 cmd = parser.parse(options, args);
1263 if (cmd.getArgs().length != 0) {
1264 throw new ParseException("Command takes no arguments");
1265 }
1266 } catch (ParseException e) {
1267 System.err.println("Failed to parse command line " + e.getMessage());
1268 System.err.println();
1269 HelpFormatter formatter = new HelpFormatter();
1270 formatter.printHelp(getClass().getSimpleName(), options);
1271 System.exit(-1);
1272 }
1273
1274 Table table = new HTable(getConf(), getTableName(getConf()));
1275
1276 Scan scan = new Scan();
1277 scan.setBatch(10000);
1278
1279 if (cmd.hasOption("s"))
1280 scan.setStartRow(Bytes.toBytesBinary(cmd.getOptionValue("s")));
1281
1282 if (cmd.hasOption("e"))
1283 scan.setStopRow(Bytes.toBytesBinary(cmd.getOptionValue("e")));
1284
1285 int limit = 0;
1286 if (cmd.hasOption("l"))
1287 limit = Integer.parseInt(cmd.getOptionValue("l"));
1288 else
1289 limit = 100;
1290
1291 ResultScanner scanner = table.getScanner(scan);
1292
1293 CINode node = new CINode();
1294 Result result = scanner.next();
1295 int count = 0;
1296 while (result != null && count++ < limit) {
1297 node = getCINode(result, node);
1298 System.out.printf("%s:%s:%012d:%s\n", Bytes.toStringBinary(node.key),
1299 Bytes.toStringBinary(node.prev), node.count, node.client);
1300 result = scanner.next();
1301 }
1302 scanner.close();
1303 table.close();
1304
1305 return 0;
1306 }
1307 }
1308
1309
1310
1311
1312 private static class Delete extends Configured implements Tool {
1313 @Override
1314 public int run(String[] args) throws Exception {
1315 if (args.length != 1) {
1316 System.out.println("Usage : " + Delete.class.getSimpleName() + " <node to delete>");
1317 return 0;
1318 }
1319 byte[] val = Bytes.toBytesBinary(args[0]);
1320
1321 org.apache.hadoop.hbase.client.Delete delete
1322 = new org.apache.hadoop.hbase.client.Delete(val);
1323
1324 Table table = new HTable(getConf(), getTableName(getConf()));
1325 table.delete(delete);
1326 table.close();
1327
1328 System.out.println("Delete successful");
1329 return 0;
1330 }
1331 }
1332
1333
1334
1335
1336
1337 private static class Walker extends Configured implements Tool {
1338 @Override
1339 public int run(String[] args) throws IOException {
1340 Options options = new Options();
1341 options.addOption("n", "num", true, "number of queries");
1342 options.addOption("s", "start", true, "key to start at, binary string");
1343 options.addOption("l", "logevery", true, "log every N queries");
1344
1345 GnuParser parser = new GnuParser();
1346 CommandLine cmd = null;
1347 try {
1348 cmd = parser.parse(options, args);
1349 if (cmd.getArgs().length != 0) {
1350 throw new ParseException("Command takes no arguments");
1351 }
1352 } catch (ParseException e) {
1353 System.err.println("Failed to parse command line " + e.getMessage());
1354 System.err.println();
1355 HelpFormatter formatter = new HelpFormatter();
1356 formatter.printHelp(getClass().getSimpleName(), options);
1357 System.exit(-1);
1358 }
1359
1360 long maxQueries = Long.MAX_VALUE;
1361 if (cmd.hasOption('n')) {
1362 maxQueries = Long.parseLong(cmd.getOptionValue("n"));
1363 }
1364 Random rand = new SecureRandom();
1365 boolean isSpecificStart = cmd.hasOption('s');
1366 byte[] startKey = isSpecificStart ? Bytes.toBytesBinary(cmd.getOptionValue('s')) : null;
1367 int logEvery = cmd.hasOption('l') ? Integer.parseInt(cmd.getOptionValue('l')) : 1;
1368
1369 Table table = new HTable(getConf(), getTableName(getConf()));
1370 long numQueries = 0;
1371
1372
1373
1374 while (numQueries < maxQueries && (numQueries == 0 || !isSpecificStart)) {
1375 if (!isSpecificStart) {
1376 startKey = new byte[ROWKEY_LENGTH];
1377 rand.nextBytes(startKey);
1378 }
1379 CINode node = findStartNode(table, startKey);
1380 if (node == null && isSpecificStart) {
1381 System.err.printf("Start node not found: %s \n", Bytes.toStringBinary(startKey));
1382 }
1383 numQueries++;
1384 while (node != null && node.prev.length != NO_KEY.length && numQueries < maxQueries) {
1385 byte[] prev = node.prev;
1386 long t1 = System.currentTimeMillis();
1387 node = getNode(prev, table, node);
1388 long t2 = System.currentTimeMillis();
1389 if (numQueries % logEvery == 0) {
1390 System.out.printf("CQ %d: %d %s \n", numQueries, t2 - t1, Bytes.toStringBinary(prev));
1391 }
1392 numQueries++;
1393 if (node == null) {
1394 System.err.printf("UNDEFINED NODE %s \n", Bytes.toStringBinary(prev));
1395 } else if (node.prev.length == NO_KEY.length) {
1396 System.err.printf("TERMINATING NODE %s \n", Bytes.toStringBinary(node.key));
1397 }
1398 }
1399 }
1400
1401 table.close();
1402 return 0;
1403 }
1404
1405 private static CINode findStartNode(Table table, byte[] startKey) throws IOException {
1406 Scan scan = new Scan();
1407 scan.setStartRow(startKey);
1408 scan.setBatch(1);
1409 scan.addColumn(FAMILY_NAME, COLUMN_PREV);
1410
1411 long t1 = System.currentTimeMillis();
1412 ResultScanner scanner = table.getScanner(scan);
1413 Result result = scanner.next();
1414 long t2 = System.currentTimeMillis();
1415 scanner.close();
1416
1417 if ( result != null) {
1418 CINode node = getCINode(result, new CINode());
1419 System.out.printf("FSR %d %s\n", t2 - t1, Bytes.toStringBinary(node.key));
1420 return node;
1421 }
1422
1423 System.out.println("FSR " + (t2 - t1));
1424
1425 return null;
1426 }
1427
1428 private CINode getNode(byte[] row, Table table, CINode node) throws IOException {
1429 Get get = new Get(row);
1430 get.addColumn(FAMILY_NAME, COLUMN_PREV);
1431 Result result = table.get(get);
1432 return getCINode(result, node);
1433 }
1434 }
1435
1436 private static class Clean extends Configured implements Tool {
1437 @Override public int run(String[] args) throws Exception {
1438 if (args.length < 1) {
1439 System.err.println("Usage: Clean <output dir>");
1440 return -1;
1441 }
1442
1443 Path p = new Path(args[0]);
1444 Configuration conf = getConf();
1445 TableName tableName = getTableName(conf);
1446 try (FileSystem fs = HFileSystem.get(conf);
1447 Connection conn = ConnectionFactory.createConnection(conf);
1448 Admin admin = conn.getAdmin()) {
1449 if (admin.tableExists(tableName)) {
1450 admin.disableTable(tableName);
1451 admin.deleteTable(tableName);
1452 }
1453
1454 if (fs.exists(p)) {
1455 fs.delete(p, true);
1456 }
1457 }
1458
1459 return 0;
1460 }
1461 }
1462
1463 static TableName getTableName(Configuration conf) {
1464 return TableName.valueOf(conf.get(TABLE_NAME_KEY, DEFAULT_TABLE_NAME));
1465 }
1466
1467 private static CINode getCINode(Result result, CINode node) {
1468 node.key = Bytes.copy(result.getRow());
1469 if (result.containsColumn(FAMILY_NAME, COLUMN_PREV)) {
1470 node.prev = Bytes.copy(result.getValue(FAMILY_NAME, COLUMN_PREV));
1471 } else {
1472 node.prev = NO_KEY;
1473 }
1474 if (result.containsColumn(FAMILY_NAME, COLUMN_COUNT)) {
1475 node.count = Bytes.toLong(result.getValue(FAMILY_NAME, COLUMN_COUNT));
1476 } else {
1477 node.count = -1;
1478 }
1479 if (result.containsColumn(FAMILY_NAME, COLUMN_CLIENT)) {
1480 node.client = Bytes.toString(result.getValue(FAMILY_NAME, COLUMN_CLIENT));
1481 } else {
1482 node.client = "";
1483 }
1484 return node;
1485 }
1486
1487 protected IntegrationTestingUtility util;
1488
1489 @Override
1490 public void setUpCluster() throws Exception {
1491 util = getTestingUtil(getConf());
1492 boolean isDistributed = util.isDistributedCluster();
1493 util.initializeCluster(isDistributed ? 1 : this.NUM_SLAVES_BASE);
1494 if (!isDistributed) {
1495 util.startMiniMapReduceCluster();
1496 }
1497 this.setConf(util.getConfiguration());
1498 }
1499
1500 @Override
1501 public void cleanUpCluster() throws Exception {
1502 super.cleanUpCluster();
1503 if (util.isDistributedCluster()) {
1504 util.shutdownMiniMapReduceCluster();
1505 }
1506 }
1507
1508 private static boolean isMultiUnevenColumnFamilies() {
1509 return Boolean.TRUE.toString().equalsIgnoreCase(
1510 System.getProperty(Generator.MULTIPLE_UNEVEN_COLUMNFAMILIES_KEY));
1511 }
1512
1513 @Test
1514 public void testContinuousIngest() throws IOException, Exception {
1515
1516 Configuration conf = getTestingUtil(getConf()).getConfiguration();
1517 if (isMultiUnevenColumnFamilies()) {
1518
1519 conf.set(FlushPolicyFactory.HBASE_FLUSH_POLICY_KEY, FlushLargeStoresPolicy.class.getName());
1520 }
1521 int ret =
1522 ToolRunner.run(conf, new Loop(), new String[] { "1", "1", "2000000",
1523 util.getDataTestDirOnTestFS("IntegrationTestBigLinkedList").toString(), "1" });
1524 org.junit.Assert.assertEquals(0, ret);
1525 }
1526
1527 private void usage() {
1528 System.err.println("Usage: " + this.getClass().getSimpleName() + " COMMAND [COMMAND options]");
1529 printCommands();
1530 }
1531
1532 private void printCommands() {
1533 System.err.println("Commands:");
1534 System.err.println(" generator Map only job that generates data.");
1535 System.err.println(" verify A map reduce job that looks for holes. Look at the counts ");
1536 System.err.println(" after running. See REFERENCED and UNREFERENCED are ok. Any ");
1537 System.err.println(" UNDEFINED counts are bad. Do not run with the Generator.");
1538 System.err.println(" walker " +
1539 "Standalone program that starts following a linked list & emits timing info.");
1540 System.err.println(" print Standalone program that prints nodes in the linked list.");
1541 System.err.println(" delete Standalone program that deletes a·single node.");
1542 System.err.println(" loop Program to Loop through Generator and Verify steps");
1543 System.err.println(" clean Program to clean all left over detritus.");
1544 System.err.println(" search Search for missing keys.");
1545 System.err.flush();
1546 }
1547
1548 @Override
1549 protected void processOptions(CommandLine cmd) {
1550 super.processOptions(cmd);
1551 String[] args = cmd.getArgs();
1552
1553 if (args.length < 1) {
1554 printUsage(this.getClass().getSimpleName() +
1555 " <general options> COMMAND [<COMMAND options>]", "General options:", "");
1556 printCommands();
1557
1558 throw new RuntimeException("Incorrect Number of args.");
1559 }
1560 toRun = args[0];
1561 otherArgs = Arrays.copyOfRange(args, 1, args.length);
1562 }
1563
1564 @Override
1565 public int runTestFromCommandLine() throws Exception {
1566 Tool tool = null;
1567 if (toRun.equalsIgnoreCase("Generator")) {
1568 tool = new Generator();
1569 } else if (toRun.equalsIgnoreCase("Verify")) {
1570 tool = new Verify();
1571 } else if (toRun.equalsIgnoreCase("Loop")) {
1572 Loop loop = new Loop();
1573 loop.it = this;
1574 tool = loop;
1575 } else if (toRun.equalsIgnoreCase("Walker")) {
1576 tool = new Walker();
1577 } else if (toRun.equalsIgnoreCase("Print")) {
1578 tool = new Print();
1579 } else if (toRun.equalsIgnoreCase("Delete")) {
1580 tool = new Delete();
1581 } else if (toRun.equalsIgnoreCase("Clean")) {
1582 tool = new Clean();
1583 } else if (toRun.equalsIgnoreCase("Search")) {
1584 tool = new Search();
1585 } else {
1586 usage();
1587 throw new RuntimeException("Unknown arg");
1588 }
1589
1590 return ToolRunner.run(getConf(), tool, otherArgs);
1591 }
1592
1593 @Override
1594 public TableName getTablename() {
1595 Configuration c = getConf();
1596 return TableName.valueOf(c.get(TABLE_NAME_KEY, DEFAULT_TABLE_NAME));
1597 }
1598
1599 @Override
1600 protected Set<String> getColumnFamilies() {
1601 if (isMultiUnevenColumnFamilies()) {
1602 return Sets.newHashSet(Bytes.toString(FAMILY_NAME), Bytes.toString(BIG_FAMILY_NAME),
1603 Bytes.toString(TINY_FAMILY_NAME));
1604 } else {
1605 return Sets.newHashSet(Bytes.toString(FAMILY_NAME));
1606 }
1607 }
1608
1609 private static void setJobConf(Job job, int numMappers, long numNodes,
1610 Integer width, Integer wrapMultiplier) {
1611 job.getConfiguration().setInt(GENERATOR_NUM_MAPPERS_KEY, numMappers);
1612 job.getConfiguration().setLong(GENERATOR_NUM_ROWS_PER_MAP_KEY, numNodes);
1613 if (width != null) {
1614 job.getConfiguration().setInt(GENERATOR_WIDTH_KEY, width);
1615 }
1616 if (wrapMultiplier != null) {
1617 job.getConfiguration().setInt(GENERATOR_WRAP_KEY, wrapMultiplier);
1618 }
1619 }
1620
1621 public static void setJobScannerConf(Job job) {
1622
1623 job.getConfiguration().setBoolean(ScannerCallable.LOG_SCANNER_ACTIVITY, true);
1624 job.getConfiguration().setInt(TableRecordReaderImpl.LOG_PER_ROW_COUNT, 100000);
1625 }
1626
1627 public static void main(String[] args) throws Exception {
1628 Configuration conf = HBaseConfiguration.create();
1629 IntegrationTestingUtility.setUseDistributedCluster(conf);
1630 int ret = ToolRunner.run(conf, new IntegrationTestBigLinkedList(), args);
1631 System.exit(ret);
1632 }
1633 }