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