1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.hadoop.hbase;
20
21 import static org.codehaus.jackson.map.SerializationConfig.Feature.SORT_PROPERTIES_ALPHABETICALLY;
22
23 import java.io.IOException;
24 import java.io.PrintStream;
25 import java.lang.reflect.Constructor;
26 import java.math.BigDecimal;
27 import java.math.MathContext;
28 import java.text.DecimalFormat;
29 import java.text.SimpleDateFormat;
30 import java.util.ArrayList;
31 import java.util.Arrays;
32 import java.util.Date;
33 import java.util.LinkedList;
34 import java.util.Map;
35 import java.util.Queue;
36 import java.util.Random;
37 import java.util.TreeMap;
38 import java.util.concurrent.Callable;
39 import java.util.concurrent.ExecutionException;
40 import java.util.concurrent.ExecutorService;
41 import java.util.concurrent.Executors;
42 import java.util.concurrent.Future;
43
44 import com.google.common.base.Objects;
45 import com.google.common.util.concurrent.ThreadFactoryBuilder;
46
47 import org.apache.commons.lang.StringUtils;
48 import org.apache.commons.logging.Log;
49 import org.apache.commons.logging.LogFactory;
50 import org.apache.hadoop.conf.Configuration;
51 import org.apache.hadoop.conf.Configured;
52 import org.apache.hadoop.fs.FileSystem;
53 import org.apache.hadoop.fs.Path;
54 import org.apache.hadoop.hbase.classification.InterfaceAudience;
55 import org.apache.hadoop.hbase.client.Admin;
56 import org.apache.hadoop.hbase.client.Append;
57 import org.apache.hadoop.hbase.client.BufferedMutator;
58 import org.apache.hadoop.hbase.client.BufferedMutatorParams;
59 import org.apache.hadoop.hbase.client.Connection;
60 import org.apache.hadoop.hbase.client.ConnectionFactory;
61 import org.apache.hadoop.hbase.client.Consistency;
62 import org.apache.hadoop.hbase.client.Delete;
63 import org.apache.hadoop.hbase.client.Durability;
64 import org.apache.hadoop.hbase.client.Get;
65 import org.apache.hadoop.hbase.client.Increment;
66 import org.apache.hadoop.hbase.client.Put;
67 import org.apache.hadoop.hbase.client.Result;
68 import org.apache.hadoop.hbase.client.ResultScanner;
69 import org.apache.hadoop.hbase.client.RowMutations;
70 import org.apache.hadoop.hbase.client.Scan;
71 import org.apache.hadoop.hbase.client.Table;
72 import org.apache.hadoop.hbase.filter.BinaryComparator;
73 import org.apache.hadoop.hbase.filter.CompareFilter;
74 import org.apache.hadoop.hbase.filter.CompareFilter.CompareOp;
75 import org.apache.hadoop.hbase.filter.Filter;
76 import org.apache.hadoop.hbase.filter.FilterAllFilter;
77 import org.apache.hadoop.hbase.filter.FilterList;
78 import org.apache.hadoop.hbase.filter.PageFilter;
79 import org.apache.hadoop.hbase.filter.SingleColumnValueFilter;
80 import org.apache.hadoop.hbase.filter.WhileMatchFilter;
81 import org.apache.hadoop.hbase.io.compress.Compression;
82 import org.apache.hadoop.hbase.io.encoding.DataBlockEncoding;
83 import org.apache.hadoop.hbase.io.hfile.RandomDistribution;
84 import org.apache.hadoop.hbase.mapreduce.TableMapReduceUtil;
85 import org.apache.hadoop.hbase.regionserver.BloomType;
86 import org.apache.hadoop.hbase.trace.HBaseHTraceConfiguration;
87 import org.apache.hadoop.hbase.trace.SpanReceiverHost;
88 import org.apache.hadoop.hbase.util.*;
89 import org.apache.hadoop.io.LongWritable;
90 import org.apache.hadoop.io.Text;
91 import org.apache.hadoop.mapreduce.Job;
92 import org.apache.hadoop.mapreduce.Mapper;
93 import org.apache.hadoop.mapreduce.lib.input.NLineInputFormat;
94 import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
95 import org.apache.hadoop.mapreduce.lib.reduce.LongSumReducer;
96 import org.apache.hadoop.util.Tool;
97 import org.apache.hadoop.util.ToolRunner;
98 import org.codehaus.jackson.map.ObjectMapper;
99
100 import com.yammer.metrics.core.Histogram;
101 import com.yammer.metrics.stats.Snapshot;
102 import com.yammer.metrics.stats.UniformSample;
103
104 import org.apache.htrace.Sampler;
105 import org.apache.htrace.Trace;
106 import org.apache.htrace.TraceScope;
107 import org.apache.htrace.impl.ProbabilitySampler;
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126 @InterfaceAudience.LimitedPrivate(HBaseInterfaceAudience.TOOLS)
127 public class PerformanceEvaluation extends Configured implements Tool {
128 private static final Log LOG = LogFactory.getLog(PerformanceEvaluation.class.getName());
129 private static final ObjectMapper MAPPER = new ObjectMapper();
130 static {
131 MAPPER.configure(SORT_PROPERTIES_ALPHABETICALLY, true);
132 }
133
134 public static final String TABLE_NAME = "TestTable";
135 public static final String FAMILY_NAME_BASE = "info";
136 public static final byte[] FAMILY_ZERO = Bytes.toBytes("info0");
137 public static final byte[] COLUMN_ZERO = Bytes.toBytes("" + 0);
138 public static final int DEFAULT_VALUE_LENGTH = 1000;
139 public static final int ROW_LENGTH = 26;
140
141 private static final int ONE_GB = 1024 * 1024 * 1000;
142 private static final int DEFAULT_ROWS_PER_GB = ONE_GB / DEFAULT_VALUE_LENGTH;
143
144 private static final int TAG_LENGTH = 256;
145 private static final DecimalFormat FMT = new DecimalFormat("0.##");
146 private static final MathContext CXT = MathContext.DECIMAL64;
147 private static final BigDecimal MS_PER_SEC = BigDecimal.valueOf(1000);
148 private static final BigDecimal BYTES_PER_MB = BigDecimal.valueOf(1024 * 1024);
149 private static final TestOptions DEFAULT_OPTS = new TestOptions();
150
151 private static Map<String, CmdDescriptor> COMMANDS = new TreeMap<String, CmdDescriptor>();
152 private static final Path PERF_EVAL_DIR = new Path("performance_evaluation");
153
154 static {
155 addCommandDescriptor(RandomReadTest.class, "randomRead",
156 "Run random read test");
157 addCommandDescriptor(RandomSeekScanTest.class, "randomSeekScan",
158 "Run random seek and scan 100 test");
159 addCommandDescriptor(RandomScanWithRange10Test.class, "scanRange10",
160 "Run random seek scan with both start and stop row (max 10 rows)");
161 addCommandDescriptor(RandomScanWithRange100Test.class, "scanRange100",
162 "Run random seek scan with both start and stop row (max 100 rows)");
163 addCommandDescriptor(RandomScanWithRange1000Test.class, "scanRange1000",
164 "Run random seek scan with both start and stop row (max 1000 rows)");
165 addCommandDescriptor(RandomScanWithRange10000Test.class, "scanRange10000",
166 "Run random seek scan with both start and stop row (max 10000 rows)");
167 addCommandDescriptor(RandomWriteTest.class, "randomWrite",
168 "Run random write test");
169 addCommandDescriptor(SequentialReadTest.class, "sequentialRead",
170 "Run sequential read test");
171 addCommandDescriptor(SequentialWriteTest.class, "sequentialWrite",
172 "Run sequential write test");
173 addCommandDescriptor(ScanTest.class, "scan",
174 "Run scan test (read every row)");
175 addCommandDescriptor(FilteredScanTest.class, "filterScan",
176 "Run scan test using a filter to find a specific row based on it's value " +
177 "(make sure to use --rows=20)");
178 addCommandDescriptor(IncrementTest.class, "increment",
179 "Increment on each row; clients overlap on keyspace so some concurrent operations");
180 addCommandDescriptor(AppendTest.class, "append",
181 "Append on each row; clients overlap on keyspace so some concurrent operations");
182 addCommandDescriptor(CheckAndMutateTest.class, "checkAndMutate",
183 "CheckAndMutate on each row; clients overlap on keyspace so some concurrent operations");
184 addCommandDescriptor(CheckAndPutTest.class, "checkAndPut",
185 "CheckAndPut on each row; clients overlap on keyspace so some concurrent operations");
186 addCommandDescriptor(CheckAndDeleteTest.class, "checkAndDelete",
187 "CheckAndDelete on each row; clients overlap on keyspace so some concurrent operations");
188 }
189
190
191
192
193
194 protected static enum Counter {
195
196 ELAPSED_TIME,
197
198 ROWS
199 }
200
201 protected static class RunResult implements Comparable<RunResult> {
202 public RunResult(long duration, Histogram hist) {
203 this.duration = duration;
204 this.hist = hist;
205 }
206
207 public final long duration;
208 public final Histogram hist;
209
210 @Override
211 public String toString() {
212 return Long.toString(duration);
213 }
214
215 @Override public int compareTo(RunResult o) {
216 return Long.compare(this.duration, o.duration);
217 }
218 }
219
220
221
222
223
224 public PerformanceEvaluation(final Configuration conf) {
225 super(conf);
226 }
227
228 protected static void addCommandDescriptor(Class<? extends Test> cmdClass,
229 String name, String description) {
230 CmdDescriptor cmdDescriptor = new CmdDescriptor(cmdClass, name, description);
231 COMMANDS.put(name, cmdDescriptor);
232 }
233
234
235
236
237 interface Status {
238
239
240
241
242
243 void setStatus(final String msg) throws IOException;
244 }
245
246
247
248
249 public static class EvaluationMapTask
250 extends Mapper<LongWritable, Text, LongWritable, LongWritable> {
251
252
253 public final static String CMD_KEY = "EvaluationMapTask.command";
254
255 public static final String PE_KEY = "EvaluationMapTask.performanceEvalImpl";
256
257 private Class<? extends Test> cmd;
258
259 @Override
260 protected void setup(Context context) throws IOException, InterruptedException {
261 this.cmd = forName(context.getConfiguration().get(CMD_KEY), Test.class);
262
263
264
265 Class<? extends PerformanceEvaluation> peClass =
266 forName(context.getConfiguration().get(PE_KEY), PerformanceEvaluation.class);
267 try {
268 peClass.getConstructor(Configuration.class).newInstance(context.getConfiguration());
269 } catch (Exception e) {
270 throw new IllegalStateException("Could not instantiate PE instance", e);
271 }
272 }
273
274 private <Type> Class<? extends Type> forName(String className, Class<Type> type) {
275 try {
276 return Class.forName(className).asSubclass(type);
277 } catch (ClassNotFoundException e) {
278 throw new IllegalStateException("Could not find class for name: " + className, e);
279 }
280 }
281
282 @Override
283 protected void map(LongWritable key, Text value, final Context context)
284 throws IOException, InterruptedException {
285
286 Status status = new Status() {
287 @Override
288 public void setStatus(String msg) {
289 context.setStatus(msg);
290 }
291 };
292
293 ObjectMapper mapper = new ObjectMapper();
294 TestOptions opts = mapper.readValue(value.toString(), TestOptions.class);
295 Configuration conf = HBaseConfiguration.create(context.getConfiguration());
296 final Connection con = ConnectionFactory.createConnection(conf);
297
298
299 RunResult result = PerformanceEvaluation.runOneClient(this.cmd, conf, con, opts, status);
300
301
302 context.getCounter(Counter.ELAPSED_TIME).increment(result.duration);
303 context.getCounter(Counter.ROWS).increment(opts.perClientRunRows);
304 context.write(new LongWritable(opts.startRow), new LongWritable(result.duration));
305 context.progress();
306 }
307 }
308
309
310
311
312
313
314 static boolean checkTable(Admin admin, TestOptions opts) throws IOException {
315 TableName tableName = TableName.valueOf(opts.tableName);
316 boolean needsDelete = false, exists = admin.tableExists(tableName);
317 boolean isReadCmd = opts.cmdName.toLowerCase().contains("read")
318 || opts.cmdName.toLowerCase().contains("scan");
319 if (!exists && isReadCmd) {
320 throw new IllegalStateException(
321 "Must specify an existing table for read commands. Run a write command first.");
322 }
323 HTableDescriptor desc =
324 exists ? admin.getTableDescriptor(TableName.valueOf(opts.tableName)) : null;
325 byte[][] splits = getSplits(opts);
326
327
328
329 if ((exists && opts.presplitRegions != DEFAULT_OPTS.presplitRegions)
330 || (!isReadCmd && desc != null && !StringUtils.equals(desc.getRegionSplitPolicyClassName(), opts.splitPolicy))
331 || (!isReadCmd && desc != null && desc.getRegionReplication() != opts.replicas)) {
332 needsDelete = true;
333
334 LOG.debug(Objects.toStringHelper("needsDelete")
335 .add("needsDelete", needsDelete)
336 .add("isReadCmd", isReadCmd)
337 .add("exists", exists)
338 .add("desc", desc)
339 .add("presplit", opts.presplitRegions)
340 .add("splitPolicy", opts.splitPolicy)
341 .add("replicas", opts.replicas));
342 }
343
344
345 if (needsDelete) {
346 if (admin.isTableEnabled(tableName)) {
347 admin.disableTable(tableName);
348 }
349 admin.deleteTable(tableName);
350 }
351
352
353 if (!exists || needsDelete) {
354 desc = getTableDescriptor(opts);
355 if (splits != null) {
356 if (LOG.isDebugEnabled()) {
357 for (int i = 0; i < splits.length; i++) {
358 LOG.debug(" split " + i + ": " + Bytes.toStringBinary(splits[i]));
359 }
360 }
361 }
362 admin.createTable(desc, splits);
363 LOG.info("Table " + desc + " created");
364 }
365 return admin.tableExists(tableName);
366 }
367
368
369
370
371 protected static HTableDescriptor getTableDescriptor(TestOptions opts) {
372 HTableDescriptor tableDesc = new HTableDescriptor(TableName.valueOf(opts.tableName));
373 for (int family = 0; family < opts.families; family++) {
374 byte[] familyName = Bytes.toBytes(FAMILY_NAME_BASE + family);
375 HColumnDescriptor familyDesc = new HColumnDescriptor(familyName);
376 familyDesc.setDataBlockEncoding(opts.blockEncoding);
377 familyDesc.setCompressionType(opts.compression);
378 familyDesc.setBloomFilterType(opts.bloomType);
379 if (opts.inMemoryCF) {
380 familyDesc.setInMemory(true);
381 }
382 tableDesc.addFamily(familyDesc);
383 }
384 if (opts.replicas != DEFAULT_OPTS.replicas) {
385 tableDesc.setRegionReplication(opts.replicas);
386 }
387 if (opts.splitPolicy != null && !opts.splitPolicy.equals(DEFAULT_OPTS.splitPolicy)) {
388 tableDesc.setRegionSplitPolicyClassName(opts.splitPolicy);
389 }
390 return tableDesc;
391 }
392
393
394
395
396 protected static byte[][] getSplits(TestOptions opts) {
397 if (opts.presplitRegions == DEFAULT_OPTS.presplitRegions)
398 return null;
399
400 int numSplitPoints = opts.presplitRegions - 1;
401 byte[][] splits = new byte[numSplitPoints][];
402 int jump = opts.totalRows / opts.presplitRegions;
403 for (int i = 0; i < numSplitPoints; i++) {
404 int rowkey = jump * (1 + i);
405 splits[i] = format(rowkey);
406 }
407 return splits;
408 }
409
410
411
412
413 static RunResult[] doLocalClients(final TestOptions opts, final Configuration conf)
414 throws IOException, InterruptedException {
415 final Class<? extends Test> cmd = determineCommandClass(opts.cmdName);
416 assert cmd != null;
417 @SuppressWarnings("unchecked")
418 Future<RunResult>[] threads = new Future[opts.numClientThreads];
419 RunResult[] results = new RunResult[opts.numClientThreads];
420 ExecutorService pool = Executors.newFixedThreadPool(opts.numClientThreads,
421 new ThreadFactoryBuilder().setNameFormat("TestClient-%s").build());
422 final Connection con = ConnectionFactory.createConnection(conf);
423 for (int i = 0; i < threads.length; i++) {
424 final int index = i;
425 threads[i] = pool.submit(new Callable<RunResult>() {
426 @Override
427 public RunResult call() throws Exception {
428 TestOptions threadOpts = new TestOptions(opts);
429 if (threadOpts.startRow == 0) threadOpts.startRow = index * threadOpts.perClientRunRows;
430 RunResult run = runOneClient(cmd, conf, con, threadOpts, new Status() {
431 @Override
432 public void setStatus(final String msg) throws IOException {
433 LOG.info(msg);
434 }
435 });
436 LOG.info("Finished " + Thread.currentThread().getName() + " in " + run.duration +
437 "ms over " + threadOpts.perClientRunRows + " rows");
438 return run;
439 }
440 });
441 }
442 pool.shutdown();
443
444 for (int i = 0; i < threads.length; i++) {
445 try {
446 results[i] = threads[i].get();
447 } catch (ExecutionException e) {
448 throw new IOException(e.getCause());
449 }
450 }
451 final String test = cmd.getSimpleName();
452 LOG.info("[" + test + "] Summary of timings (ms): "
453 + Arrays.toString(results));
454 Arrays.sort(results);
455 long total = 0;
456 for (RunResult result : results) {
457 total += result.duration;
458 }
459 LOG.info("[" + test + "]"
460 + "\tMin: " + results[0] + "ms"
461 + "\tMax: " + results[results.length - 1] + "ms"
462 + "\tAvg: " + (total / results.length) + "ms");
463
464 con.close();
465
466 return results;
467 }
468
469
470
471
472
473
474
475
476 static Job doMapReduce(TestOptions opts, final Configuration conf)
477 throws IOException, InterruptedException, ClassNotFoundException {
478 final Class<? extends Test> cmd = determineCommandClass(opts.cmdName);
479 assert cmd != null;
480 Path inputDir = writeInputFile(conf, opts);
481 conf.set(EvaluationMapTask.CMD_KEY, cmd.getName());
482 conf.set(EvaluationMapTask.PE_KEY, PerformanceEvaluation.class.getName());
483 Job job = Job.getInstance(conf);
484 job.setJarByClass(PerformanceEvaluation.class);
485 job.setJobName("HBase Performance Evaluation - " + opts.cmdName);
486
487 job.setInputFormatClass(NLineInputFormat.class);
488 NLineInputFormat.setInputPaths(job, inputDir);
489
490 NLineInputFormat.setNumLinesPerSplit(job, 1);
491
492 job.setOutputKeyClass(LongWritable.class);
493 job.setOutputValueClass(LongWritable.class);
494
495 job.setMapperClass(EvaluationMapTask.class);
496 job.setReducerClass(LongSumReducer.class);
497
498 job.setNumReduceTasks(1);
499
500 job.setOutputFormatClass(TextOutputFormat.class);
501 TextOutputFormat.setOutputPath(job, new Path(inputDir.getParent(), "outputs"));
502
503 TableMapReduceUtil.addDependencyJars(job);
504 TableMapReduceUtil.addDependencyJars(job.getConfiguration(),
505 Histogram.class,
506 ObjectMapper.class);
507
508 TableMapReduceUtil.initCredentials(job);
509
510 job.waitForCompletion(true);
511 return job;
512 }
513
514
515
516
517
518
519
520 private static Path writeInputFile(final Configuration c, final TestOptions opts) throws IOException {
521 SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
522 Path jobdir = new Path(PERF_EVAL_DIR, formatter.format(new Date()));
523 Path inputDir = new Path(jobdir, "inputs");
524
525 FileSystem fs = FileSystem.get(c);
526 fs.mkdirs(inputDir);
527
528 Path inputFile = new Path(inputDir, "input.txt");
529 PrintStream out = new PrintStream(fs.create(inputFile));
530
531 Map<Integer, String> m = new TreeMap<Integer, String>();
532 Hash h = MurmurHash.getInstance();
533 int perClientRows = (opts.totalRows / opts.numClientThreads);
534 try {
535 for (int i = 0; i < 10; i++) {
536 for (int j = 0; j < opts.numClientThreads; j++) {
537 TestOptions next = new TestOptions(opts);
538 next.startRow = (j * perClientRows) + (i * (perClientRows/10));
539 next.perClientRunRows = perClientRows / 10;
540 String s = MAPPER.writeValueAsString(next);
541 LOG.info("maptask input=" + s);
542 int hash = h.hash(Bytes.toBytes(s));
543 m.put(hash, s);
544 }
545 }
546 for (Map.Entry<Integer, String> e: m.entrySet()) {
547 out.println(e.getValue());
548 }
549 } finally {
550 out.close();
551 }
552 return inputDir;
553 }
554
555
556
557
558 static class CmdDescriptor {
559 private Class<? extends Test> cmdClass;
560 private String name;
561 private String description;
562
563 CmdDescriptor(Class<? extends Test> cmdClass, String name, String description) {
564 this.cmdClass = cmdClass;
565 this.name = name;
566 this.description = description;
567 }
568
569 public Class<? extends Test> getCmdClass() {
570 return cmdClass;
571 }
572
573 public String getName() {
574 return name;
575 }
576
577 public String getDescription() {
578 return description;
579 }
580 }
581
582
583
584
585
586
587
588
589 static class TestOptions {
590 String cmdName = null;
591 boolean nomapred = false;
592 boolean filterAll = false;
593 int startRow = 0;
594 float size = 1.0f;
595 int perClientRunRows = DEFAULT_ROWS_PER_GB;
596 int numClientThreads = 1;
597 int totalRows = DEFAULT_ROWS_PER_GB;
598 float sampleRate = 1.0f;
599 double traceRate = 0.0;
600 String tableName = TABLE_NAME;
601 boolean flushCommits = true;
602 boolean writeToWAL = true;
603 boolean autoFlush = false;
604 boolean oneCon = false;
605 boolean useTags = false;
606 int noOfTags = 1;
607 boolean reportLatency = false;
608 int multiGet = 0;
609 int randomSleep = 0;
610 boolean inMemoryCF = false;
611 int presplitRegions = 0;
612 int replicas = HTableDescriptor.DEFAULT_REGION_REPLICATION;
613 String splitPolicy = null;
614 Compression.Algorithm compression = Compression.Algorithm.NONE;
615 BloomType bloomType = BloomType.ROW;
616 DataBlockEncoding blockEncoding = DataBlockEncoding.NONE;
617 boolean valueRandom = false;
618 boolean valueZipf = false;
619 int valueSize = DEFAULT_VALUE_LENGTH;
620 int period = (this.perClientRunRows / 10) == 0? perClientRunRows: perClientRunRows / 10;
621 int columns = 1;
622 int families = 1;
623 int caching = 30;
624 boolean addColumns = true;
625 long bufferSize = 2l * 1024l * 1024l;
626
627 public TestOptions() {}
628
629
630
631
632
633 public TestOptions(TestOptions that) {
634 this.cmdName = that.cmdName;
635 this.nomapred = that.nomapred;
636 this.startRow = that.startRow;
637 this.size = that.size;
638 this.perClientRunRows = that.perClientRunRows;
639 this.numClientThreads = that.numClientThreads;
640 this.totalRows = that.totalRows;
641 this.sampleRate = that.sampleRate;
642 this.traceRate = that.traceRate;
643 this.tableName = that.tableName;
644 this.flushCommits = that.flushCommits;
645 this.writeToWAL = that.writeToWAL;
646 this.autoFlush = that.autoFlush;
647 this.oneCon = that.oneCon;
648 this.useTags = that.useTags;
649 this.noOfTags = that.noOfTags;
650 this.reportLatency = that.reportLatency;
651 this.multiGet = that.multiGet;
652 this.inMemoryCF = that.inMemoryCF;
653 this.presplitRegions = that.presplitRegions;
654 this.replicas = that.replicas;
655 this.splitPolicy = that.splitPolicy;
656 this.compression = that.compression;
657 this.blockEncoding = that.blockEncoding;
658 this.filterAll = that.filterAll;
659 this.bloomType = that.bloomType;
660 this.valueRandom = that.valueRandom;
661 this.valueZipf = that.valueZipf;
662 this.valueSize = that.valueSize;
663 this.period = that.period;
664 this.randomSleep = that.randomSleep;
665 this.addColumns = that.addColumns;
666 this.columns = that.columns;
667 this.families = that.families;
668 this.caching = that.caching;
669 this.bufferSize = that.bufferSize;
670 }
671
672 public int getCaching() {
673 return this.caching;
674 }
675
676 public void setCaching(final int caching) {
677 this.caching = caching;
678 }
679
680 public int getColumns() {
681 return this.columns;
682 }
683
684 public void setColumns(final int columns) {
685 this.columns = columns;
686 }
687
688 public int getFamilies() {
689 return this.families;
690 }
691
692 public void setFamilies(final int families) {
693 this.families = families;
694 }
695
696 public boolean isValueZipf() {
697 return valueZipf;
698 }
699
700 public void setValueZipf(boolean valueZipf) {
701 this.valueZipf = valueZipf;
702 }
703
704 public String getCmdName() {
705 return cmdName;
706 }
707
708 public void setCmdName(String cmdName) {
709 this.cmdName = cmdName;
710 }
711
712 public int getRandomSleep() {
713 return randomSleep;
714 }
715
716 public void setRandomSleep(int randomSleep) {
717 this.randomSleep = randomSleep;
718 }
719
720 public int getReplicas() {
721 return replicas;
722 }
723
724 public void setReplicas(int replicas) {
725 this.replicas = replicas;
726 }
727
728 public String getSplitPolicy() {
729 return splitPolicy;
730 }
731
732 public void setSplitPolicy(String splitPolicy) {
733 this.splitPolicy = splitPolicy;
734 }
735
736 public void setNomapred(boolean nomapred) {
737 this.nomapred = nomapred;
738 }
739
740 public void setFilterAll(boolean filterAll) {
741 this.filterAll = filterAll;
742 }
743
744 public void setStartRow(int startRow) {
745 this.startRow = startRow;
746 }
747
748 public void setSize(float size) {
749 this.size = size;
750 }
751
752 public void setPerClientRunRows(int perClientRunRows) {
753 this.perClientRunRows = perClientRunRows;
754 }
755
756 public void setNumClientThreads(int numClientThreads) {
757 this.numClientThreads = numClientThreads;
758 }
759
760 public void setTotalRows(int totalRows) {
761 this.totalRows = totalRows;
762 }
763
764 public void setSampleRate(float sampleRate) {
765 this.sampleRate = sampleRate;
766 }
767
768 public void setTraceRate(double traceRate) {
769 this.traceRate = traceRate;
770 }
771
772 public void setTableName(String tableName) {
773 this.tableName = tableName;
774 }
775
776 public void setFlushCommits(boolean flushCommits) {
777 this.flushCommits = flushCommits;
778 }
779
780 public void setWriteToWAL(boolean writeToWAL) {
781 this.writeToWAL = writeToWAL;
782 }
783
784 public void setAutoFlush(boolean autoFlush) {
785 this.autoFlush = autoFlush;
786 }
787
788 public void setOneCon(boolean oneCon) {
789 this.oneCon = oneCon;
790 }
791
792 public void setUseTags(boolean useTags) {
793 this.useTags = useTags;
794 }
795
796 public void setNoOfTags(int noOfTags) {
797 this.noOfTags = noOfTags;
798 }
799
800 public void setReportLatency(boolean reportLatency) {
801 this.reportLatency = reportLatency;
802 }
803
804 public void setMultiGet(int multiGet) {
805 this.multiGet = multiGet;
806 }
807
808 public void setInMemoryCF(boolean inMemoryCF) {
809 this.inMemoryCF = inMemoryCF;
810 }
811
812 public void setPresplitRegions(int presplitRegions) {
813 this.presplitRegions = presplitRegions;
814 }
815
816 public void setCompression(Compression.Algorithm compression) {
817 this.compression = compression;
818 }
819
820 public void setBloomType(BloomType bloomType) {
821 this.bloomType = bloomType;
822 }
823
824 public void setBlockEncoding(DataBlockEncoding blockEncoding) {
825 this.blockEncoding = blockEncoding;
826 }
827
828 public void setValueRandom(boolean valueRandom) {
829 this.valueRandom = valueRandom;
830 }
831
832 public void setValueSize(int valueSize) {
833 this.valueSize = valueSize;
834 }
835
836 public void setBufferSize(long bufferSize) {
837 this.bufferSize = bufferSize;
838 }
839
840 public long getBufferSize() {
841 return this.bufferSize;
842 }
843
844 public void setPeriod(int period) {
845 this.period = period;
846 }
847
848 public boolean isNomapred() {
849 return nomapred;
850 }
851
852 public boolean isFilterAll() {
853 return filterAll;
854 }
855
856 public int getStartRow() {
857 return startRow;
858 }
859
860 public float getSize() {
861 return size;
862 }
863
864 public int getPerClientRunRows() {
865 return perClientRunRows;
866 }
867
868 public int getNumClientThreads() {
869 return numClientThreads;
870 }
871
872 public int getTotalRows() {
873 return totalRows;
874 }
875
876 public float getSampleRate() {
877 return sampleRate;
878 }
879
880 public double getTraceRate() {
881 return traceRate;
882 }
883
884 public String getTableName() {
885 return tableName;
886 }
887
888 public boolean isFlushCommits() {
889 return flushCommits;
890 }
891
892 public boolean isWriteToWAL() {
893 return writeToWAL;
894 }
895
896 public boolean isAutoFlush() {
897 return autoFlush;
898 }
899
900 public boolean isUseTags() {
901 return useTags;
902 }
903
904 public int getNoOfTags() {
905 return noOfTags;
906 }
907
908 public boolean isReportLatency() {
909 return reportLatency;
910 }
911
912 public int getMultiGet() {
913 return multiGet;
914 }
915
916 public boolean isInMemoryCF() {
917 return inMemoryCF;
918 }
919
920 public int getPresplitRegions() {
921 return presplitRegions;
922 }
923
924 public Compression.Algorithm getCompression() {
925 return compression;
926 }
927
928 public DataBlockEncoding getBlockEncoding() {
929 return blockEncoding;
930 }
931
932 public boolean isValueRandom() {
933 return valueRandom;
934 }
935
936 public int getValueSize() {
937 return valueSize;
938 }
939
940 public int getPeriod() {
941 return period;
942 }
943
944 public BloomType getBloomType() {
945 return bloomType;
946 }
947
948 public boolean isOneCon() {
949 return oneCon;
950 }
951
952 public boolean getAddColumns() {
953 return addColumns;
954 }
955
956 public void setAddColumns(boolean addColumns) {
957 this.addColumns = addColumns;
958 }
959 }
960
961
962
963
964
965 static abstract class Test {
966
967
968 private static final Random randomSeed = new Random(System.currentTimeMillis());
969
970 private static long nextRandomSeed() {
971 return randomSeed.nextLong();
972 }
973 private final int everyN;
974
975 protected final Random rand = new Random(nextRandomSeed());
976 protected final Configuration conf;
977 protected final TestOptions opts;
978
979 private final Status status;
980 private final Sampler<?> traceSampler;
981 private final SpanReceiverHost receiverHost;
982 protected Connection connection;
983
984 private String testName;
985 private Histogram latency;
986 private Histogram valueSize;
987 private RandomDistribution.Zipf zipf;
988
989
990
991
992
993 Test(final Connection con, final TestOptions options, final Status status) {
994 this.connection = con;
995 this.conf = con == null ? HBaseConfiguration.create() : this.connection.getConfiguration();
996 this.opts = options;
997 this.status = status;
998 this.testName = this.getClass().getSimpleName();
999 receiverHost = SpanReceiverHost.getInstance(conf);
1000 if (options.traceRate >= 1.0) {
1001 this.traceSampler = Sampler.ALWAYS;
1002 } else if (options.traceRate > 0.0) {
1003 conf.setDouble("hbase.sampler.fraction", options.traceRate);
1004 this.traceSampler = new ProbabilitySampler(new HBaseHTraceConfiguration(conf));
1005 } else {
1006 this.traceSampler = Sampler.NEVER;
1007 }
1008 everyN = (int) (opts.totalRows / (opts.totalRows * opts.sampleRate));
1009 if (options.isValueZipf()) {
1010 this.zipf = new RandomDistribution.Zipf(this.rand, 1, options.getValueSize(), 1.1);
1011 }
1012 LOG.info("Sampling 1 every " + everyN + " out of " + opts.perClientRunRows + " total rows.");
1013 }
1014
1015 int getValueLength(final Random r) {
1016 if (this.opts.isValueRandom()) return Math.abs(r.nextInt() % opts.valueSize);
1017 else if (this.opts.isValueZipf()) return Math.abs(this.zipf.nextInt());
1018 else return opts.valueSize;
1019 }
1020
1021 void updateValueSize(final Result [] rs) throws IOException {
1022 if (rs == null || !isRandomValueSize()) return;
1023 for (Result r: rs) updateValueSize(r);
1024 }
1025
1026 void updateValueSize(final Result r) throws IOException {
1027 if (r == null || !isRandomValueSize()) return;
1028 int size = 0;
1029 for (CellScanner scanner = r.cellScanner(); scanner.advance();) {
1030 size += scanner.current().getValueLength();
1031 }
1032 updateValueSize(size);
1033 }
1034
1035 void updateValueSize(final int valueSize) {
1036 if (!isRandomValueSize()) return;
1037 this.valueSize.update(valueSize);
1038 }
1039
1040 String generateStatus(final int sr, final int i, final int lr) {
1041 return sr + "/" + i + "/" + lr + ", latency " + getShortLatencyReport() +
1042 (!isRandomValueSize()? "": ", value size " + getShortValueSizeReport());
1043 }
1044
1045 boolean isRandomValueSize() {
1046 return opts.valueRandom;
1047 }
1048
1049 protected int getReportingPeriod() {
1050 return opts.period;
1051 }
1052
1053
1054
1055
1056 public Histogram getLatency() {
1057 return latency;
1058 }
1059
1060 void testSetup() throws IOException {
1061 if (!opts.oneCon) {
1062 this.connection = ConnectionFactory.createConnection(conf);
1063 }
1064 onStartup();
1065 latency = YammerHistogramUtils.newHistogram(new UniformSample(1024 * 500));
1066 valueSize = YammerHistogramUtils.newHistogram(new UniformSample(1024 * 500));
1067 }
1068
1069 abstract void onStartup() throws IOException;
1070
1071 void testTakedown() throws IOException {
1072 reportLatency();
1073 reportValueSize();
1074 onTakedown();
1075 if (!opts.oneCon) {
1076 connection.close();
1077 }
1078 receiverHost.closeReceivers();
1079 }
1080
1081 abstract void onTakedown() throws IOException;
1082
1083
1084
1085
1086
1087
1088 long test() throws IOException, InterruptedException {
1089 testSetup();
1090 LOG.info("Timed test starting in thread " + Thread.currentThread().getName());
1091 final long startTime = System.nanoTime();
1092 try {
1093 testTimed();
1094 } finally {
1095 testTakedown();
1096 }
1097 return (System.nanoTime() - startTime) / 1000000;
1098 }
1099
1100 int getStartRow() {
1101 return opts.startRow;
1102 }
1103
1104 int getLastRow() {
1105 return getStartRow() + opts.perClientRunRows;
1106 }
1107
1108
1109
1110
1111 void testTimed() throws IOException, InterruptedException {
1112 int startRow = getStartRow();
1113 int lastRow = getLastRow();
1114
1115 for (int i = startRow; i < lastRow; i++) {
1116 if (i % everyN != 0) continue;
1117 long startTime = System.nanoTime();
1118 TraceScope scope = Trace.startSpan("test row", traceSampler);
1119 try {
1120 testRow(i);
1121 } finally {
1122 scope.close();
1123 }
1124 latency.update((System.nanoTime() - startTime) / 1000);
1125 if (status != null && i > 0 && (i % getReportingPeriod()) == 0) {
1126 status.setStatus(generateStatus(startRow, i, lastRow));
1127 }
1128 }
1129 }
1130
1131
1132
1133
1134
1135 private void reportLatency() throws IOException {
1136 status.setStatus(testName + " latency log (microseconds), on " +
1137 latency.count() + " measures");
1138 reportHistogram(this.latency);
1139 }
1140
1141 private void reportValueSize() throws IOException {
1142 status.setStatus(testName + " valueSize after " +
1143 valueSize.count() + " measures");
1144 reportHistogram(this.valueSize);
1145 }
1146
1147 private void reportHistogram(final Histogram h) throws IOException {
1148 Snapshot sn = h.getSnapshot();
1149 status.setStatus(testName + " Min = " + h.min());
1150 status.setStatus(testName + " Avg = " + h.mean());
1151 status.setStatus(testName + " StdDev = " + h.stdDev());
1152 status.setStatus(testName + " 50th = " + sn.getMedian());
1153 status.setStatus(testName + " 75th = " + sn.get75thPercentile());
1154 status.setStatus(testName + " 95th = " + sn.get95thPercentile());
1155 status.setStatus(testName + " 99th = " + sn.get99thPercentile());
1156 status.setStatus(testName + " 99.9th = " + sn.get999thPercentile());
1157 status.setStatus(testName + " 99.99th = " + sn.getValue(0.9999));
1158 status.setStatus(testName + " 99.999th = " + sn.getValue(0.99999));
1159 status.setStatus(testName + " Max = " + h.max());
1160 }
1161
1162
1163
1164
1165 public String getShortLatencyReport() {
1166 return YammerHistogramUtils.getShortHistogramReport(this.latency);
1167 }
1168
1169
1170
1171
1172 public String getShortValueSizeReport() {
1173 return YammerHistogramUtils.getShortHistogramReport(this.valueSize);
1174 }
1175
1176
1177
1178
1179
1180 abstract void testRow(final int i) throws IOException, InterruptedException;
1181 }
1182
1183 static abstract class TableTest extends Test {
1184 protected Table table;
1185
1186 TableTest(Connection con, TestOptions options, Status status) {
1187 super(con, options, status);
1188 }
1189
1190 @Override
1191 void onStartup() throws IOException {
1192 this.table = connection.getTable(TableName.valueOf(opts.tableName));
1193 }
1194
1195 @Override
1196 void onTakedown() throws IOException {
1197 table.close();
1198 }
1199 }
1200
1201 static abstract class BufferedMutatorTest extends Test {
1202 protected BufferedMutator mutator;
1203
1204 BufferedMutatorTest(Connection con, TestOptions options, Status status) {
1205 super(con, options, status);
1206 }
1207
1208 @Override
1209 void onStartup() throws IOException {
1210 BufferedMutatorParams p = new BufferedMutatorParams(TableName.valueOf(opts.tableName));
1211 p.writeBufferSize(opts.bufferSize);
1212 this.mutator = connection.getBufferedMutator(p);
1213 }
1214
1215 @Override
1216 void onTakedown() throws IOException {
1217 mutator.close();
1218 }
1219 }
1220
1221 static class RandomSeekScanTest extends TableTest {
1222 RandomSeekScanTest(Connection con, TestOptions options, Status status) {
1223 super(con, options, status);
1224 }
1225
1226 @Override
1227 void testRow(final int i) throws IOException {
1228 Scan scan = new Scan(getRandomRow(this.rand, opts.totalRows));
1229 scan.setCaching(opts.caching);
1230 FilterList list = new FilterList();
1231 for (int family = 0; family < opts.families; family++) {
1232 byte[] familyName = Bytes.toBytes(FAMILY_NAME_BASE + family);
1233 if (opts.addColumns) {
1234 for (int column = 0; column < opts.columns; column++) {
1235 byte [] qualifier = column == 0? COLUMN_ZERO: Bytes.toBytes("" + column);
1236 scan.addColumn(familyName, qualifier);
1237 }
1238 } else {
1239 scan.addFamily(familyName);
1240 }
1241 }
1242 if (opts.filterAll) {
1243 list.addFilter(new FilterAllFilter());
1244 }
1245 list.addFilter(new WhileMatchFilter(new PageFilter(120)));
1246 scan.setFilter(list);
1247 ResultScanner s = this.table.getScanner(scan);
1248 for (Result rr; (rr = s.next()) != null;) {
1249 updateValueSize(rr);
1250 }
1251 s.close();
1252 }
1253
1254 @Override
1255 protected int getReportingPeriod() {
1256 int period = opts.perClientRunRows / 100;
1257 return period == 0 ? opts.perClientRunRows : period;
1258 }
1259
1260 }
1261
1262 static abstract class RandomScanWithRangeTest extends TableTest {
1263 RandomScanWithRangeTest(Connection con, TestOptions options, Status status) {
1264 super(con, options, status);
1265 }
1266
1267 @Override
1268 void testRow(final int i) throws IOException {
1269 Pair<byte[], byte[]> startAndStopRow = getStartAndStopRow();
1270 Scan scan = new Scan(startAndStopRow.getFirst(), startAndStopRow.getSecond());
1271 for (int family = 0; family < opts.families; family++) {
1272 byte[] familyName = Bytes.toBytes(FAMILY_NAME_BASE + family);
1273 if (opts.addColumns) {
1274 for (int column = 0; column < opts.columns; column++) {
1275 byte [] qualifier = column == 0? COLUMN_ZERO: Bytes.toBytes("" + column);
1276 scan.addColumn(familyName, qualifier);
1277 }
1278 } else {
1279 scan.addFamily(familyName);
1280 }
1281 }
1282 if (opts.filterAll) {
1283 scan.setFilter(new FilterAllFilter());
1284 }
1285 scan.setCaching(opts.caching);
1286 scan.setScanMetricsEnabled(true);
1287 Result r = null;
1288 int count = 0;
1289 ResultScanner s = this.table.getScanner(scan);
1290 for (; (r = s.next()) != null;) {
1291 updateValueSize(r);
1292 count++;
1293 }
1294 if (i % 100 == 0) {
1295 LOG.info(String.format("Scan for key range %s - %s returned %s rows",
1296 Bytes.toString(startAndStopRow.getFirst()),
1297 Bytes.toString(startAndStopRow.getSecond()), count));
1298 }
1299
1300 s.close();
1301 }
1302
1303 protected abstract Pair<byte[],byte[]> getStartAndStopRow();
1304
1305 protected Pair<byte[], byte[]> generateStartAndStopRows(int maxRange) {
1306 int start = this.rand.nextInt(Integer.MAX_VALUE) % opts.totalRows;
1307 int stop = start + maxRange;
1308 return new Pair<byte[],byte[]>(format(start), format(stop));
1309 }
1310
1311 @Override
1312 protected int getReportingPeriod() {
1313 int period = opts.perClientRunRows / 100;
1314 return period == 0? opts.perClientRunRows: period;
1315 }
1316 }
1317
1318 static class RandomScanWithRange10Test extends RandomScanWithRangeTest {
1319 RandomScanWithRange10Test(Connection con, TestOptions options, Status status) {
1320 super(con, options, status);
1321 }
1322
1323 @Override
1324 protected Pair<byte[], byte[]> getStartAndStopRow() {
1325 return generateStartAndStopRows(10);
1326 }
1327 }
1328
1329 static class RandomScanWithRange100Test extends RandomScanWithRangeTest {
1330 RandomScanWithRange100Test(Connection con, TestOptions options, Status status) {
1331 super(con, options, status);
1332 }
1333
1334 @Override
1335 protected Pair<byte[], byte[]> getStartAndStopRow() {
1336 return generateStartAndStopRows(100);
1337 }
1338 }
1339
1340 static class RandomScanWithRange1000Test extends RandomScanWithRangeTest {
1341 RandomScanWithRange1000Test(Connection con, TestOptions options, Status status) {
1342 super(con, options, status);
1343 }
1344
1345 @Override
1346 protected Pair<byte[], byte[]> getStartAndStopRow() {
1347 return generateStartAndStopRows(1000);
1348 }
1349 }
1350
1351 static class RandomScanWithRange10000Test extends RandomScanWithRangeTest {
1352 RandomScanWithRange10000Test(Connection con, TestOptions options, Status status) {
1353 super(con, options, status);
1354 }
1355
1356 @Override
1357 protected Pair<byte[], byte[]> getStartAndStopRow() {
1358 return generateStartAndStopRows(10000);
1359 }
1360 }
1361
1362 static class RandomReadTest extends TableTest {
1363 private final Consistency consistency;
1364 private ArrayList<Get> gets;
1365 private Random rd = new Random();
1366
1367 RandomReadTest(Connection con, TestOptions options, Status status) {
1368 super(con, options, status);
1369 consistency = options.replicas == DEFAULT_OPTS.replicas ? null : Consistency.TIMELINE;
1370 if (opts.multiGet > 0) {
1371 LOG.info("MultiGet enabled. Sending GETs in batches of " + opts.multiGet + ".");
1372 this.gets = new ArrayList<Get>(opts.multiGet);
1373 }
1374 }
1375
1376 @Override
1377 void testRow(final int i) throws IOException, InterruptedException {
1378 if (opts.randomSleep > 0) {
1379 Thread.sleep(rd.nextInt(opts.randomSleep));
1380 }
1381 Get get = new Get(getRandomRow(this.rand, opts.totalRows));
1382 for (int family = 0; family < opts.families; family++) {
1383 byte[] familyName = Bytes.toBytes(FAMILY_NAME_BASE + family);
1384 if (opts.addColumns) {
1385 for (int column = 0; column < opts.columns; column++) {
1386 byte [] qualifier = column == 0? COLUMN_ZERO: Bytes.toBytes("" + column);
1387 get.addColumn(familyName, qualifier);
1388 }
1389 } else {
1390 get.addFamily(familyName);
1391 }
1392 }
1393 if (opts.filterAll) {
1394 get.setFilter(new FilterAllFilter());
1395 }
1396 get.setConsistency(consistency);
1397 if (LOG.isTraceEnabled()) LOG.trace(get.toString());
1398 if (opts.multiGet > 0) {
1399 this.gets.add(get);
1400 if (this.gets.size() == opts.multiGet) {
1401 Result [] rs = this.table.get(this.gets);
1402 updateValueSize(rs);
1403 this.gets.clear();
1404 }
1405 } else {
1406 updateValueSize(this.table.get(get));
1407 }
1408 }
1409
1410 @Override
1411 protected int getReportingPeriod() {
1412 int period = opts.perClientRunRows / 10;
1413 return period == 0 ? opts.perClientRunRows : period;
1414 }
1415
1416 @Override
1417 protected void testTakedown() throws IOException {
1418 if (this.gets != null && this.gets.size() > 0) {
1419 this.table.get(gets);
1420 this.gets.clear();
1421 }
1422 super.testTakedown();
1423 }
1424 }
1425
1426 static class RandomWriteTest extends BufferedMutatorTest {
1427 RandomWriteTest(Connection con, TestOptions options, Status status) {
1428 super(con, options, status);
1429 }
1430
1431 @Override
1432 void testRow(final int i) throws IOException {
1433 byte[] row = getRandomRow(this.rand, opts.totalRows);
1434 Put put = new Put(row);
1435 for (int family = 0; family < opts.families; family++) {
1436 byte[] familyName = Bytes.toBytes(FAMILY_NAME_BASE + family);
1437 for (int column = 0; column < opts.columns; column++) {
1438 byte [] qualifier = column == 0? COLUMN_ZERO: Bytes.toBytes("" + column);
1439 byte[] value = generateData(this.rand, getValueLength(this.rand));
1440 if (opts.useTags) {
1441 byte[] tag = generateData(this.rand, TAG_LENGTH);
1442 Tag[] tags = new Tag[opts.noOfTags];
1443 for (int n = 0; n < opts.noOfTags; n++) {
1444 Tag t = new Tag((byte) n, tag);
1445 tags[n] = t;
1446 }
1447 KeyValue kv = new KeyValue(row, familyName, qualifier, HConstants.LATEST_TIMESTAMP,
1448 value, tags);
1449 put.add(kv);
1450 updateValueSize(kv.getValueLength());
1451 } else {
1452 put.add(familyName, qualifier, value);
1453 updateValueSize(value.length);
1454 }
1455 }
1456 }
1457 put.setDurability(opts.writeToWAL ? Durability.SYNC_WAL : Durability.SKIP_WAL);
1458 mutator.mutate(put);
1459 if (opts.autoFlush) {
1460 mutator.flush();
1461 }
1462 }
1463 }
1464
1465 static class ScanTest extends TableTest {
1466 private ResultScanner testScanner;
1467
1468 ScanTest(Connection con, TestOptions options, Status status) {
1469 super(con, options, status);
1470 }
1471
1472 @Override
1473 void testTakedown() throws IOException {
1474 if (this.testScanner != null) {
1475 this.testScanner.close();
1476 }
1477 super.testTakedown();
1478 }
1479
1480
1481 @Override
1482 void testRow(final int i) throws IOException {
1483 if (this.testScanner == null) {
1484 Scan scan = new Scan(format(opts.startRow));
1485 for (int family = 0; family < opts.families; family++) {
1486 byte[] familyName = Bytes.toBytes(FAMILY_NAME_BASE + family);
1487 if (opts.addColumns) {
1488 for (int column = 0; column < opts.columns; column++) {
1489 byte [] qualifier = column == 0? COLUMN_ZERO: Bytes.toBytes("" + column);
1490 scan.addColumn(familyName, qualifier);
1491 }
1492 } else {
1493 scan.addFamily(familyName);
1494 }
1495 }
1496 if (opts.filterAll) {
1497 scan.setFilter(new FilterAllFilter());
1498 }
1499 scan.setCaching(opts.caching);
1500 this.testScanner = table.getScanner(scan);
1501 }
1502 Result r = testScanner.next();
1503 updateValueSize(r);
1504 }
1505 }
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515 static abstract class CASTableTest extends TableTest {
1516 private final byte [] qualifier;
1517 CASTableTest(Connection con, TestOptions options, Status status) {
1518 super(con, options, status);
1519 qualifier = Bytes.toBytes(this.getClass().getSimpleName());
1520 }
1521
1522 byte [] getQualifier() {
1523 return this.qualifier;
1524 }
1525
1526 @Override
1527 int getStartRow() {
1528 return 0;
1529 }
1530
1531 @Override
1532 int getLastRow() {
1533 return opts.perClientRunRows;
1534 }
1535 }
1536
1537 static class IncrementTest extends CASTableTest {
1538 IncrementTest(Connection con, TestOptions options, Status status) {
1539 super(con, options, status);
1540 }
1541
1542 @Override
1543 void testRow(final int i) throws IOException {
1544 Increment increment = new Increment(format(i));
1545
1546
1547
1548 for (int family = 0; family < opts.families; family++) {
1549 byte[] familyName = Bytes.toBytes(FAMILY_NAME_BASE + family);
1550 increment.addColumn(familyName, getQualifier(), 1l);
1551 }
1552 updateValueSize(this.table.increment(increment));
1553 }
1554 }
1555
1556 static class AppendTest extends CASTableTest {
1557 AppendTest(Connection con, TestOptions options, Status status) {
1558 super(con, options, status);
1559 }
1560
1561 @Override
1562 void testRow(final int i) throws IOException {
1563 byte [] bytes = format(i);
1564 Append append = new Append(bytes);
1565
1566
1567
1568 for (int family = 0; family < opts.families; family++) {
1569 byte[] familyName = Bytes.toBytes(FAMILY_NAME_BASE + family);
1570 append.add(familyName, getQualifier(), bytes);
1571 }
1572 updateValueSize(this.table.append(append));
1573 }
1574 }
1575
1576 static class CheckAndMutateTest extends CASTableTest {
1577 CheckAndMutateTest(Connection con, TestOptions options, Status status) {
1578 super(con, options, status);
1579 }
1580
1581 @Override
1582 void testRow(final int i) throws IOException {
1583 final byte [] bytes = format(i);
1584
1585
1586 Put put = new Put(bytes);
1587 put.addColumn(FAMILY_ZERO, getQualifier(), bytes);
1588 this.table.put(put);
1589 RowMutations mutations = new RowMutations(bytes);
1590 mutations.add(put);
1591 this.table.checkAndMutate(bytes, FAMILY_ZERO, getQualifier(), CompareOp.EQUAL, bytes,
1592 mutations);
1593 }
1594 }
1595
1596 static class CheckAndPutTest extends CASTableTest {
1597 CheckAndPutTest(Connection con, TestOptions options, Status status) {
1598 super(con, options, status);
1599 }
1600
1601 @Override
1602 void testRow(final int i) throws IOException {
1603 final byte [] bytes = format(i);
1604
1605
1606 Put put = new Put(bytes);
1607 put.addColumn(FAMILY_ZERO, getQualifier(), bytes);
1608 this.table.put(put);
1609 this.table.checkAndPut(bytes, FAMILY_ZERO, getQualifier(), CompareOp.EQUAL, bytes, put);
1610 }
1611 }
1612
1613 static class CheckAndDeleteTest extends CASTableTest {
1614 CheckAndDeleteTest(Connection con, TestOptions options, Status status) {
1615 super(con, options, status);
1616 }
1617
1618 @Override
1619 void testRow(final int i) throws IOException {
1620 final byte [] bytes = format(i);
1621
1622
1623 Put put = new Put(bytes);
1624 put.addColumn(FAMILY_ZERO, getQualifier(), bytes);
1625 this.table.put(put);
1626 Delete delete = new Delete(put.getRow());
1627 delete.addColumn(FAMILY_ZERO, getQualifier());
1628 this.table.checkAndDelete(bytes, FAMILY_ZERO, getQualifier(), CompareOp.EQUAL, bytes, delete);
1629 }
1630 }
1631
1632 static class SequentialReadTest extends TableTest {
1633 SequentialReadTest(Connection con, TestOptions options, Status status) {
1634 super(con, options, status);
1635 }
1636
1637 @Override
1638 void testRow(final int i) throws IOException {
1639 Get get = new Get(format(i));
1640 for (int family = 0; family < opts.families; family++) {
1641 byte[] familyName = Bytes.toBytes(FAMILY_NAME_BASE + family);
1642 if (opts.addColumns) {
1643 for (int column = 0; column < opts.columns; column++) {
1644 byte [] qualifier = column == 0? COLUMN_ZERO: Bytes.toBytes("" + column);
1645 get.addColumn(familyName, qualifier);
1646 }
1647 } else {
1648 get.addFamily(familyName);
1649 }
1650 }
1651 if (opts.filterAll) {
1652 get.setFilter(new FilterAllFilter());
1653 }
1654 updateValueSize(table.get(get));
1655 }
1656 }
1657
1658 static class SequentialWriteTest extends BufferedMutatorTest {
1659 SequentialWriteTest(Connection con, TestOptions options, Status status) {
1660 super(con, options, status);
1661 }
1662
1663 @Override
1664 void testRow(final int i) throws IOException {
1665 byte[] row = format(i);
1666 Put put = new Put(row);
1667 for (int family = 0; family < opts.families; family++) {
1668 byte[] familyName = Bytes.toBytes(FAMILY_NAME_BASE + family);
1669 for (int column = 0; column < opts.columns; column++) {
1670 byte [] qualifier = column == 0? COLUMN_ZERO: Bytes.toBytes("" + column);
1671 byte[] value = generateData(this.rand, getValueLength(this.rand));
1672 if (opts.useTags) {
1673 byte[] tag = generateData(this.rand, TAG_LENGTH);
1674 Tag[] tags = new Tag[opts.noOfTags];
1675 for (int n = 0; n < opts.noOfTags; n++) {
1676 Tag t = new Tag((byte) n, tag);
1677 tags[n] = t;
1678 }
1679 KeyValue kv = new KeyValue(row, familyName, qualifier, HConstants.LATEST_TIMESTAMP,
1680 value, tags);
1681 put.add(kv);
1682 updateValueSize(kv.getValueLength());
1683 } else {
1684 put.add(familyName, qualifier, value);
1685 updateValueSize(value.length);
1686 }
1687 }
1688 }
1689 put.setDurability(opts.writeToWAL ? Durability.SYNC_WAL : Durability.SKIP_WAL);
1690 mutator.mutate(put);
1691 if (opts.autoFlush) {
1692 mutator.flush();
1693 }
1694 }
1695 }
1696
1697 static class FilteredScanTest extends TableTest {
1698 protected static final Log LOG = LogFactory.getLog(FilteredScanTest.class.getName());
1699
1700 FilteredScanTest(Connection con, TestOptions options, Status status) {
1701 super(con, options, status);
1702 }
1703
1704 @Override
1705 void testRow(int i) throws IOException {
1706 byte[] value = generateData(this.rand, getValueLength(this.rand));
1707 Scan scan = constructScan(value);
1708 ResultScanner scanner = null;
1709 try {
1710 scanner = this.table.getScanner(scan);
1711 for (Result r = null; (r = scanner.next()) != null;) {
1712 updateValueSize(r);
1713 }
1714 } finally {
1715 if (scanner != null) scanner.close();
1716 }
1717 }
1718
1719 protected Scan constructScan(byte[] valuePrefix) throws IOException {
1720 FilterList list = new FilterList();
1721 Filter filter = new SingleColumnValueFilter(FAMILY_ZERO, COLUMN_ZERO,
1722 CompareFilter.CompareOp.EQUAL, new BinaryComparator(valuePrefix));
1723 list.addFilter(filter);
1724 if (opts.filterAll) {
1725 list.addFilter(new FilterAllFilter());
1726 }
1727 Scan scan = new Scan();
1728 scan.setCaching(opts.caching);
1729 if (opts.addColumns) {
1730 for (int column = 0; column < opts.columns; column++) {
1731 byte [] qualifier = column == 0? COLUMN_ZERO: Bytes.toBytes("" + column);
1732 scan.addColumn(FAMILY_ZERO, qualifier);
1733 }
1734 } else {
1735 scan.addFamily(FAMILY_ZERO);
1736 }
1737 scan.setFilter(list);
1738 return scan;
1739 }
1740 }
1741
1742
1743
1744
1745
1746
1747
1748 private static String calculateMbps(int rows, long timeMs, final int valueSize, int families,
1749 int columns) {
1750 BigDecimal rowSize = BigDecimal.valueOf(ROW_LENGTH +
1751 ((valueSize + (FAMILY_NAME_BASE.length()+1) + COLUMN_ZERO.length) * columns) * families);
1752 BigDecimal mbps = BigDecimal.valueOf(rows).multiply(rowSize, CXT)
1753 .divide(BigDecimal.valueOf(timeMs), CXT).multiply(MS_PER_SEC, CXT)
1754 .divide(BYTES_PER_MB, CXT);
1755 return FMT.format(mbps) + " MB/s";
1756 }
1757
1758
1759
1760
1761
1762
1763
1764 public static byte [] format(final int number) {
1765 byte [] b = new byte[ROW_LENGTH];
1766 int d = Math.abs(number);
1767 for (int i = b.length - 1; i >= 0; i--) {
1768 b[i] = (byte)((d % 10) + '0');
1769 d /= 10;
1770 }
1771 return b;
1772 }
1773
1774
1775
1776
1777
1778
1779
1780 public static byte[] generateData(final Random r, int length) {
1781 byte [] b = new byte [length];
1782 int i;
1783
1784 for(i = 0; i < (length-8); i += 8) {
1785 b[i] = (byte) (65 + r.nextInt(26));
1786 b[i+1] = b[i];
1787 b[i+2] = b[i];
1788 b[i+3] = b[i];
1789 b[i+4] = b[i];
1790 b[i+5] = b[i];
1791 b[i+6] = b[i];
1792 b[i+7] = b[i];
1793 }
1794
1795 byte a = (byte) (65 + r.nextInt(26));
1796 for(; i < length; i++) {
1797 b[i] = a;
1798 }
1799 return b;
1800 }
1801
1802
1803
1804
1805
1806 @Deprecated
1807 public static byte[] generateValue(final Random r) {
1808 return generateData(r, DEFAULT_VALUE_LENGTH);
1809 }
1810
1811 static byte [] getRandomRow(final Random random, final int totalRows) {
1812 return format(random.nextInt(Integer.MAX_VALUE) % totalRows);
1813 }
1814
1815 static RunResult runOneClient(final Class<? extends Test> cmd, Configuration conf, Connection con,
1816 TestOptions opts, final Status status)
1817 throws IOException, InterruptedException {
1818 status.setStatus("Start " + cmd + " at offset " + opts.startRow + " for " +
1819 opts.perClientRunRows + " rows");
1820 long totalElapsedTime;
1821
1822 final Test t;
1823 try {
1824 Constructor<? extends Test> constructor =
1825 cmd.getDeclaredConstructor(Connection.class, TestOptions.class, Status.class);
1826 t = constructor.newInstance(con, opts, status);
1827 } catch (NoSuchMethodException e) {
1828 throw new IllegalArgumentException("Invalid command class: " +
1829 cmd.getName() + ". It does not provide a constructor as described by " +
1830 "the javadoc comment. Available constructors are: " +
1831 Arrays.toString(cmd.getConstructors()));
1832 } catch (Exception e) {
1833 throw new IllegalStateException("Failed to construct command class", e);
1834 }
1835 totalElapsedTime = t.test();
1836
1837 status.setStatus("Finished " + cmd + " in " + totalElapsedTime +
1838 "ms at offset " + opts.startRow + " for " + opts.perClientRunRows + " rows" +
1839 " (" + calculateMbps((int)(opts.perClientRunRows * opts.sampleRate), totalElapsedTime,
1840 getAverageValueLength(opts), opts.families, opts.columns) + ")");
1841
1842 return new RunResult(totalElapsedTime, t.getLatency());
1843 }
1844
1845 private static int getAverageValueLength(final TestOptions opts) {
1846 return opts.valueRandom? opts.valueSize/2: opts.valueSize;
1847 }
1848
1849 private void runTest(final Class<? extends Test> cmd, TestOptions opts) throws IOException,
1850 InterruptedException, ClassNotFoundException {
1851
1852
1853 LOG.info(cmd.getSimpleName() + " test run options=" + MAPPER.writeValueAsString(opts));
1854 try(Connection conn = ConnectionFactory.createConnection(getConf());
1855 Admin admin = conn.getAdmin()) {
1856 checkTable(admin, opts);
1857 }
1858 if (opts.nomapred) {
1859 doLocalClients(opts, getConf());
1860 } else {
1861 doMapReduce(opts, getConf());
1862 }
1863 }
1864
1865 protected void printUsage() {
1866 printUsage(this.getClass().getName(), null);
1867 }
1868
1869 protected static void printUsage(final String message) {
1870 printUsage(PerformanceEvaluation.class.getName(), message);
1871 }
1872
1873 protected static void printUsageAndExit(final String message, final int exitCode) {
1874 printUsage(message);
1875 System.exit(exitCode);
1876 }
1877
1878 protected static void printUsage(final String className, final String message) {
1879 if (message != null && message.length() > 0) {
1880 System.err.println(message);
1881 }
1882 System.err.println("Usage: java " + className + " \\");
1883 System.err.println(" <OPTIONS> [-D<property=value>]* <command> <nclients>");
1884 System.err.println();
1885 System.err.println("Options:");
1886 System.err.println(" nomapred Run multiple clients using threads " +
1887 "(rather than use mapreduce)");
1888 System.err.println(" rows Rows each client runs. Default: One million");
1889 System.err.println(" size Total size in GiB. Mutually exclusive with --rows. " +
1890 "Default: 1.0.");
1891 System.err.println(" sampleRate Execute test on a sample of total " +
1892 "rows. Only supported by randomRead. Default: 1.0");
1893 System.err.println(" traceRate Enable HTrace spans. Initiate tracing every N rows. " +
1894 "Default: 0");
1895 System.err.println(" table Alternate table name. Default: 'TestTable'");
1896 System.err.println(" multiGet If >0, when doing RandomRead, perform multiple gets " +
1897 "instead of single gets. Default: 0");
1898 System.err.println(" compress Compression type to use (GZ, LZO, ...). Default: 'NONE'");
1899 System.err.println(" flushCommits Used to determine if the test should flush the table. " +
1900 "Default: false");
1901 System.err.println(" writeToWAL Set writeToWAL on puts. Default: True");
1902 System.err.println(" autoFlush Set autoFlush on htable. Default: False");
1903 System.err.println(" oneCon all the threads share the same connection. Default: False");
1904 System.err.println(" presplit Create presplit table. Recommended for accurate perf " +
1905 "analysis (see guide). Default: disabled");
1906 System.err.println(" inmemory Tries to keep the HFiles of the CF " +
1907 "inmemory as far as possible. Not guaranteed that reads are always served " +
1908 "from memory. Default: false");
1909 System.err.println(" usetags Writes tags along with KVs. Use with HFile V3. " +
1910 "Default: false");
1911 System.err.println(" numoftags Specify the no of tags that would be needed. " +
1912 "This works only if usetags is true.");
1913 System.err.println(" filterAll Helps to filter out all the rows on the server side"
1914 + " there by not returning any thing back to the client. Helps to check the server side"
1915 + " performance. Uses FilterAllFilter internally. ");
1916 System.err.println(" latency Set to report operation latencies. Default: False");
1917 System.err.println(" bloomFilter Bloom filter type, one of " + Arrays.toString(BloomType.values()));
1918 System.err.println(" valueSize Pass value size to use: Default: 1024");
1919 System.err.println(" valueRandom Set if we should vary value size between 0 and " +
1920 "'valueSize'; set on read for stats on size: Default: Not set.");
1921 System.err.println(" valueZipf Set if we should vary value size between 0 and " +
1922 "'valueSize' in zipf form: Default: Not set.");
1923 System.err.println(" period Report every 'period' rows: " +
1924 "Default: opts.perClientRunRows / 10");
1925 System.err.println(" multiGet Batch gets together into groups of N. Only supported " +
1926 "by randomRead. Default: disabled");
1927 System.err.println(" addColumns Adds columns to scans/gets explicitly. Default: true");
1928 System.err.println(" replicas Enable region replica testing. Defaults: 1.");
1929 System.err.println(" splitPolicy Specify a custom RegionSplitPolicy for the table.");
1930 System.err.println(" randomSleep Do a random sleep before each get between 0 and entered value. Defaults: 0");
1931 System.err.println(" columns Columns to write per row. Default: 1");
1932 System.err.println(" families Specify number of column families for the table. Default: 1");
1933 System.err.println(" caching Scan caching to use. Default: 30");
1934 System.err.println(" bufferSize Set the value of client side buffering. Default: 2MB");
1935 System.err.println();
1936 System.err.println(" Note: -D properties will be applied to the conf used. ");
1937 System.err.println(" For example: ");
1938 System.err.println(" -Dmapreduce.output.fileoutputformat.compress=true");
1939 System.err.println(" -Dmapreduce.task.timeout=60000");
1940 System.err.println();
1941 System.err.println("Command:");
1942 for (CmdDescriptor command : COMMANDS.values()) {
1943 System.err.println(String.format(" %-15s %s", command.getName(), command.getDescription()));
1944 }
1945 System.err.println();
1946 System.err.println("Args:");
1947 System.err.println(" nclients Integer. Required. Total number of " +
1948 "clients (and HRegionServers)");
1949 System.err.println(" running: 1 <= value <= 500");
1950 System.err.println("Examples:");
1951 System.err.println(" To run a single client doing the default 1M sequentialWrites:");
1952 System.err.println(" $ bin/hbase " + className + " sequentialWrite 1");
1953 System.err.println(" To run 10 clients doing increments over ten rows:");
1954 System.err.println(" $ bin/hbase " + className + " --rows=10 --nomapred increment 10");
1955 }
1956
1957
1958
1959
1960
1961
1962
1963 static TestOptions parseOpts(Queue<String> args) {
1964 TestOptions opts = new TestOptions();
1965
1966 String cmd = null;
1967 while ((cmd = args.poll()) != null) {
1968 if (cmd.equals("-h") || cmd.startsWith("--h")) {
1969
1970 args.add(cmd);
1971 break;
1972 }
1973
1974 final String nmr = "--nomapred";
1975 if (cmd.startsWith(nmr)) {
1976 opts.nomapred = true;
1977 continue;
1978 }
1979
1980 final String rows = "--rows=";
1981 if (cmd.startsWith(rows)) {
1982 opts.perClientRunRows = Integer.parseInt(cmd.substring(rows.length()));
1983 continue;
1984 }
1985
1986 final String sampleRate = "--sampleRate=";
1987 if (cmd.startsWith(sampleRate)) {
1988 opts.sampleRate = Float.parseFloat(cmd.substring(sampleRate.length()));
1989 continue;
1990 }
1991
1992 final String table = "--table=";
1993 if (cmd.startsWith(table)) {
1994 opts.tableName = cmd.substring(table.length());
1995 continue;
1996 }
1997
1998 final String startRow = "--startRow=";
1999 if (cmd.startsWith(startRow)) {
2000 opts.startRow = Integer.parseInt(cmd.substring(startRow.length()));
2001 continue;
2002 }
2003
2004 final String compress = "--compress=";
2005 if (cmd.startsWith(compress)) {
2006 opts.compression = Compression.Algorithm.valueOf(cmd.substring(compress.length()));
2007 continue;
2008 }
2009
2010 final String traceRate = "--traceRate=";
2011 if (cmd.startsWith(traceRate)) {
2012 opts.traceRate = Double.parseDouble(cmd.substring(traceRate.length()));
2013 continue;
2014 }
2015
2016 final String blockEncoding = "--blockEncoding=";
2017 if (cmd.startsWith(blockEncoding)) {
2018 opts.blockEncoding = DataBlockEncoding.valueOf(cmd.substring(blockEncoding.length()));
2019 continue;
2020 }
2021
2022 final String flushCommits = "--flushCommits=";
2023 if (cmd.startsWith(flushCommits)) {
2024 opts.flushCommits = Boolean.parseBoolean(cmd.substring(flushCommits.length()));
2025 continue;
2026 }
2027
2028 final String writeToWAL = "--writeToWAL=";
2029 if (cmd.startsWith(writeToWAL)) {
2030 opts.writeToWAL = Boolean.parseBoolean(cmd.substring(writeToWAL.length()));
2031 continue;
2032 }
2033
2034 final String presplit = "--presplit=";
2035 if (cmd.startsWith(presplit)) {
2036 opts.presplitRegions = Integer.parseInt(cmd.substring(presplit.length()));
2037 continue;
2038 }
2039
2040 final String inMemory = "--inmemory=";
2041 if (cmd.startsWith(inMemory)) {
2042 opts.inMemoryCF = Boolean.parseBoolean(cmd.substring(inMemory.length()));
2043 continue;
2044 }
2045
2046 final String autoFlush = "--autoFlush=";
2047 if (cmd.startsWith(autoFlush)) {
2048 opts.autoFlush = Boolean.parseBoolean(cmd.substring(autoFlush.length()));
2049 continue;
2050 }
2051
2052 final String onceCon = "--oneCon=";
2053 if (cmd.startsWith(onceCon)) {
2054 opts.oneCon = Boolean.parseBoolean(cmd.substring(onceCon.length()));
2055 continue;
2056 }
2057
2058 final String latency = "--latency";
2059 if (cmd.startsWith(latency)) {
2060 opts.reportLatency = true;
2061 continue;
2062 }
2063
2064 final String multiGet = "--multiGet=";
2065 if (cmd.startsWith(multiGet)) {
2066 opts.multiGet = Integer.parseInt(cmd.substring(multiGet.length()));
2067 continue;
2068 }
2069
2070 final String useTags = "--usetags=";
2071 if (cmd.startsWith(useTags)) {
2072 opts.useTags = Boolean.parseBoolean(cmd.substring(useTags.length()));
2073 continue;
2074 }
2075
2076 final String noOfTags = "--numoftags=";
2077 if (cmd.startsWith(noOfTags)) {
2078 opts.noOfTags = Integer.parseInt(cmd.substring(noOfTags.length()));
2079 continue;
2080 }
2081
2082 final String replicas = "--replicas=";
2083 if (cmd.startsWith(replicas)) {
2084 opts.replicas = Integer.parseInt(cmd.substring(replicas.length()));
2085 continue;
2086 }
2087
2088 final String filterOutAll = "--filterAll";
2089 if (cmd.startsWith(filterOutAll)) {
2090 opts.filterAll = true;
2091 continue;
2092 }
2093
2094 final String size = "--size=";
2095 if (cmd.startsWith(size)) {
2096 opts.size = Float.parseFloat(cmd.substring(size.length()));
2097 continue;
2098 }
2099
2100 final String splitPolicy = "--splitPolicy=";
2101 if (cmd.startsWith(splitPolicy)) {
2102 opts.splitPolicy = cmd.substring(splitPolicy.length());
2103 continue;
2104 }
2105
2106 final String randomSleep = "--randomSleep=";
2107 if (cmd.startsWith(randomSleep)) {
2108 opts.randomSleep = Integer.parseInt(cmd.substring(randomSleep.length()));
2109 continue;
2110 }
2111
2112 final String bloomFilter = "--bloomFilter=";
2113 if (cmd.startsWith(bloomFilter)) {
2114 opts.bloomType = BloomType.valueOf(cmd.substring(bloomFilter.length()));
2115 continue;
2116 }
2117
2118 final String valueSize = "--valueSize=";
2119 if (cmd.startsWith(valueSize)) {
2120 opts.valueSize = Integer.parseInt(cmd.substring(valueSize.length()));
2121 continue;
2122 }
2123
2124 final String valueRandom = "--valueRandom";
2125 if (cmd.startsWith(valueRandom)) {
2126 opts.valueRandom = true;
2127 if (opts.valueZipf) {
2128 throw new IllegalStateException("Either valueZipf or valueRandom but not both");
2129 }
2130 continue;
2131 }
2132
2133 final String valueZipf = "--valueZipf";
2134 if (cmd.startsWith(valueZipf)) {
2135 opts.valueZipf = true;
2136 if (opts.valueRandom) {
2137 throw new IllegalStateException("Either valueZipf or valueRandom but not both");
2138 }
2139 continue;
2140 }
2141
2142 final String period = "--period=";
2143 if (cmd.startsWith(period)) {
2144 opts.period = Integer.parseInt(cmd.substring(period.length()));
2145 continue;
2146 }
2147
2148 final String addColumns = "--addColumns=";
2149 if (cmd.startsWith(addColumns)) {
2150 opts.addColumns = Boolean.parseBoolean(cmd.substring(addColumns.length()));
2151 continue;
2152 }
2153
2154 final String columns = "--columns=";
2155 if (cmd.startsWith(columns)) {
2156 opts.columns = Integer.parseInt(cmd.substring(columns.length()));
2157 continue;
2158 }
2159
2160 final String families = "--families=";
2161 if (cmd.startsWith(families)) {
2162 opts.families = Integer.parseInt(cmd.substring(families.length()));
2163 continue;
2164 }
2165
2166 final String caching = "--caching=";
2167 if (cmd.startsWith(caching)) {
2168 opts.caching = Integer.parseInt(cmd.substring(caching.length()));
2169 continue;
2170 }
2171
2172 final String bufferSize = "--bufferSize=";
2173 if (cmd.startsWith(bufferSize)) {
2174 opts.bufferSize = Long.parseLong(cmd.substring(bufferSize.length()));
2175 continue;
2176 }
2177
2178 if (isCommandClass(cmd)) {
2179 opts.cmdName = cmd;
2180 opts.numClientThreads = Integer.parseInt(args.remove());
2181 int rowsPerGB = getRowsPerGB(opts);
2182 if (opts.size != DEFAULT_OPTS.size &&
2183 opts.perClientRunRows != DEFAULT_OPTS.perClientRunRows) {
2184 throw new IllegalArgumentException(rows + " and " + size + " are mutually exclusive arguments.");
2185 }
2186 if (opts.size != DEFAULT_OPTS.size) {
2187
2188 opts.totalRows = (int) opts.size * rowsPerGB;
2189 opts.perClientRunRows = opts.totalRows / opts.numClientThreads;
2190 } else {
2191 opts.totalRows = opts.perClientRunRows * opts.numClientThreads;
2192 opts.size = opts.totalRows / rowsPerGB;
2193 }
2194 break;
2195 } else {
2196 printUsageAndExit("ERROR: Unrecognized option/command: " + cmd, -1);
2197 }
2198
2199
2200 System.err.println("Error: Wrong option or command: " + cmd);
2201 args.add(cmd);
2202 break;
2203 }
2204 return opts;
2205 }
2206
2207 static int getRowsPerGB(final TestOptions opts) {
2208 return ONE_GB / ((opts.valueRandom? opts.valueSize/2: opts.valueSize) * opts.getColumns() *
2209 opts.getFamilies());
2210 }
2211
2212 @Override
2213 public int run(String[] args) throws Exception {
2214
2215
2216 int errCode = -1;
2217 if (args.length < 1) {
2218 printUsage();
2219 return errCode;
2220 }
2221
2222 try {
2223 LinkedList<String> argv = new LinkedList<String>();
2224 argv.addAll(Arrays.asList(args));
2225 TestOptions opts = parseOpts(argv);
2226
2227
2228 if (!argv.isEmpty()) {
2229 errCode = 0;
2230 printUsage();
2231 return errCode;
2232 }
2233
2234
2235 if (opts.numClientThreads <= 0) {
2236 throw new IllegalArgumentException("Number of clients must be > 0");
2237 }
2238
2239
2240 if (opts.cmdName == null) {
2241 printUsage();
2242 return errCode;
2243 }
2244
2245 Class<? extends Test> cmdClass = determineCommandClass(opts.cmdName);
2246 if (cmdClass != null) {
2247 runTest(cmdClass, opts);
2248 errCode = 0;
2249 }
2250
2251 } catch (Exception e) {
2252 e.printStackTrace();
2253 }
2254
2255 return errCode;
2256 }
2257
2258 private static boolean isCommandClass(String cmd) {
2259 return COMMANDS.containsKey(cmd);
2260 }
2261
2262 private static Class<? extends Test> determineCommandClass(String cmd) {
2263 CmdDescriptor descriptor = COMMANDS.get(cmd);
2264 return descriptor != null ? descriptor.getCmdClass() : null;
2265 }
2266
2267 public static void main(final String[] args) throws Exception {
2268 int res = ToolRunner.run(new PerformanceEvaluation(HBaseConfiguration.create()), args);
2269 System.exit(res);
2270 }
2271 }