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