View Javadoc

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