001/** 002 * 003 * Licensed to the Apache Software Foundation (ASF) under one 004 * or more contributor license agreements. See the NOTICE file 005 * distributed with this work for additional information 006 * regarding copyright ownership. The ASF licenses this file 007 * to you under the Apache License, Version 2.0 (the 008 * "License"); you may not use this file except in compliance 009 * with the License. You may obtain a copy of the License at 010 * 011 * http://www.apache.org/licenses/LICENSE-2.0 012 * 013 * Unless required by applicable law or agreed to in writing, software 014 * distributed under the License is distributed on an "AS IS" BASIS, 015 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 016 * See the License for the specific language governing permissions and 017 * limitations under the License. 018 */ 019package org.apache.hadoop.hbase; 020 021import com.codahale.metrics.Histogram; 022import com.codahale.metrics.UniformReservoir; 023import com.fasterxml.jackson.databind.MapperFeature; 024import com.fasterxml.jackson.databind.ObjectMapper; 025 026import java.io.IOException; 027import java.io.PrintStream; 028import java.lang.reflect.Constructor; 029import java.math.BigDecimal; 030import java.math.MathContext; 031import java.text.DecimalFormat; 032import java.text.SimpleDateFormat; 033import java.util.ArrayList; 034import java.util.Arrays; 035import java.util.Date; 036import java.util.LinkedList; 037import java.util.Locale; 038import java.util.Map; 039import java.util.NoSuchElementException; 040import java.util.Queue; 041import java.util.Random; 042import java.util.TreeMap; 043import java.util.concurrent.Callable; 044import java.util.concurrent.ExecutionException; 045import java.util.concurrent.ExecutorService; 046import java.util.concurrent.Executors; 047import java.util.concurrent.Future; 048 049import org.apache.commons.lang3.StringUtils; 050import org.apache.hadoop.conf.Configuration; 051import org.apache.hadoop.conf.Configured; 052import org.apache.hadoop.fs.FileSystem; 053import org.apache.hadoop.fs.Path; 054import org.apache.hadoop.hbase.client.Admin; 055import org.apache.hadoop.hbase.client.Append; 056import org.apache.hadoop.hbase.client.AsyncConnection; 057import org.apache.hadoop.hbase.client.AsyncTable; 058import org.apache.hadoop.hbase.client.BufferedMutator; 059import org.apache.hadoop.hbase.client.BufferedMutatorParams; 060import org.apache.hadoop.hbase.client.Connection; 061import org.apache.hadoop.hbase.client.ConnectionFactory; 062import org.apache.hadoop.hbase.client.Consistency; 063import org.apache.hadoop.hbase.client.Delete; 064import org.apache.hadoop.hbase.client.Durability; 065import org.apache.hadoop.hbase.client.Get; 066import org.apache.hadoop.hbase.client.Increment; 067import org.apache.hadoop.hbase.client.Put; 068import org.apache.hadoop.hbase.client.Result; 069import org.apache.hadoop.hbase.client.ResultScanner; 070import org.apache.hadoop.hbase.client.RowMutations; 071import org.apache.hadoop.hbase.client.Scan; 072import org.apache.hadoop.hbase.client.Table; 073import org.apache.hadoop.hbase.client.metrics.ScanMetrics; 074import org.apache.hadoop.hbase.filter.BinaryComparator; 075import org.apache.hadoop.hbase.filter.Filter; 076import org.apache.hadoop.hbase.filter.FilterAllFilter; 077import org.apache.hadoop.hbase.filter.FilterList; 078import org.apache.hadoop.hbase.filter.PageFilter; 079import org.apache.hadoop.hbase.filter.SingleColumnValueFilter; 080import org.apache.hadoop.hbase.filter.WhileMatchFilter; 081import org.apache.hadoop.hbase.io.compress.Compression; 082import org.apache.hadoop.hbase.io.encoding.DataBlockEncoding; 083import org.apache.hadoop.hbase.io.hfile.RandomDistribution; 084import org.apache.hadoop.hbase.mapreduce.TableMapReduceUtil; 085import org.apache.hadoop.hbase.regionserver.BloomType; 086import org.apache.hadoop.hbase.regionserver.CompactingMemStore; 087import org.apache.hadoop.hbase.trace.HBaseHTraceConfiguration; 088import org.apache.hadoop.hbase.trace.SpanReceiverHost; 089import org.apache.hadoop.hbase.trace.TraceUtil; 090import org.apache.hadoop.hbase.util.ByteArrayHashKey; 091import org.apache.hadoop.hbase.util.Bytes; 092import org.apache.hadoop.hbase.util.Hash; 093import org.apache.hadoop.hbase.util.MurmurHash; 094import org.apache.hadoop.hbase.util.Pair; 095import org.apache.hadoop.hbase.util.YammerHistogramUtils; 096import org.apache.hadoop.io.LongWritable; 097import org.apache.hadoop.io.Text; 098import org.apache.hadoop.mapreduce.Job; 099import org.apache.hadoop.mapreduce.Mapper; 100import org.apache.hadoop.mapreduce.lib.input.NLineInputFormat; 101import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat; 102import org.apache.hadoop.mapreduce.lib.reduce.LongSumReducer; 103import org.apache.hadoop.util.Tool; 104import org.apache.hadoop.util.ToolRunner; 105import org.apache.htrace.core.ProbabilitySampler; 106import org.apache.htrace.core.Sampler; 107import org.apache.htrace.core.TraceScope; 108import org.apache.yetus.audience.InterfaceAudience; 109import org.slf4j.Logger; 110import org.slf4j.LoggerFactory; 111import org.apache.hbase.thirdparty.com.google.common.base.MoreObjects; 112import org.apache.hbase.thirdparty.com.google.common.util.concurrent.ThreadFactoryBuilder; 113 114/** 115 * Script used evaluating HBase performance and scalability. Runs a HBase 116 * client that steps through one of a set of hardcoded tests or 'experiments' 117 * (e.g. a random reads test, a random writes test, etc.). Pass on the 118 * command-line which test to run and how many clients are participating in 119 * this experiment. Run {@code PerformanceEvaluation --help} to obtain usage. 120 * 121 * <p>This class sets up and runs the evaluation programs described in 122 * Section 7, <i>Performance Evaluation</i>, of the <a 123 * href="http://labs.google.com/papers/bigtable.html">Bigtable</a> 124 * paper, pages 8-10. 125 * 126 * <p>By default, runs as a mapreduce job where each mapper runs a single test 127 * client. Can also run as a non-mapreduce, multithreaded application by 128 * specifying {@code --nomapred}. Each client does about 1GB of data, unless 129 * specified otherwise. 130 */ 131@InterfaceAudience.LimitedPrivate(HBaseInterfaceAudience.TOOLS) 132public class PerformanceEvaluation extends Configured implements Tool { 133 static final String RANDOM_SEEK_SCAN = "randomSeekScan"; 134 static final String RANDOM_READ = "randomRead"; 135 private static final Logger LOG = LoggerFactory.getLogger(PerformanceEvaluation.class.getName()); 136 private static final ObjectMapper MAPPER = new ObjectMapper(); 137 static { 138 MAPPER.configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true); 139 } 140 141 public static final String TABLE_NAME = "TestTable"; 142 public static final String FAMILY_NAME_BASE = "info"; 143 public static final byte[] FAMILY_ZERO = Bytes.toBytes("info0"); 144 public static final byte[] COLUMN_ZERO = Bytes.toBytes("" + 0); 145 public static final int DEFAULT_VALUE_LENGTH = 1000; 146 public static final int ROW_LENGTH = 26; 147 148 private static final int ONE_GB = 1024 * 1024 * 1000; 149 private static final int DEFAULT_ROWS_PER_GB = ONE_GB / DEFAULT_VALUE_LENGTH; 150 // TODO : should we make this configurable 151 private static final int TAG_LENGTH = 256; 152 private static final DecimalFormat FMT = new DecimalFormat("0.##"); 153 private static final MathContext CXT = MathContext.DECIMAL64; 154 private static final BigDecimal MS_PER_SEC = BigDecimal.valueOf(1000); 155 private static final BigDecimal BYTES_PER_MB = BigDecimal.valueOf(1024 * 1024); 156 private static final TestOptions DEFAULT_OPTS = new TestOptions(); 157 158 private static Map<String, CmdDescriptor> COMMANDS = new TreeMap<>(); 159 private static final Path PERF_EVAL_DIR = new Path("performance_evaluation"); 160 161 static { 162 addCommandDescriptor(AsyncRandomReadTest.class, "asyncRandomRead", 163 "Run async random read test"); 164 addCommandDescriptor(AsyncRandomWriteTest.class, "asyncRandomWrite", 165 "Run async random write test"); 166 addCommandDescriptor(AsyncSequentialReadTest.class, "asyncSequentialRead", 167 "Run async sequential read test"); 168 addCommandDescriptor(AsyncSequentialWriteTest.class, "asyncSequentialWrite", 169 "Run async sequential write test"); 170 addCommandDescriptor(AsyncScanTest.class, "asyncScan", 171 "Run async scan test (read every row)"); 172 addCommandDescriptor(RandomReadTest.class, RANDOM_READ, 173 "Run random read test"); 174 addCommandDescriptor(RandomSeekScanTest.class, RANDOM_SEEK_SCAN, 175 "Run random seek and scan 100 test"); 176 addCommandDescriptor(RandomScanWithRange10Test.class, "scanRange10", 177 "Run random seek scan with both start and stop row (max 10 rows)"); 178 addCommandDescriptor(RandomScanWithRange100Test.class, "scanRange100", 179 "Run random seek scan with both start and stop row (max 100 rows)"); 180 addCommandDescriptor(RandomScanWithRange1000Test.class, "scanRange1000", 181 "Run random seek scan with both start and stop row (max 1000 rows)"); 182 addCommandDescriptor(RandomScanWithRange10000Test.class, "scanRange10000", 183 "Run random seek scan with both start and stop row (max 10000 rows)"); 184 addCommandDescriptor(RandomWriteTest.class, "randomWrite", 185 "Run random write test"); 186 addCommandDescriptor(SequentialReadTest.class, "sequentialRead", 187 "Run sequential read test"); 188 addCommandDescriptor(SequentialWriteTest.class, "sequentialWrite", 189 "Run sequential write test"); 190 addCommandDescriptor(ScanTest.class, "scan", 191 "Run scan test (read every row)"); 192 addCommandDescriptor(FilteredScanTest.class, "filterScan", 193 "Run scan test using a filter to find a specific row based on it's value " + 194 "(make sure to use --rows=20)"); 195 addCommandDescriptor(IncrementTest.class, "increment", 196 "Increment on each row; clients overlap on keyspace so some concurrent operations"); 197 addCommandDescriptor(AppendTest.class, "append", 198 "Append on each row; clients overlap on keyspace so some concurrent operations"); 199 addCommandDescriptor(CheckAndMutateTest.class, "checkAndMutate", 200 "CheckAndMutate on each row; clients overlap on keyspace so some concurrent operations"); 201 addCommandDescriptor(CheckAndPutTest.class, "checkAndPut", 202 "CheckAndPut on each row; clients overlap on keyspace so some concurrent operations"); 203 addCommandDescriptor(CheckAndDeleteTest.class, "checkAndDelete", 204 "CheckAndDelete on each row; clients overlap on keyspace so some concurrent operations"); 205 } 206 207 /** 208 * Enum for map metrics. Keep it out here rather than inside in the Map 209 * inner-class so we can find associated properties. 210 */ 211 protected static enum Counter { 212 /** elapsed time */ 213 ELAPSED_TIME, 214 /** number of rows */ 215 ROWS 216 } 217 218 protected static class RunResult implements Comparable<RunResult> { 219 public RunResult(long duration, Histogram hist) { 220 this.duration = duration; 221 this.hist = hist; 222 } 223 224 public final long duration; 225 public final Histogram hist; 226 227 @Override 228 public String toString() { 229 return Long.toString(duration); 230 } 231 232 @Override public int compareTo(RunResult o) { 233 return Long.compare(this.duration, o.duration); 234 } 235 } 236 237 /** 238 * Constructor 239 * @param conf Configuration object 240 */ 241 public PerformanceEvaluation(final Configuration conf) { 242 super(conf); 243 } 244 245 protected static void addCommandDescriptor(Class<? extends TestBase> cmdClass, 246 String name, String description) { 247 CmdDescriptor cmdDescriptor = new CmdDescriptor(cmdClass, name, description); 248 COMMANDS.put(name, cmdDescriptor); 249 } 250 251 /** 252 * Implementations can have their status set. 253 */ 254 interface Status { 255 /** 256 * Sets status 257 * @param msg status message 258 * @throws IOException 259 */ 260 void setStatus(final String msg) throws IOException; 261 } 262 263 /** 264 * MapReduce job that runs a performance evaluation client in each map task. 265 */ 266 public static class EvaluationMapTask 267 extends Mapper<LongWritable, Text, LongWritable, LongWritable> { 268 269 /** configuration parameter name that contains the command */ 270 public final static String CMD_KEY = "EvaluationMapTask.command"; 271 /** configuration parameter name that contains the PE impl */ 272 public static final String PE_KEY = "EvaluationMapTask.performanceEvalImpl"; 273 274 private Class<? extends Test> cmd; 275 276 @Override 277 protected void setup(Context context) throws IOException, InterruptedException { 278 this.cmd = forName(context.getConfiguration().get(CMD_KEY), Test.class); 279 280 // this is required so that extensions of PE are instantiated within the 281 // map reduce task... 282 Class<? extends PerformanceEvaluation> peClass = 283 forName(context.getConfiguration().get(PE_KEY), PerformanceEvaluation.class); 284 try { 285 peClass.getConstructor(Configuration.class).newInstance(context.getConfiguration()); 286 } catch (Exception e) { 287 throw new IllegalStateException("Could not instantiate PE instance", e); 288 } 289 } 290 291 private <Type> Class<? extends Type> forName(String className, Class<Type> type) { 292 try { 293 return Class.forName(className).asSubclass(type); 294 } catch (ClassNotFoundException e) { 295 throw new IllegalStateException("Could not find class for name: " + className, e); 296 } 297 } 298 299 @Override 300 protected void map(LongWritable key, Text value, final Context context) 301 throws IOException, InterruptedException { 302 303 Status status = new Status() { 304 @Override 305 public void setStatus(String msg) { 306 context.setStatus(msg); 307 } 308 }; 309 310 ObjectMapper mapper = new ObjectMapper(); 311 TestOptions opts = mapper.readValue(value.toString(), TestOptions.class); 312 Configuration conf = HBaseConfiguration.create(context.getConfiguration()); 313 final Connection con = ConnectionFactory.createConnection(conf); 314 AsyncConnection asyncCon = null; 315 try { 316 asyncCon = ConnectionFactory.createAsyncConnection(conf).get(); 317 } catch (ExecutionException e) { 318 throw new IOException(e); 319 } 320 321 // Evaluation task 322 RunResult result = PerformanceEvaluation.runOneClient(this.cmd, conf, con, asyncCon, opts, status); 323 // Collect how much time the thing took. Report as map output and 324 // to the ELAPSED_TIME counter. 325 context.getCounter(Counter.ELAPSED_TIME).increment(result.duration); 326 context.getCounter(Counter.ROWS).increment(opts.perClientRunRows); 327 context.write(new LongWritable(opts.startRow), new LongWritable(result.duration)); 328 context.progress(); 329 } 330 } 331 332 /* 333 * If table does not already exist, create. Also create a table when 334 * {@code opts.presplitRegions} is specified or when the existing table's 335 * region replica count doesn't match {@code opts.replicas}. 336 */ 337 static boolean checkTable(Admin admin, TestOptions opts) throws IOException { 338 TableName tableName = TableName.valueOf(opts.tableName); 339 boolean needsDelete = false, exists = admin.tableExists(tableName); 340 boolean isReadCmd = opts.cmdName.toLowerCase(Locale.ROOT).contains("read") 341 || opts.cmdName.toLowerCase(Locale.ROOT).contains("scan"); 342 if (!exists && isReadCmd) { 343 throw new IllegalStateException( 344 "Must specify an existing table for read commands. Run a write command first."); 345 } 346 HTableDescriptor desc = 347 exists ? admin.getTableDescriptor(TableName.valueOf(opts.tableName)) : null; 348 byte[][] splits = getSplits(opts); 349 350 // recreate the table when user has requested presplit or when existing 351 // {RegionSplitPolicy,replica count} does not match requested, or when the 352 // number of column families does not match requested. 353 if ((exists && opts.presplitRegions != DEFAULT_OPTS.presplitRegions) 354 || (!isReadCmd && desc != null && 355 !StringUtils.equals(desc.getRegionSplitPolicyClassName(), opts.splitPolicy)) 356 || (!isReadCmd && desc != null && desc.getRegionReplication() != opts.replicas) 357 || (desc != null && desc.getColumnFamilyCount() != opts.families)) { 358 needsDelete = true; 359 // wait, why did it delete my table?!? 360 LOG.debug(MoreObjects.toStringHelper("needsDelete") 361 .add("needsDelete", needsDelete) 362 .add("isReadCmd", isReadCmd) 363 .add("exists", exists) 364 .add("desc", desc) 365 .add("presplit", opts.presplitRegions) 366 .add("splitPolicy", opts.splitPolicy) 367 .add("replicas", opts.replicas) 368 .add("families", opts.families) 369 .toString()); 370 } 371 372 // remove an existing table 373 if (needsDelete) { 374 if (admin.isTableEnabled(tableName)) { 375 admin.disableTable(tableName); 376 } 377 admin.deleteTable(tableName); 378 } 379 380 // table creation is necessary 381 if (!exists || needsDelete) { 382 desc = getTableDescriptor(opts); 383 if (splits != null) { 384 if (LOG.isDebugEnabled()) { 385 for (int i = 0; i < splits.length; i++) { 386 LOG.debug(" split " + i + ": " + Bytes.toStringBinary(splits[i])); 387 } 388 } 389 } 390 admin.createTable(desc, splits); 391 LOG.info("Table " + desc + " created"); 392 } 393 return admin.tableExists(tableName); 394 } 395 396 /** 397 * Create an HTableDescriptor from provided TestOptions. 398 */ 399 protected static HTableDescriptor getTableDescriptor(TestOptions opts) { 400 HTableDescriptor tableDesc = new HTableDescriptor(TableName.valueOf(opts.tableName)); 401 for (int family = 0; family < opts.families; family++) { 402 byte[] familyName = Bytes.toBytes(FAMILY_NAME_BASE + family); 403 HColumnDescriptor familyDesc = new HColumnDescriptor(familyName); 404 familyDesc.setDataBlockEncoding(opts.blockEncoding); 405 familyDesc.setCompressionType(opts.compression); 406 familyDesc.setBloomFilterType(opts.bloomType); 407 familyDesc.setBlocksize(opts.blockSize); 408 if (opts.inMemoryCF) { 409 familyDesc.setInMemory(true); 410 } 411 familyDesc.setInMemoryCompaction(opts.inMemoryCompaction); 412 tableDesc.addFamily(familyDesc); 413 } 414 if (opts.replicas != DEFAULT_OPTS.replicas) { 415 tableDesc.setRegionReplication(opts.replicas); 416 } 417 if (opts.splitPolicy != null && !opts.splitPolicy.equals(DEFAULT_OPTS.splitPolicy)) { 418 tableDesc.setRegionSplitPolicyClassName(opts.splitPolicy); 419 } 420 return tableDesc; 421 } 422 423 /** 424 * generates splits based on total number of rows and specified split regions 425 */ 426 protected static byte[][] getSplits(TestOptions opts) { 427 if (opts.presplitRegions == DEFAULT_OPTS.presplitRegions) 428 return null; 429 430 int numSplitPoints = opts.presplitRegions - 1; 431 byte[][] splits = new byte[numSplitPoints][]; 432 int jump = opts.totalRows / opts.presplitRegions; 433 for (int i = 0; i < numSplitPoints; i++) { 434 int rowkey = jump * (1 + i); 435 splits[i] = format(rowkey); 436 } 437 return splits; 438 } 439 440 /* 441 * Run all clients in this vm each to its own thread. 442 */ 443 static RunResult[] doLocalClients(final TestOptions opts, final Configuration conf) 444 throws IOException, InterruptedException, ExecutionException { 445 final Class<? extends TestBase> cmd = determineCommandClass(opts.cmdName); 446 assert cmd != null; 447 @SuppressWarnings("unchecked") 448 Future<RunResult>[] threads = new Future[opts.numClientThreads]; 449 RunResult[] results = new RunResult[opts.numClientThreads]; 450 ExecutorService pool = Executors.newFixedThreadPool(opts.numClientThreads, 451 new ThreadFactoryBuilder().setNameFormat("TestClient-%s").build()); 452 final Connection con = ConnectionFactory.createConnection(conf); 453 final AsyncConnection asyncCon = ConnectionFactory.createAsyncConnection(conf).get(); 454 for (int i = 0; i < threads.length; i++) { 455 final int index = i; 456 threads[i] = pool.submit(new Callable<RunResult>() { 457 @Override 458 public RunResult call() throws Exception { 459 TestOptions threadOpts = new TestOptions(opts); 460 if (threadOpts.startRow == 0) threadOpts.startRow = index * threadOpts.perClientRunRows; 461 RunResult run = runOneClient(cmd, conf, con, asyncCon, threadOpts, new Status() { 462 @Override 463 public void setStatus(final String msg) throws IOException { 464 LOG.info(msg); 465 } 466 }); 467 LOG.info("Finished " + Thread.currentThread().getName() + " in " + run.duration + 468 "ms over " + threadOpts.perClientRunRows + " rows"); 469 return run; 470 } 471 }); 472 } 473 pool.shutdown(); 474 475 for (int i = 0; i < threads.length; i++) { 476 try { 477 results[i] = threads[i].get(); 478 } catch (ExecutionException e) { 479 throw new IOException(e.getCause()); 480 } 481 } 482 final String test = cmd.getSimpleName(); 483 LOG.info("[" + test + "] Summary of timings (ms): " 484 + Arrays.toString(results)); 485 Arrays.sort(results); 486 long total = 0; 487 for (RunResult result : results) { 488 total += result.duration; 489 } 490 LOG.info("[" + test + "]" 491 + "\tMin: " + results[0] + "ms" 492 + "\tMax: " + results[results.length - 1] + "ms" 493 + "\tAvg: " + (total / results.length) + "ms"); 494 495 con.close(); 496 asyncCon.close(); 497 498 return results; 499 } 500 501 /* 502 * Run a mapreduce job. Run as many maps as asked-for clients. 503 * Before we start up the job, write out an input file with instruction 504 * per client regards which row they are to start on. 505 * @param cmd Command to run. 506 * @throws IOException 507 */ 508 static Job doMapReduce(TestOptions opts, final Configuration conf) 509 throws IOException, InterruptedException, ClassNotFoundException { 510 final Class<? extends TestBase> cmd = determineCommandClass(opts.cmdName); 511 assert cmd != null; 512 Path inputDir = writeInputFile(conf, opts); 513 conf.set(EvaluationMapTask.CMD_KEY, cmd.getName()); 514 conf.set(EvaluationMapTask.PE_KEY, PerformanceEvaluation.class.getName()); 515 Job job = Job.getInstance(conf); 516 job.setJarByClass(PerformanceEvaluation.class); 517 job.setJobName("HBase Performance Evaluation - " + opts.cmdName); 518 519 job.setInputFormatClass(NLineInputFormat.class); 520 NLineInputFormat.setInputPaths(job, inputDir); 521 // this is default, but be explicit about it just in case. 522 NLineInputFormat.setNumLinesPerSplit(job, 1); 523 524 job.setOutputKeyClass(LongWritable.class); 525 job.setOutputValueClass(LongWritable.class); 526 527 job.setMapperClass(EvaluationMapTask.class); 528 job.setReducerClass(LongSumReducer.class); 529 530 job.setNumReduceTasks(1); 531 532 job.setOutputFormatClass(TextOutputFormat.class); 533 TextOutputFormat.setOutputPath(job, new Path(inputDir.getParent(), "outputs")); 534 535 TableMapReduceUtil.addDependencyJars(job); 536 TableMapReduceUtil.addDependencyJarsForClasses(job.getConfiguration(), 537 Histogram.class, // yammer metrics 538 ObjectMapper.class, // jackson-mapper-asl 539 FilterAllFilter.class // hbase-server tests jar 540 ); 541 542 TableMapReduceUtil.initCredentials(job); 543 544 job.waitForCompletion(true); 545 return job; 546 } 547 548 /** 549 * Each client has one mapper to do the work, and client do the resulting count in a map task. 550 */ 551 552 static String JOB_INPUT_FILENAME = "input.txt"; 553 554 /* 555 * Write input file of offsets-per-client for the mapreduce job. 556 * @param c Configuration 557 * @return Directory that contains file written whose name is JOB_INPUT_FILENAME 558 * @throws IOException 559 */ 560 static Path writeInputFile(final Configuration c, final TestOptions opts) throws IOException { 561 return writeInputFile(c, opts, new Path(".")); 562 } 563 564 static Path writeInputFile(final Configuration c, final TestOptions opts, final Path basedir) 565 throws IOException { 566 SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss"); 567 Path jobdir = new Path(new Path(basedir, PERF_EVAL_DIR), formatter.format(new Date())); 568 Path inputDir = new Path(jobdir, "inputs"); 569 570 FileSystem fs = FileSystem.get(c); 571 fs.mkdirs(inputDir); 572 573 Path inputFile = new Path(inputDir, JOB_INPUT_FILENAME); 574 PrintStream out = new PrintStream(fs.create(inputFile)); 575 // Make input random. 576 Map<Integer, String> m = new TreeMap<>(); 577 Hash h = MurmurHash.getInstance(); 578 int perClientRows = (opts.totalRows / opts.numClientThreads); 579 try { 580 for (int j = 0; j < opts.numClientThreads; j++) { 581 TestOptions next = new TestOptions(opts); 582 next.startRow = j * perClientRows; 583 next.perClientRunRows = perClientRows; 584 String s = MAPPER.writeValueAsString(next); 585 LOG.info("Client=" + j + ", input=" + s); 586 byte[] b = Bytes.toBytes(s); 587 int hash = h.hash(new ByteArrayHashKey(b, 0, b.length), -1); 588 m.put(hash, s); 589 } 590 for (Map.Entry<Integer, String> e: m.entrySet()) { 591 out.println(e.getValue()); 592 } 593 } finally { 594 out.close(); 595 } 596 return inputDir; 597 } 598 599 /** 600 * Describes a command. 601 */ 602 static class CmdDescriptor { 603 private Class<? extends TestBase> cmdClass; 604 private String name; 605 private String description; 606 607 CmdDescriptor(Class<? extends TestBase> cmdClass, String name, String description) { 608 this.cmdClass = cmdClass; 609 this.name = name; 610 this.description = description; 611 } 612 613 public Class<? extends TestBase> getCmdClass() { 614 return cmdClass; 615 } 616 617 public String getName() { 618 return name; 619 } 620 621 public String getDescription() { 622 return description; 623 } 624 } 625 626 /** 627 * Wraps up options passed to {@link org.apache.hadoop.hbase.PerformanceEvaluation}. 628 * This makes tracking all these arguments a little easier. 629 * NOTE: ADDING AN OPTION, you need to add a data member, a getter/setter (to make JSON 630 * serialization of this TestOptions class behave), and you need to add to the clone constructor 631 * below copying your new option from the 'that' to the 'this'. Look for 'clone' below. 632 */ 633 static class TestOptions { 634 String cmdName = null; 635 boolean nomapred = false; 636 boolean filterAll = false; 637 int startRow = 0; 638 float size = 1.0f; 639 int perClientRunRows = DEFAULT_ROWS_PER_GB; 640 int numClientThreads = 1; 641 int totalRows = DEFAULT_ROWS_PER_GB; 642 int measureAfter = 0; 643 float sampleRate = 1.0f; 644 double traceRate = 0.0; 645 String tableName = TABLE_NAME; 646 boolean flushCommits = true; 647 boolean writeToWAL = true; 648 boolean autoFlush = false; 649 boolean oneCon = false; 650 boolean useTags = false; 651 int noOfTags = 1; 652 boolean reportLatency = false; 653 int multiGet = 0; 654 int randomSleep = 0; 655 boolean inMemoryCF = false; 656 int presplitRegions = 0; 657 int replicas = HTableDescriptor.DEFAULT_REGION_REPLICATION; 658 String splitPolicy = null; 659 Compression.Algorithm compression = Compression.Algorithm.NONE; 660 BloomType bloomType = BloomType.ROW; 661 int blockSize = HConstants.DEFAULT_BLOCKSIZE; 662 DataBlockEncoding blockEncoding = DataBlockEncoding.NONE; 663 boolean valueRandom = false; 664 boolean valueZipf = false; 665 int valueSize = DEFAULT_VALUE_LENGTH; 666 int period = (this.perClientRunRows / 10) == 0? perClientRunRows: perClientRunRows / 10; 667 int cycles = 1; 668 int columns = 1; 669 int families = 1; 670 int caching = 30; 671 boolean addColumns = true; 672 MemoryCompactionPolicy inMemoryCompaction = 673 MemoryCompactionPolicy.valueOf( 674 CompactingMemStore.COMPACTING_MEMSTORE_TYPE_DEFAULT); 675 boolean asyncPrefetch = false; 676 boolean cacheBlocks = true; 677 Scan.ReadType scanReadType = Scan.ReadType.DEFAULT; 678 long bufferSize = 2l * 1024l * 1024l; 679 680 public TestOptions() {} 681 682 /** 683 * Clone constructor. 684 * @param that Object to copy from. 685 */ 686 public TestOptions(TestOptions that) { 687 this.cmdName = that.cmdName; 688 this.cycles = that.cycles; 689 this.nomapred = that.nomapred; 690 this.startRow = that.startRow; 691 this.size = that.size; 692 this.perClientRunRows = that.perClientRunRows; 693 this.numClientThreads = that.numClientThreads; 694 this.totalRows = that.totalRows; 695 this.sampleRate = that.sampleRate; 696 this.traceRate = that.traceRate; 697 this.tableName = that.tableName; 698 this.flushCommits = that.flushCommits; 699 this.writeToWAL = that.writeToWAL; 700 this.autoFlush = that.autoFlush; 701 this.oneCon = that.oneCon; 702 this.useTags = that.useTags; 703 this.noOfTags = that.noOfTags; 704 this.reportLatency = that.reportLatency; 705 this.multiGet = that.multiGet; 706 this.inMemoryCF = that.inMemoryCF; 707 this.presplitRegions = that.presplitRegions; 708 this.replicas = that.replicas; 709 this.splitPolicy = that.splitPolicy; 710 this.compression = that.compression; 711 this.blockEncoding = that.blockEncoding; 712 this.filterAll = that.filterAll; 713 this.bloomType = that.bloomType; 714 this.blockSize = that.blockSize; 715 this.valueRandom = that.valueRandom; 716 this.valueZipf = that.valueZipf; 717 this.valueSize = that.valueSize; 718 this.period = that.period; 719 this.randomSleep = that.randomSleep; 720 this.measureAfter = that.measureAfter; 721 this.addColumns = that.addColumns; 722 this.columns = that.columns; 723 this.families = that.families; 724 this.caching = that.caching; 725 this.inMemoryCompaction = that.inMemoryCompaction; 726 this.asyncPrefetch = that.asyncPrefetch; 727 this.cacheBlocks = that.cacheBlocks; 728 this.scanReadType = that.scanReadType; 729 this.bufferSize = that.bufferSize; 730 } 731 732 public int getCaching() { 733 return this.caching; 734 } 735 736 public void setCaching(final int caching) { 737 this.caching = caching; 738 } 739 740 public int getColumns() { 741 return this.columns; 742 } 743 744 public void setColumns(final int columns) { 745 this.columns = columns; 746 } 747 748 public int getFamilies() { 749 return this.families; 750 } 751 752 public void setFamilies(final int families) { 753 this.families = families; 754 } 755 756 public int getCycles() { 757 return this.cycles; 758 } 759 760 public void setCycles(final int cycles) { 761 this.cycles = cycles; 762 } 763 764 public boolean isValueZipf() { 765 return valueZipf; 766 } 767 768 public void setValueZipf(boolean valueZipf) { 769 this.valueZipf = valueZipf; 770 } 771 772 public String getCmdName() { 773 return cmdName; 774 } 775 776 public void setCmdName(String cmdName) { 777 this.cmdName = cmdName; 778 } 779 780 public int getRandomSleep() { 781 return randomSleep; 782 } 783 784 public void setRandomSleep(int randomSleep) { 785 this.randomSleep = randomSleep; 786 } 787 788 public int getReplicas() { 789 return replicas; 790 } 791 792 public void setReplicas(int replicas) { 793 this.replicas = replicas; 794 } 795 796 public String getSplitPolicy() { 797 return splitPolicy; 798 } 799 800 public void setSplitPolicy(String splitPolicy) { 801 this.splitPolicy = splitPolicy; 802 } 803 804 public void setNomapred(boolean nomapred) { 805 this.nomapred = nomapred; 806 } 807 808 public void setFilterAll(boolean filterAll) { 809 this.filterAll = filterAll; 810 } 811 812 public void setStartRow(int startRow) { 813 this.startRow = startRow; 814 } 815 816 public void setSize(float size) { 817 this.size = size; 818 } 819 820 public void setPerClientRunRows(int perClientRunRows) { 821 this.perClientRunRows = perClientRunRows; 822 } 823 824 public void setNumClientThreads(int numClientThreads) { 825 this.numClientThreads = numClientThreads; 826 } 827 828 public void setTotalRows(int totalRows) { 829 this.totalRows = totalRows; 830 } 831 832 public void setSampleRate(float sampleRate) { 833 this.sampleRate = sampleRate; 834 } 835 836 public void setTraceRate(double traceRate) { 837 this.traceRate = traceRate; 838 } 839 840 public void setTableName(String tableName) { 841 this.tableName = tableName; 842 } 843 844 public void setFlushCommits(boolean flushCommits) { 845 this.flushCommits = flushCommits; 846 } 847 848 public void setWriteToWAL(boolean writeToWAL) { 849 this.writeToWAL = writeToWAL; 850 } 851 852 public void setAutoFlush(boolean autoFlush) { 853 this.autoFlush = autoFlush; 854 } 855 856 public void setOneCon(boolean oneCon) { 857 this.oneCon = oneCon; 858 } 859 860 public void setUseTags(boolean useTags) { 861 this.useTags = useTags; 862 } 863 864 public void setNoOfTags(int noOfTags) { 865 this.noOfTags = noOfTags; 866 } 867 868 public void setReportLatency(boolean reportLatency) { 869 this.reportLatency = reportLatency; 870 } 871 872 public void setMultiGet(int multiGet) { 873 this.multiGet = multiGet; 874 } 875 876 public void setInMemoryCF(boolean inMemoryCF) { 877 this.inMemoryCF = inMemoryCF; 878 } 879 880 public void setPresplitRegions(int presplitRegions) { 881 this.presplitRegions = presplitRegions; 882 } 883 884 public void setCompression(Compression.Algorithm compression) { 885 this.compression = compression; 886 } 887 888 public void setBloomType(BloomType bloomType) { 889 this.bloomType = bloomType; 890 } 891 892 public void setBlockSize(int blockSize) { 893 this.blockSize = blockSize; 894 } 895 896 public void setBlockEncoding(DataBlockEncoding blockEncoding) { 897 this.blockEncoding = blockEncoding; 898 } 899 900 public void setValueRandom(boolean valueRandom) { 901 this.valueRandom = valueRandom; 902 } 903 904 public void setValueSize(int valueSize) { 905 this.valueSize = valueSize; 906 } 907 908 public void setBufferSize(long bufferSize) { 909 this.bufferSize = bufferSize; 910 } 911 912 public void setPeriod(int period) { 913 this.period = period; 914 } 915 916 public boolean isNomapred() { 917 return nomapred; 918 } 919 920 public boolean isFilterAll() { 921 return filterAll; 922 } 923 924 public int getStartRow() { 925 return startRow; 926 } 927 928 public float getSize() { 929 return size; 930 } 931 932 public int getPerClientRunRows() { 933 return perClientRunRows; 934 } 935 936 public int getNumClientThreads() { 937 return numClientThreads; 938 } 939 940 public int getTotalRows() { 941 return totalRows; 942 } 943 944 public float getSampleRate() { 945 return sampleRate; 946 } 947 948 public double getTraceRate() { 949 return traceRate; 950 } 951 952 public String getTableName() { 953 return tableName; 954 } 955 956 public boolean isFlushCommits() { 957 return flushCommits; 958 } 959 960 public boolean isWriteToWAL() { 961 return writeToWAL; 962 } 963 964 public boolean isAutoFlush() { 965 return autoFlush; 966 } 967 968 public boolean isUseTags() { 969 return useTags; 970 } 971 972 public int getNoOfTags() { 973 return noOfTags; 974 } 975 976 public boolean isReportLatency() { 977 return reportLatency; 978 } 979 980 public int getMultiGet() { 981 return multiGet; 982 } 983 984 public boolean isInMemoryCF() { 985 return inMemoryCF; 986 } 987 988 public int getPresplitRegions() { 989 return presplitRegions; 990 } 991 992 public Compression.Algorithm getCompression() { 993 return compression; 994 } 995 996 public DataBlockEncoding getBlockEncoding() { 997 return blockEncoding; 998 } 999 1000 public boolean isValueRandom() { 1001 return valueRandom; 1002 } 1003 1004 public int getValueSize() { 1005 return valueSize; 1006 } 1007 1008 public int getPeriod() { 1009 return period; 1010 } 1011 1012 public BloomType getBloomType() { 1013 return bloomType; 1014 } 1015 1016 public int getBlockSize() { 1017 return blockSize; 1018 } 1019 1020 public boolean isOneCon() { 1021 return oneCon; 1022 } 1023 1024 public int getMeasureAfter() { 1025 return measureAfter; 1026 } 1027 1028 public void setMeasureAfter(int measureAfter) { 1029 this.measureAfter = measureAfter; 1030 } 1031 1032 public boolean getAddColumns() { 1033 return addColumns; 1034 } 1035 1036 public void setAddColumns(boolean addColumns) { 1037 this.addColumns = addColumns; 1038 } 1039 1040 public void setInMemoryCompaction(MemoryCompactionPolicy inMemoryCompaction) { 1041 this.inMemoryCompaction = inMemoryCompaction; 1042 } 1043 1044 public MemoryCompactionPolicy getInMemoryCompaction() { 1045 return this.inMemoryCompaction; 1046 } 1047 1048 public long getBufferSize() { 1049 return this.bufferSize; 1050 } 1051 } 1052 1053 /* 1054 * A test. 1055 * Subclass to particularize what happens per row. 1056 */ 1057 static abstract class TestBase { 1058 // Below is make it so when Tests are all running in the one 1059 // jvm, that they each have a differently seeded Random. 1060 private static final Random randomSeed = new Random(System.currentTimeMillis()); 1061 1062 private static long nextRandomSeed() { 1063 return randomSeed.nextLong(); 1064 } 1065 private final int everyN; 1066 1067 protected final Random rand = new Random(nextRandomSeed()); 1068 protected final Configuration conf; 1069 protected final TestOptions opts; 1070 1071 private final Status status; 1072 private final Sampler traceSampler; 1073 private final SpanReceiverHost receiverHost; 1074 1075 private String testName; 1076 private Histogram latencyHistogram; 1077 private Histogram valueSizeHistogram; 1078 private Histogram rpcCallsHistogram; 1079 private Histogram remoteRpcCallsHistogram; 1080 private Histogram millisBetweenNextHistogram; 1081 private Histogram regionsScannedHistogram; 1082 private Histogram bytesInResultsHistogram; 1083 private Histogram bytesInRemoteResultsHistogram; 1084 private RandomDistribution.Zipf zipf; 1085 1086 /** 1087 * Note that all subclasses of this class must provide a public constructor 1088 * that has the exact same list of arguments. 1089 */ 1090 TestBase(final Configuration conf, final TestOptions options, final Status status) { 1091 this.conf = conf; 1092 this.receiverHost = this.conf == null? null: SpanReceiverHost.getInstance(conf); 1093 this.opts = options; 1094 this.status = status; 1095 this.testName = this.getClass().getSimpleName(); 1096 if (options.traceRate >= 1.0) { 1097 this.traceSampler = Sampler.ALWAYS; 1098 } else if (options.traceRate > 0.0) { 1099 conf.setDouble("hbase.sampler.fraction", options.traceRate); 1100 this.traceSampler = new ProbabilitySampler(new HBaseHTraceConfiguration(conf)); 1101 } else { 1102 this.traceSampler = Sampler.NEVER; 1103 } 1104 everyN = (int) (opts.totalRows / (opts.totalRows * opts.sampleRate)); 1105 if (options.isValueZipf()) { 1106 this.zipf = new RandomDistribution.Zipf(this.rand, 1, options.getValueSize(), 1.2); 1107 } 1108 LOG.info("Sampling 1 every " + everyN + " out of " + opts.perClientRunRows + " total rows."); 1109 } 1110 1111 int getValueLength(final Random r) { 1112 if (this.opts.isValueRandom()) { 1113 return r.nextInt(opts.valueSize); 1114 } else if (this.opts.isValueZipf()) { 1115 return Math.abs(this.zipf.nextInt()); 1116 } else { 1117 return opts.valueSize; 1118 } 1119 } 1120 1121 void updateValueSize(final Result [] rs) throws IOException { 1122 if (rs == null || !isRandomValueSize()) return; 1123 for (Result r: rs) updateValueSize(r); 1124 } 1125 1126 void updateValueSize(final Result r) throws IOException { 1127 if (r == null || !isRandomValueSize()) return; 1128 int size = 0; 1129 for (CellScanner scanner = r.cellScanner(); scanner.advance();) { 1130 size += scanner.current().getValueLength(); 1131 } 1132 updateValueSize(size); 1133 } 1134 1135 void updateValueSize(final int valueSize) { 1136 if (!isRandomValueSize()) return; 1137 this.valueSizeHistogram.update(valueSize); 1138 } 1139 1140 void updateScanMetrics(final ScanMetrics metrics) { 1141 Map<String,Long> metricsMap = metrics.getMetricsMap(); 1142 Long rpcCalls = metricsMap.get(ScanMetrics.RPC_CALLS_METRIC_NAME); 1143 if (rpcCalls != null) { 1144 this.rpcCallsHistogram.update(rpcCalls.longValue()); 1145 } 1146 Long remoteRpcCalls = metricsMap.get(ScanMetrics.REMOTE_RPC_CALLS_METRIC_NAME); 1147 if (remoteRpcCalls != null) { 1148 this.remoteRpcCallsHistogram.update(remoteRpcCalls.longValue()); 1149 } 1150 Long millisBetweenNext = metricsMap.get(ScanMetrics.MILLIS_BETWEEN_NEXTS_METRIC_NAME); 1151 if (millisBetweenNext != null) { 1152 this.millisBetweenNextHistogram.update(millisBetweenNext.longValue()); 1153 } 1154 Long regionsScanned = metricsMap.get(ScanMetrics.REGIONS_SCANNED_METRIC_NAME); 1155 if (regionsScanned != null) { 1156 this.regionsScannedHistogram.update(regionsScanned.longValue()); 1157 } 1158 Long bytesInResults = metricsMap.get(ScanMetrics.BYTES_IN_RESULTS_METRIC_NAME); 1159 if (bytesInResults != null && bytesInResults.longValue() > 0) { 1160 this.bytesInResultsHistogram.update(bytesInResults.longValue()); 1161 } 1162 Long bytesInRemoteResults = metricsMap.get(ScanMetrics.BYTES_IN_REMOTE_RESULTS_METRIC_NAME); 1163 if (bytesInRemoteResults != null && bytesInRemoteResults.longValue() > 0) { 1164 this.bytesInRemoteResultsHistogram.update(bytesInRemoteResults.longValue()); 1165 } 1166 } 1167 1168 String generateStatus(final int sr, final int i, final int lr) { 1169 return sr + "/" + i + "/" + lr + ", latency " + getShortLatencyReport() + 1170 (!isRandomValueSize()? "": ", value size " + getShortValueSizeReport()); 1171 } 1172 1173 boolean isRandomValueSize() { 1174 return opts.valueRandom; 1175 } 1176 1177 protected int getReportingPeriod() { 1178 return opts.period; 1179 } 1180 1181 /** 1182 * Populated by testTakedown. Only implemented by RandomReadTest at the moment. 1183 */ 1184 public Histogram getLatencyHistogram() { 1185 return latencyHistogram; 1186 } 1187 1188 void testSetup() throws IOException { 1189 // test metrics 1190 latencyHistogram = YammerHistogramUtils.newHistogram(new UniformReservoir(1024 * 500)); 1191 valueSizeHistogram = YammerHistogramUtils.newHistogram(new UniformReservoir(1024 * 500)); 1192 // scan metrics 1193 rpcCallsHistogram = YammerHistogramUtils.newHistogram(new UniformReservoir(1024 * 500)); 1194 remoteRpcCallsHistogram = YammerHistogramUtils.newHistogram(new UniformReservoir(1024 * 500)); 1195 millisBetweenNextHistogram = YammerHistogramUtils.newHistogram(new UniformReservoir(1024 * 500)); 1196 regionsScannedHistogram = YammerHistogramUtils.newHistogram(new UniformReservoir(1024 * 500)); 1197 bytesInResultsHistogram = YammerHistogramUtils.newHistogram(new UniformReservoir(1024 * 500)); 1198 bytesInRemoteResultsHistogram = YammerHistogramUtils.newHistogram(new UniformReservoir(1024 * 500)); 1199 1200 createConnection(); 1201 onStartup(); 1202 } 1203 1204 abstract void createConnection() throws IOException; 1205 1206 abstract void onStartup() throws IOException; 1207 1208 void testTakedown() throws IOException { 1209 onTakedown(); 1210 // Print all stats for this thread continuously. 1211 // Synchronize on Test.class so different threads don't intermingle the 1212 // output. We can't use 'this' here because each thread has its own instance of Test class. 1213 synchronized (Test.class) { 1214 status.setStatus("Test : " + testName + ", Thread : " + Thread.currentThread().getName()); 1215 status.setStatus("Latency (us) : " + YammerHistogramUtils.getHistogramReport( 1216 latencyHistogram)); 1217 status.setStatus("Num measures (latency) : " + latencyHistogram.getCount()); 1218 status.setStatus(YammerHistogramUtils.getPrettyHistogramReport(latencyHistogram)); 1219 status.setStatus("ValueSize (bytes) : " 1220 + YammerHistogramUtils.getHistogramReport(valueSizeHistogram)); 1221 status.setStatus("Num measures (ValueSize): " + valueSizeHistogram.getCount()); 1222 status.setStatus(YammerHistogramUtils.getPrettyHistogramReport(valueSizeHistogram)); 1223 if (rpcCallsHistogram.getCount() > 0) { 1224 status.setStatus("rpcCalls (count): " + 1225 YammerHistogramUtils.getHistogramReport(rpcCallsHistogram)); 1226 } 1227 if (remoteRpcCallsHistogram.getCount() > 0) { 1228 status.setStatus("remoteRpcCalls (count): " + 1229 YammerHistogramUtils.getHistogramReport(remoteRpcCallsHistogram)); 1230 } 1231 if (millisBetweenNextHistogram.getCount() > 0) { 1232 status.setStatus("millisBetweenNext (latency): " + 1233 YammerHistogramUtils.getHistogramReport(millisBetweenNextHistogram)); 1234 } 1235 if (regionsScannedHistogram.getCount() > 0) { 1236 status.setStatus("regionsScanned (count): " + 1237 YammerHistogramUtils.getHistogramReport(regionsScannedHistogram)); 1238 } 1239 if (bytesInResultsHistogram.getCount() > 0) { 1240 status.setStatus("bytesInResults (size): " + 1241 YammerHistogramUtils.getHistogramReport(bytesInResultsHistogram)); 1242 } 1243 if (bytesInRemoteResultsHistogram.getCount() > 0) { 1244 status.setStatus("bytesInRemoteResults (size): " + 1245 YammerHistogramUtils.getHistogramReport(bytesInRemoteResultsHistogram)); 1246 } 1247 } 1248 closeConnection(); 1249 receiverHost.closeReceivers(); 1250 } 1251 1252 abstract void onTakedown() throws IOException; 1253 1254 abstract void closeConnection() throws IOException; 1255 1256 /* 1257 * Run test 1258 * @return Elapsed time. 1259 * @throws IOException 1260 */ 1261 long test() throws IOException, InterruptedException { 1262 testSetup(); 1263 LOG.info("Timed test starting in thread " + Thread.currentThread().getName()); 1264 final long startTime = System.nanoTime(); 1265 try { 1266 testTimed(); 1267 } finally { 1268 testTakedown(); 1269 } 1270 return (System.nanoTime() - startTime) / 1000000; 1271 } 1272 1273 int getStartRow() { 1274 return opts.startRow; 1275 } 1276 1277 int getLastRow() { 1278 return getStartRow() + opts.perClientRunRows; 1279 } 1280 1281 /** 1282 * Provides an extension point for tests that don't want a per row invocation. 1283 */ 1284 void testTimed() throws IOException, InterruptedException { 1285 int startRow = getStartRow(); 1286 int lastRow = getLastRow(); 1287 TraceUtil.addSampler(traceSampler); 1288 // Report on completion of 1/10th of total. 1289 for (int ii = 0; ii < opts.cycles; ii++) { 1290 if (opts.cycles > 1) LOG.info("Cycle=" + ii + " of " + opts.cycles); 1291 for (int i = startRow; i < lastRow; i++) { 1292 if (i % everyN != 0) continue; 1293 long startTime = System.nanoTime(); 1294 try (TraceScope scope = TraceUtil.createTrace("test row");){ 1295 testRow(i); 1296 } 1297 if ( (i - startRow) > opts.measureAfter) { 1298 // If multiget is enabled, say set to 10, testRow() returns immediately first 9 times 1299 // and sends the actual get request in the 10th iteration. We should only set latency 1300 // when actual request is sent because otherwise it turns out to be 0. 1301 if (opts.multiGet == 0 || (i - startRow + 1) % opts.multiGet == 0) { 1302 latencyHistogram.update((System.nanoTime() - startTime) / 1000); 1303 } 1304 if (status != null && i > 0 && (i % getReportingPeriod()) == 0) { 1305 status.setStatus(generateStatus(startRow, i, lastRow)); 1306 } 1307 } 1308 } 1309 } 1310 } 1311 1312 /** 1313 * @return Subset of the histograms' calculation. 1314 */ 1315 public String getShortLatencyReport() { 1316 return YammerHistogramUtils.getShortHistogramReport(this.latencyHistogram); 1317 } 1318 1319 /** 1320 * @return Subset of the histograms' calculation. 1321 */ 1322 public String getShortValueSizeReport() { 1323 return YammerHistogramUtils.getShortHistogramReport(this.valueSizeHistogram); 1324 } 1325 1326 /* 1327 * Test for individual row. 1328 * @param i Row index. 1329 */ 1330 abstract void testRow(final int i) throws IOException, InterruptedException; 1331 } 1332 1333 static abstract class Test extends TestBase { 1334 protected Connection connection; 1335 1336 Test(final Connection con, final TestOptions options, final Status status) { 1337 super(con == null ? HBaseConfiguration.create() : con.getConfiguration(), options, status); 1338 this.connection = con; 1339 } 1340 1341 @Override 1342 void createConnection() throws IOException { 1343 if (!opts.isOneCon()) { 1344 this.connection = ConnectionFactory.createConnection(conf); 1345 } 1346 } 1347 1348 @Override 1349 void closeConnection() throws IOException { 1350 if (!opts.isOneCon()) { 1351 this.connection.close(); 1352 } 1353 } 1354 } 1355 1356 static abstract class AsyncTest extends TestBase { 1357 protected AsyncConnection connection; 1358 1359 AsyncTest(final AsyncConnection con, final TestOptions options, final Status status) { 1360 super(con == null ? HBaseConfiguration.create() : con.getConfiguration(), options, status); 1361 this.connection = con; 1362 } 1363 1364 @Override 1365 void createConnection() { 1366 if (!opts.isOneCon()) { 1367 try { 1368 this.connection = ConnectionFactory.createAsyncConnection(conf).get(); 1369 } catch (InterruptedException | ExecutionException e) { 1370 LOG.error("Failed to create async connection", e); 1371 } 1372 } 1373 } 1374 1375 @Override 1376 void closeConnection() throws IOException { 1377 if (!opts.isOneCon()) { 1378 this.connection.close(); 1379 } 1380 } 1381 } 1382 1383 static abstract class TableTest extends Test { 1384 protected Table table; 1385 1386 TableTest(Connection con, TestOptions options, Status status) { 1387 super(con, options, status); 1388 } 1389 1390 @Override 1391 void onStartup() throws IOException { 1392 this.table = connection.getTable(TableName.valueOf(opts.tableName)); 1393 } 1394 1395 @Override 1396 void onTakedown() throws IOException { 1397 table.close(); 1398 } 1399 } 1400 1401 static abstract class AsyncTableTest extends AsyncTest { 1402 protected AsyncTable<?> table; 1403 1404 AsyncTableTest(AsyncConnection con, TestOptions options, Status status) { 1405 super(con, options, status); 1406 } 1407 1408 @Override 1409 void onStartup() throws IOException { 1410 this.table = connection.getTable(TableName.valueOf(opts.tableName)); 1411 } 1412 1413 @Override 1414 void onTakedown() throws IOException { 1415 } 1416 } 1417 1418 static class AsyncRandomReadTest extends AsyncTableTest { 1419 private final Consistency consistency; 1420 private ArrayList<Get> gets; 1421 private Random rd = new Random(); 1422 1423 AsyncRandomReadTest(AsyncConnection con, TestOptions options, Status status) { 1424 super(con, options, status); 1425 consistency = options.replicas == DEFAULT_OPTS.replicas ? null : Consistency.TIMELINE; 1426 if (opts.multiGet > 0) { 1427 LOG.info("MultiGet enabled. Sending GETs in batches of " + opts.multiGet + "."); 1428 this.gets = new ArrayList<>(opts.multiGet); 1429 } 1430 } 1431 1432 @Override 1433 void testRow(final int i) throws IOException, InterruptedException { 1434 if (opts.randomSleep > 0) { 1435 Thread.sleep(rd.nextInt(opts.randomSleep)); 1436 } 1437 Get get = new Get(getRandomRow(this.rand, opts.totalRows)); 1438 for (int family = 0; family < opts.families; family++) { 1439 byte[] familyName = Bytes.toBytes(FAMILY_NAME_BASE + family); 1440 if (opts.addColumns) { 1441 for (int column = 0; column < opts.columns; column++) { 1442 byte [] qualifier = column == 0? COLUMN_ZERO: Bytes.toBytes("" + column); 1443 get.addColumn(familyName, qualifier); 1444 } 1445 } else { 1446 get.addFamily(familyName); 1447 } 1448 } 1449 if (opts.filterAll) { 1450 get.setFilter(new FilterAllFilter()); 1451 } 1452 get.setConsistency(consistency); 1453 if (LOG.isTraceEnabled()) LOG.trace(get.toString()); 1454 try { 1455 if (opts.multiGet > 0) { 1456 this.gets.add(get); 1457 if (this.gets.size() == opts.multiGet) { 1458 Result[] rs = 1459 this.table.get(this.gets).stream().map(f -> propagate(f::get)).toArray(Result[]::new); 1460 updateValueSize(rs); 1461 this.gets.clear(); 1462 } 1463 } else { 1464 updateValueSize(this.table.get(get).get()); 1465 } 1466 } catch (ExecutionException e) { 1467 throw new IOException(e); 1468 } 1469 } 1470 1471 public static RuntimeException runtime(Throwable e) { 1472 if (e instanceof RuntimeException) { 1473 return (RuntimeException) e; 1474 } 1475 return new RuntimeException(e); 1476 } 1477 1478 public static <V> V propagate(Callable<V> callable) { 1479 try { 1480 return callable.call(); 1481 } catch (Exception e) { 1482 throw runtime(e); 1483 } 1484 } 1485 1486 @Override 1487 protected int getReportingPeriod() { 1488 int period = opts.perClientRunRows / 10; 1489 return period == 0 ? opts.perClientRunRows : period; 1490 } 1491 1492 @Override 1493 protected void testTakedown() throws IOException { 1494 if (this.gets != null && this.gets.size() > 0) { 1495 this.table.get(gets); 1496 this.gets.clear(); 1497 } 1498 super.testTakedown(); 1499 } 1500 } 1501 1502 static class AsyncRandomWriteTest extends AsyncTableTest { 1503 AsyncRandomWriteTest(AsyncConnection con, TestOptions options, Status status) { 1504 super(con, options, status); 1505 } 1506 1507 @Override 1508 void testRow(final int i) throws IOException, InterruptedException { 1509 byte[] row = getRandomRow(this.rand, opts.totalRows); 1510 Put put = new Put(row); 1511 for (int family = 0; family < opts.families; family++) { 1512 byte[] familyName = Bytes.toBytes(FAMILY_NAME_BASE + family); 1513 for (int column = 0; column < opts.columns; column++) { 1514 byte[] qualifier = column == 0 ? COLUMN_ZERO : Bytes.toBytes("" + column); 1515 byte[] value = generateData(this.rand, getValueLength(this.rand)); 1516 if (opts.useTags) { 1517 byte[] tag = generateData(this.rand, TAG_LENGTH); 1518 Tag[] tags = new Tag[opts.noOfTags]; 1519 for (int n = 0; n < opts.noOfTags; n++) { 1520 Tag t = new ArrayBackedTag((byte) n, tag); 1521 tags[n] = t; 1522 } 1523 KeyValue kv = 1524 new KeyValue(row, familyName, qualifier, HConstants.LATEST_TIMESTAMP, value, tags); 1525 put.add(kv); 1526 updateValueSize(kv.getValueLength()); 1527 } else { 1528 put.addColumn(familyName, qualifier, value); 1529 updateValueSize(value.length); 1530 } 1531 } 1532 } 1533 put.setDurability(opts.writeToWAL ? Durability.SYNC_WAL : Durability.SKIP_WAL); 1534 try { 1535 table.put(put).get(); 1536 } catch (ExecutionException e) { 1537 throw new IOException(e); 1538 } 1539 } 1540 } 1541 1542 static class AsyncScanTest extends AsyncTableTest { 1543 private ResultScanner testScanner; 1544 private AsyncTable<?> asyncTable; 1545 1546 AsyncScanTest(AsyncConnection con, TestOptions options, Status status) { 1547 super(con, options, status); 1548 } 1549 1550 @Override 1551 void onStartup() throws IOException { 1552 this.asyncTable = 1553 connection.getTable(TableName.valueOf(opts.tableName), 1554 Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors())); 1555 } 1556 1557 @Override 1558 void testTakedown() throws IOException { 1559 if (this.testScanner != null) { 1560 updateScanMetrics(this.testScanner.getScanMetrics()); 1561 this.testScanner.close(); 1562 } 1563 super.testTakedown(); 1564 } 1565 1566 @Override 1567 void testRow(final int i) throws IOException { 1568 if (this.testScanner == null) { 1569 Scan scan = 1570 new Scan().withStartRow(format(opts.startRow)).setCaching(opts.caching) 1571 .setCacheBlocks(opts.cacheBlocks).setAsyncPrefetch(opts.asyncPrefetch) 1572 .setReadType(opts.scanReadType).setScanMetricsEnabled(true); 1573 for (int family = 0; family < opts.families; family++) { 1574 byte[] familyName = Bytes.toBytes(FAMILY_NAME_BASE + family); 1575 if (opts.addColumns) { 1576 for (int column = 0; column < opts.columns; column++) { 1577 byte [] qualifier = column == 0? COLUMN_ZERO: Bytes.toBytes("" + column); 1578 scan.addColumn(familyName, qualifier); 1579 } 1580 } else { 1581 scan.addFamily(familyName); 1582 } 1583 } 1584 if (opts.filterAll) { 1585 scan.setFilter(new FilterAllFilter()); 1586 } 1587 this.testScanner = asyncTable.getScanner(scan); 1588 } 1589 Result r = testScanner.next(); 1590 updateValueSize(r); 1591 } 1592 } 1593 1594 static class AsyncSequentialReadTest extends AsyncTableTest { 1595 AsyncSequentialReadTest(AsyncConnection con, TestOptions options, Status status) { 1596 super(con, options, status); 1597 } 1598 1599 @Override 1600 void testRow(final int i) throws IOException, InterruptedException { 1601 Get get = new Get(format(i)); 1602 for (int family = 0; family < opts.families; family++) { 1603 byte[] familyName = Bytes.toBytes(FAMILY_NAME_BASE + family); 1604 if (opts.addColumns) { 1605 for (int column = 0; column < opts.columns; column++) { 1606 byte [] qualifier = column == 0? COLUMN_ZERO: Bytes.toBytes("" + column); 1607 get.addColumn(familyName, qualifier); 1608 } 1609 } else { 1610 get.addFamily(familyName); 1611 } 1612 } 1613 if (opts.filterAll) { 1614 get.setFilter(new FilterAllFilter()); 1615 } 1616 try { 1617 updateValueSize(table.get(get).get()); 1618 } catch (ExecutionException e) { 1619 throw new IOException(e); 1620 } 1621 } 1622 } 1623 1624 static class AsyncSequentialWriteTest extends AsyncTableTest { 1625 AsyncSequentialWriteTest(AsyncConnection con, TestOptions options, Status status) { 1626 super(con, options, status); 1627 } 1628 1629 @Override 1630 void testRow(final int i) throws IOException, InterruptedException { 1631 byte[] row = format(i); 1632 Put put = new Put(row); 1633 for (int family = 0; family < opts.families; family++) { 1634 byte[] familyName = Bytes.toBytes(FAMILY_NAME_BASE + family); 1635 for (int column = 0; column < opts.columns; column++) { 1636 byte [] qualifier = column == 0? COLUMN_ZERO: Bytes.toBytes("" + column); 1637 byte[] value = generateData(this.rand, getValueLength(this.rand)); 1638 if (opts.useTags) { 1639 byte[] tag = generateData(this.rand, TAG_LENGTH); 1640 Tag[] tags = new Tag[opts.noOfTags]; 1641 for (int n = 0; n < opts.noOfTags; n++) { 1642 Tag t = new ArrayBackedTag((byte) n, tag); 1643 tags[n] = t; 1644 } 1645 KeyValue kv = new KeyValue(row, familyName, qualifier, HConstants.LATEST_TIMESTAMP, 1646 value, tags); 1647 put.add(kv); 1648 updateValueSize(kv.getValueLength()); 1649 } else { 1650 put.addColumn(familyName, qualifier, value); 1651 updateValueSize(value.length); 1652 } 1653 } 1654 } 1655 put.setDurability(opts.writeToWAL ? Durability.SYNC_WAL : Durability.SKIP_WAL); 1656 try { 1657 table.put(put).get(); 1658 } catch (ExecutionException e) { 1659 throw new IOException(e); 1660 } 1661 } 1662 } 1663 1664 static abstract class BufferedMutatorTest extends Test { 1665 protected BufferedMutator mutator; 1666 protected Table table; 1667 1668 BufferedMutatorTest(Connection con, TestOptions options, Status status) { 1669 super(con, options, status); 1670 } 1671 1672 @Override 1673 void onStartup() throws IOException { 1674 BufferedMutatorParams p = new BufferedMutatorParams(TableName.valueOf(opts.tableName)); 1675 p.writeBufferSize(opts.bufferSize); 1676 this.mutator = connection.getBufferedMutator(p); 1677 this.table = connection.getTable(TableName.valueOf(opts.tableName)); 1678 } 1679 1680 @Override 1681 void onTakedown() throws IOException { 1682 mutator.close(); 1683 table.close(); 1684 } 1685 } 1686 1687 static class RandomSeekScanTest extends TableTest { 1688 RandomSeekScanTest(Connection con, TestOptions options, Status status) { 1689 super(con, options, status); 1690 } 1691 1692 @Override 1693 void testRow(final int i) throws IOException { 1694 Scan scan = new Scan().withStartRow(getRandomRow(this.rand, opts.totalRows)) 1695 .setCaching(opts.caching).setCacheBlocks(opts.cacheBlocks) 1696 .setAsyncPrefetch(opts.asyncPrefetch).setReadType(opts.scanReadType) 1697 .setScanMetricsEnabled(true); 1698 FilterList list = new FilterList(); 1699 for (int family = 0; family < opts.families; family++) { 1700 byte[] familyName = Bytes.toBytes(FAMILY_NAME_BASE + family); 1701 if (opts.addColumns) { 1702 for (int column = 0; column < opts.columns; column++) { 1703 byte [] qualifier = column == 0? COLUMN_ZERO: Bytes.toBytes("" + column); 1704 scan.addColumn(familyName, qualifier); 1705 } 1706 } else { 1707 scan.addFamily(familyName); 1708 } 1709 } 1710 if (opts.filterAll) { 1711 list.addFilter(new FilterAllFilter()); 1712 } 1713 list.addFilter(new WhileMatchFilter(new PageFilter(120))); 1714 scan.setFilter(list); 1715 ResultScanner s = this.table.getScanner(scan); 1716 try { 1717 for (Result rr; (rr = s.next()) != null;) { 1718 updateValueSize(rr); 1719 } 1720 } finally { 1721 updateScanMetrics(s.getScanMetrics()); 1722 s.close(); 1723 } 1724 } 1725 1726 @Override 1727 protected int getReportingPeriod() { 1728 int period = opts.perClientRunRows / 100; 1729 return period == 0 ? opts.perClientRunRows : period; 1730 } 1731 1732 } 1733 1734 static abstract class RandomScanWithRangeTest extends TableTest { 1735 RandomScanWithRangeTest(Connection con, TestOptions options, Status status) { 1736 super(con, options, status); 1737 } 1738 1739 @Override 1740 void testRow(final int i) throws IOException { 1741 Pair<byte[], byte[]> startAndStopRow = getStartAndStopRow(); 1742 Scan scan = new Scan().withStartRow(startAndStopRow.getFirst()) 1743 .withStopRow(startAndStopRow.getSecond()).setCaching(opts.caching) 1744 .setCacheBlocks(opts.cacheBlocks).setAsyncPrefetch(opts.asyncPrefetch) 1745 .setReadType(opts.scanReadType).setScanMetricsEnabled(true); 1746 for (int family = 0; family < opts.families; family++) { 1747 byte[] familyName = Bytes.toBytes(FAMILY_NAME_BASE + family); 1748 if (opts.addColumns) { 1749 for (int column = 0; column < opts.columns; column++) { 1750 byte [] qualifier = column == 0? COLUMN_ZERO: Bytes.toBytes("" + column); 1751 scan.addColumn(familyName, qualifier); 1752 } 1753 } else { 1754 scan.addFamily(familyName); 1755 } 1756 } 1757 if (opts.filterAll) { 1758 scan.setFilter(new FilterAllFilter()); 1759 } 1760 Result r = null; 1761 int count = 0; 1762 ResultScanner s = this.table.getScanner(scan); 1763 try { 1764 for (; (r = s.next()) != null;) { 1765 updateValueSize(r); 1766 count++; 1767 } 1768 if (i % 100 == 0) { 1769 LOG.info(String.format("Scan for key range %s - %s returned %s rows", 1770 Bytes.toString(startAndStopRow.getFirst()), 1771 Bytes.toString(startAndStopRow.getSecond()), count)); 1772 } 1773 } finally { 1774 updateScanMetrics(s.getScanMetrics()); 1775 s.close(); 1776 } 1777 } 1778 1779 protected abstract Pair<byte[],byte[]> getStartAndStopRow(); 1780 1781 protected Pair<byte[], byte[]> generateStartAndStopRows(int maxRange) { 1782 int start = this.rand.nextInt(Integer.MAX_VALUE) % opts.totalRows; 1783 int stop = start + maxRange; 1784 return new Pair<>(format(start), format(stop)); 1785 } 1786 1787 @Override 1788 protected int getReportingPeriod() { 1789 int period = opts.perClientRunRows / 100; 1790 return period == 0? opts.perClientRunRows: period; 1791 } 1792 } 1793 1794 static class RandomScanWithRange10Test extends RandomScanWithRangeTest { 1795 RandomScanWithRange10Test(Connection con, TestOptions options, Status status) { 1796 super(con, options, status); 1797 } 1798 1799 @Override 1800 protected Pair<byte[], byte[]> getStartAndStopRow() { 1801 return generateStartAndStopRows(10); 1802 } 1803 } 1804 1805 static class RandomScanWithRange100Test extends RandomScanWithRangeTest { 1806 RandomScanWithRange100Test(Connection con, TestOptions options, Status status) { 1807 super(con, options, status); 1808 } 1809 1810 @Override 1811 protected Pair<byte[], byte[]> getStartAndStopRow() { 1812 return generateStartAndStopRows(100); 1813 } 1814 } 1815 1816 static class RandomScanWithRange1000Test extends RandomScanWithRangeTest { 1817 RandomScanWithRange1000Test(Connection con, TestOptions options, Status status) { 1818 super(con, options, status); 1819 } 1820 1821 @Override 1822 protected Pair<byte[], byte[]> getStartAndStopRow() { 1823 return generateStartAndStopRows(1000); 1824 } 1825 } 1826 1827 static class RandomScanWithRange10000Test extends RandomScanWithRangeTest { 1828 RandomScanWithRange10000Test(Connection con, TestOptions options, Status status) { 1829 super(con, options, status); 1830 } 1831 1832 @Override 1833 protected Pair<byte[], byte[]> getStartAndStopRow() { 1834 return generateStartAndStopRows(10000); 1835 } 1836 } 1837 1838 static class RandomReadTest extends TableTest { 1839 private final Consistency consistency; 1840 private ArrayList<Get> gets; 1841 private Random rd = new Random(); 1842 1843 RandomReadTest(Connection con, TestOptions options, Status status) { 1844 super(con, options, status); 1845 consistency = options.replicas == DEFAULT_OPTS.replicas ? null : Consistency.TIMELINE; 1846 if (opts.multiGet > 0) { 1847 LOG.info("MultiGet enabled. Sending GETs in batches of " + opts.multiGet + "."); 1848 this.gets = new ArrayList<>(opts.multiGet); 1849 } 1850 } 1851 1852 @Override 1853 void testRow(final int i) throws IOException, InterruptedException { 1854 if (opts.randomSleep > 0) { 1855 Thread.sleep(rd.nextInt(opts.randomSleep)); 1856 } 1857 Get get = new Get(getRandomRow(this.rand, opts.totalRows)); 1858 for (int family = 0; family < opts.families; family++) { 1859 byte[] familyName = Bytes.toBytes(FAMILY_NAME_BASE + family); 1860 if (opts.addColumns) { 1861 for (int column = 0; column < opts.columns; column++) { 1862 byte [] qualifier = column == 0? COLUMN_ZERO: Bytes.toBytes("" + column); 1863 get.addColumn(familyName, qualifier); 1864 } 1865 } else { 1866 get.addFamily(familyName); 1867 } 1868 } 1869 if (opts.filterAll) { 1870 get.setFilter(new FilterAllFilter()); 1871 } 1872 get.setConsistency(consistency); 1873 if (LOG.isTraceEnabled()) LOG.trace(get.toString()); 1874 if (opts.multiGet > 0) { 1875 this.gets.add(get); 1876 if (this.gets.size() == opts.multiGet) { 1877 Result [] rs = this.table.get(this.gets); 1878 updateValueSize(rs); 1879 this.gets.clear(); 1880 } 1881 } else { 1882 updateValueSize(this.table.get(get)); 1883 } 1884 } 1885 1886 @Override 1887 protected int getReportingPeriod() { 1888 int period = opts.perClientRunRows / 10; 1889 return period == 0 ? opts.perClientRunRows : period; 1890 } 1891 1892 @Override 1893 protected void testTakedown() throws IOException { 1894 if (this.gets != null && this.gets.size() > 0) { 1895 this.table.get(gets); 1896 this.gets.clear(); 1897 } 1898 super.testTakedown(); 1899 } 1900 } 1901 1902 static class RandomWriteTest extends BufferedMutatorTest { 1903 RandomWriteTest(Connection con, TestOptions options, Status status) { 1904 super(con, options, status); 1905 } 1906 1907 @Override 1908 void testRow(final int i) throws IOException { 1909 byte[] row = getRandomRow(this.rand, opts.totalRows); 1910 Put put = new Put(row); 1911 for (int family = 0; family < opts.families; family++) { 1912 byte[] familyName = Bytes.toBytes(FAMILY_NAME_BASE + family); 1913 for (int column = 0; column < opts.columns; column++) { 1914 byte [] qualifier = column == 0? COLUMN_ZERO: Bytes.toBytes("" + column); 1915 byte[] value = generateData(this.rand, getValueLength(this.rand)); 1916 if (opts.useTags) { 1917 byte[] tag = generateData(this.rand, TAG_LENGTH); 1918 Tag[] tags = new Tag[opts.noOfTags]; 1919 for (int n = 0; n < opts.noOfTags; n++) { 1920 Tag t = new ArrayBackedTag((byte) n, tag); 1921 tags[n] = t; 1922 } 1923 KeyValue kv = new KeyValue(row, familyName, qualifier, HConstants.LATEST_TIMESTAMP, 1924 value, tags); 1925 put.add(kv); 1926 updateValueSize(kv.getValueLength()); 1927 } else { 1928 put.addColumn(familyName, qualifier, value); 1929 updateValueSize(value.length); 1930 } 1931 } 1932 } 1933 put.setDurability(opts.writeToWAL ? Durability.SYNC_WAL : Durability.SKIP_WAL); 1934 if (opts.autoFlush) { 1935 table.put(put); 1936 } else { 1937 mutator.mutate(put); 1938 } 1939 } 1940 } 1941 1942 static class ScanTest extends TableTest { 1943 private ResultScanner testScanner; 1944 1945 ScanTest(Connection con, TestOptions options, Status status) { 1946 super(con, options, status); 1947 } 1948 1949 @Override 1950 void testTakedown() throws IOException { 1951 if (this.testScanner != null) { 1952 this.testScanner.close(); 1953 } 1954 super.testTakedown(); 1955 } 1956 1957 1958 @Override 1959 void testRow(final int i) throws IOException { 1960 if (this.testScanner == null) { 1961 Scan scan = new Scan().withStartRow(format(opts.startRow)).setCaching(opts.caching) 1962 .setCacheBlocks(opts.cacheBlocks).setAsyncPrefetch(opts.asyncPrefetch) 1963 .setReadType(opts.scanReadType).setScanMetricsEnabled(true); 1964 for (int family = 0; family < opts.families; family++) { 1965 byte[] familyName = Bytes.toBytes(FAMILY_NAME_BASE + family); 1966 if (opts.addColumns) { 1967 for (int column = 0; column < opts.columns; column++) { 1968 byte [] qualifier = column == 0? COLUMN_ZERO: Bytes.toBytes("" + column); 1969 scan.addColumn(familyName, qualifier); 1970 } 1971 } else { 1972 scan.addFamily(familyName); 1973 } 1974 } 1975 if (opts.filterAll) { 1976 scan.setFilter(new FilterAllFilter()); 1977 } 1978 this.testScanner = table.getScanner(scan); 1979 } 1980 Result r = testScanner.next(); 1981 updateValueSize(r); 1982 } 1983 } 1984 1985 /** 1986 * Base class for operations that are CAS-like; that read a value and then set it based off what 1987 * they read. In this category is increment, append, checkAndPut, etc. 1988 * 1989 * <p>These operations also want some concurrency going on. Usually when these tests run, they 1990 * operate in their own part of the key range. In CASTest, we will have them all overlap on the 1991 * same key space. We do this with our getStartRow and getLastRow overrides. 1992 */ 1993 static abstract class CASTableTest extends TableTest { 1994 private final byte [] qualifier; 1995 CASTableTest(Connection con, TestOptions options, Status status) { 1996 super(con, options, status); 1997 qualifier = Bytes.toBytes(this.getClass().getSimpleName()); 1998 } 1999 2000 byte [] getQualifier() { 2001 return this.qualifier; 2002 } 2003 2004 @Override 2005 int getStartRow() { 2006 return 0; 2007 } 2008 2009 @Override 2010 int getLastRow() { 2011 return opts.perClientRunRows; 2012 } 2013 } 2014 2015 static class IncrementTest extends CASTableTest { 2016 IncrementTest(Connection con, TestOptions options, Status status) { 2017 super(con, options, status); 2018 } 2019 2020 @Override 2021 void testRow(final int i) throws IOException { 2022 Increment increment = new Increment(format(i)); 2023 // unlike checkAndXXX tests, which make most sense to do on a single value, 2024 // if multiple families are specified for an increment test we assume it is 2025 // meant to raise the work factor 2026 for (int family = 0; family < opts.families; family++) { 2027 byte[] familyName = Bytes.toBytes(FAMILY_NAME_BASE + family); 2028 increment.addColumn(familyName, getQualifier(), 1l); 2029 } 2030 updateValueSize(this.table.increment(increment)); 2031 } 2032 } 2033 2034 static class AppendTest extends CASTableTest { 2035 AppendTest(Connection con, TestOptions options, Status status) { 2036 super(con, options, status); 2037 } 2038 2039 @Override 2040 void testRow(final int i) throws IOException { 2041 byte [] bytes = format(i); 2042 Append append = new Append(bytes); 2043 // unlike checkAndXXX tests, which make most sense to do on a single value, 2044 // if multiple families are specified for an append test we assume it is 2045 // meant to raise the work factor 2046 for (int family = 0; family < opts.families; family++) { 2047 byte[] familyName = Bytes.toBytes(FAMILY_NAME_BASE + family); 2048 append.addColumn(familyName, getQualifier(), bytes); 2049 } 2050 updateValueSize(this.table.append(append)); 2051 } 2052 } 2053 2054 static class CheckAndMutateTest extends CASTableTest { 2055 CheckAndMutateTest(Connection con, TestOptions options, Status status) { 2056 super(con, options, status); 2057 } 2058 2059 @Override 2060 void testRow(final int i) throws IOException { 2061 final byte [] bytes = format(i); 2062 // checkAndXXX tests operate on only a single value 2063 // Put a known value so when we go to check it, it is there. 2064 Put put = new Put(bytes); 2065 put.addColumn(FAMILY_ZERO, getQualifier(), bytes); 2066 this.table.put(put); 2067 RowMutations mutations = new RowMutations(bytes); 2068 mutations.add(put); 2069 this.table.checkAndMutate(bytes, FAMILY_ZERO).qualifier(getQualifier()) 2070 .ifEquals(bytes).thenMutate(mutations); 2071 } 2072 } 2073 2074 static class CheckAndPutTest extends CASTableTest { 2075 CheckAndPutTest(Connection con, TestOptions options, Status status) { 2076 super(con, options, status); 2077 } 2078 2079 @Override 2080 void testRow(final int i) throws IOException { 2081 final byte [] bytes = format(i); 2082 // checkAndXXX tests operate on only a single value 2083 // Put a known value so when we go to check it, it is there. 2084 Put put = new Put(bytes); 2085 put.addColumn(FAMILY_ZERO, getQualifier(), bytes); 2086 this.table.put(put); 2087 this.table.checkAndMutate(bytes, FAMILY_ZERO).qualifier(getQualifier()) 2088 .ifEquals(bytes).thenPut(put); 2089 } 2090 } 2091 2092 static class CheckAndDeleteTest extends CASTableTest { 2093 CheckAndDeleteTest(Connection con, TestOptions options, Status status) { 2094 super(con, options, status); 2095 } 2096 2097 @Override 2098 void testRow(final int i) throws IOException { 2099 final byte [] bytes = format(i); 2100 // checkAndXXX tests operate on only a single value 2101 // Put a known value so when we go to check it, it is there. 2102 Put put = new Put(bytes); 2103 put.addColumn(FAMILY_ZERO, getQualifier(), bytes); 2104 this.table.put(put); 2105 Delete delete = new Delete(put.getRow()); 2106 delete.addColumn(FAMILY_ZERO, getQualifier()); 2107 this.table.checkAndMutate(bytes, FAMILY_ZERO).qualifier(getQualifier()) 2108 .ifEquals(bytes).thenDelete(delete); 2109 } 2110 } 2111 2112 static class SequentialReadTest extends TableTest { 2113 SequentialReadTest(Connection con, TestOptions options, Status status) { 2114 super(con, options, status); 2115 } 2116 2117 @Override 2118 void testRow(final int i) throws IOException { 2119 Get get = new Get(format(i)); 2120 for (int family = 0; family < opts.families; family++) { 2121 byte[] familyName = Bytes.toBytes(FAMILY_NAME_BASE + family); 2122 if (opts.addColumns) { 2123 for (int column = 0; column < opts.columns; column++) { 2124 byte [] qualifier = column == 0? COLUMN_ZERO: Bytes.toBytes("" + column); 2125 get.addColumn(familyName, qualifier); 2126 } 2127 } else { 2128 get.addFamily(familyName); 2129 } 2130 } 2131 if (opts.filterAll) { 2132 get.setFilter(new FilterAllFilter()); 2133 } 2134 updateValueSize(table.get(get)); 2135 } 2136 } 2137 2138 static class SequentialWriteTest extends BufferedMutatorTest { 2139 SequentialWriteTest(Connection con, TestOptions options, Status status) { 2140 super(con, options, status); 2141 } 2142 2143 @Override 2144 void testRow(final int i) throws IOException { 2145 byte[] row = format(i); 2146 Put put = new Put(row); 2147 for (int family = 0; family < opts.families; family++) { 2148 byte familyName[] = Bytes.toBytes(FAMILY_NAME_BASE + family); 2149 for (int column = 0; column < opts.columns; column++) { 2150 byte [] qualifier = column == 0? COLUMN_ZERO: Bytes.toBytes("" + column); 2151 byte[] value = generateData(this.rand, getValueLength(this.rand)); 2152 if (opts.useTags) { 2153 byte[] tag = generateData(this.rand, TAG_LENGTH); 2154 Tag[] tags = new Tag[opts.noOfTags]; 2155 for (int n = 0; n < opts.noOfTags; n++) { 2156 Tag t = new ArrayBackedTag((byte) n, tag); 2157 tags[n] = t; 2158 } 2159 KeyValue kv = new KeyValue(row, familyName, qualifier, HConstants.LATEST_TIMESTAMP, 2160 value, tags); 2161 put.add(kv); 2162 updateValueSize(kv.getValueLength()); 2163 } else { 2164 put.addColumn(familyName, qualifier, value); 2165 updateValueSize(value.length); 2166 } 2167 } 2168 } 2169 put.setDurability(opts.writeToWAL ? Durability.SYNC_WAL : Durability.SKIP_WAL); 2170 if (opts.autoFlush) { 2171 table.put(put); 2172 } else { 2173 mutator.mutate(put); 2174 } 2175 } 2176 } 2177 2178 static class FilteredScanTest extends TableTest { 2179 protected static final Logger LOG = LoggerFactory.getLogger(FilteredScanTest.class.getName()); 2180 2181 FilteredScanTest(Connection con, TestOptions options, Status status) { 2182 super(con, options, status); 2183 } 2184 2185 @Override 2186 void testRow(int i) throws IOException { 2187 byte[] value = generateData(this.rand, getValueLength(this.rand)); 2188 Scan scan = constructScan(value); 2189 ResultScanner scanner = null; 2190 try { 2191 scanner = this.table.getScanner(scan); 2192 for (Result r = null; (r = scanner.next()) != null;) { 2193 updateValueSize(r); 2194 } 2195 } finally { 2196 if (scanner != null) { 2197 updateScanMetrics(scanner.getScanMetrics()); 2198 scanner.close(); 2199 } 2200 } 2201 } 2202 2203 protected Scan constructScan(byte[] valuePrefix) throws IOException { 2204 FilterList list = new FilterList(); 2205 Filter filter = new SingleColumnValueFilter(FAMILY_ZERO, COLUMN_ZERO, 2206 CompareOperator.EQUAL, new BinaryComparator(valuePrefix)); 2207 list.addFilter(filter); 2208 if (opts.filterAll) { 2209 list.addFilter(new FilterAllFilter()); 2210 } 2211 Scan scan = new Scan().setCaching(opts.caching).setCacheBlocks(opts.cacheBlocks) 2212 .setAsyncPrefetch(opts.asyncPrefetch).setReadType(opts.scanReadType) 2213 .setScanMetricsEnabled(true); 2214 if (opts.addColumns) { 2215 for (int column = 0; column < opts.columns; column++) { 2216 byte [] qualifier = column == 0? COLUMN_ZERO: Bytes.toBytes("" + column); 2217 scan.addColumn(FAMILY_ZERO, qualifier); 2218 } 2219 } else { 2220 scan.addFamily(FAMILY_ZERO); 2221 } 2222 scan.setFilter(list); 2223 return scan; 2224 } 2225 } 2226 2227 /** 2228 * Compute a throughput rate in MB/s. 2229 * @param rows Number of records consumed. 2230 * @param timeMs Time taken in milliseconds. 2231 * @return String value with label, ie '123.76 MB/s' 2232 */ 2233 private static String calculateMbps(int rows, long timeMs, final int valueSize, int families, int columns) { 2234 BigDecimal rowSize = BigDecimal.valueOf(ROW_LENGTH + 2235 ((valueSize + (FAMILY_NAME_BASE.length()+1) + COLUMN_ZERO.length) * columns) * families); 2236 BigDecimal mbps = BigDecimal.valueOf(rows).multiply(rowSize, CXT) 2237 .divide(BigDecimal.valueOf(timeMs), CXT).multiply(MS_PER_SEC, CXT) 2238 .divide(BYTES_PER_MB, CXT); 2239 return FMT.format(mbps) + " MB/s"; 2240 } 2241 2242 /* 2243 * Format passed integer. 2244 * @param number 2245 * @return Returns zero-prefixed ROW_LENGTH-byte wide decimal version of passed 2246 * number (Does absolute in case number is negative). 2247 */ 2248 public static byte [] format(final int number) { 2249 byte [] b = new byte[ROW_LENGTH]; 2250 int d = Math.abs(number); 2251 for (int i = b.length - 1; i >= 0; i--) { 2252 b[i] = (byte)((d % 10) + '0'); 2253 d /= 10; 2254 } 2255 return b; 2256 } 2257 2258 /* 2259 * This method takes some time and is done inline uploading data. For 2260 * example, doing the mapfile test, generation of the key and value 2261 * consumes about 30% of CPU time. 2262 * @return Generated random value to insert into a table cell. 2263 */ 2264 public static byte[] generateData(final Random r, int length) { 2265 byte [] b = new byte [length]; 2266 int i; 2267 2268 for(i = 0; i < (length-8); i += 8) { 2269 b[i] = (byte) (65 + r.nextInt(26)); 2270 b[i+1] = b[i]; 2271 b[i+2] = b[i]; 2272 b[i+3] = b[i]; 2273 b[i+4] = b[i]; 2274 b[i+5] = b[i]; 2275 b[i+6] = b[i]; 2276 b[i+7] = b[i]; 2277 } 2278 2279 byte a = (byte) (65 + r.nextInt(26)); 2280 for(; i < length; i++) { 2281 b[i] = a; 2282 } 2283 return b; 2284 } 2285 2286 static byte [] getRandomRow(final Random random, final int totalRows) { 2287 return format(generateRandomRow(random, totalRows)); 2288 } 2289 2290 static int generateRandomRow(final Random random, final int totalRows) { 2291 return random.nextInt(Integer.MAX_VALUE) % totalRows; 2292 } 2293 2294 static RunResult runOneClient(final Class<? extends TestBase> cmd, Configuration conf, 2295 Connection con, AsyncConnection asyncCon, TestOptions opts, final Status status) 2296 throws IOException, InterruptedException { 2297 status.setStatus("Start " + cmd + " at offset " + opts.startRow + " for " 2298 + opts.perClientRunRows + " rows"); 2299 long totalElapsedTime; 2300 2301 final TestBase t; 2302 try { 2303 if (AsyncTest.class.isAssignableFrom(cmd)) { 2304 Class<? extends AsyncTest> newCmd = (Class<? extends AsyncTest>) cmd; 2305 Constructor<? extends AsyncTest> constructor = 2306 newCmd.getDeclaredConstructor(AsyncConnection.class, TestOptions.class, Status.class); 2307 t = constructor.newInstance(asyncCon, opts, status); 2308 } else { 2309 Class<? extends Test> newCmd = (Class<? extends Test>) cmd; 2310 Constructor<? extends Test> constructor = 2311 newCmd.getDeclaredConstructor(Connection.class, TestOptions.class, Status.class); 2312 t = constructor.newInstance(con, opts, status); 2313 } 2314 } catch (NoSuchMethodException e) { 2315 throw new IllegalArgumentException("Invalid command class: " + cmd.getName() 2316 + ". It does not provide a constructor as described by " 2317 + "the javadoc comment. Available constructors are: " 2318 + Arrays.toString(cmd.getConstructors())); 2319 } catch (Exception e) { 2320 throw new IllegalStateException("Failed to construct command class", e); 2321 } 2322 totalElapsedTime = t.test(); 2323 2324 status.setStatus("Finished " + cmd + " in " + totalElapsedTime + 2325 "ms at offset " + opts.startRow + " for " + opts.perClientRunRows + " rows" + 2326 " (" + calculateMbps((int)(opts.perClientRunRows * opts.sampleRate), totalElapsedTime, 2327 getAverageValueLength(opts), opts.families, opts.columns) + ")"); 2328 2329 return new RunResult(totalElapsedTime, t.getLatencyHistogram()); 2330 } 2331 2332 private static int getAverageValueLength(final TestOptions opts) { 2333 return opts.valueRandom? opts.valueSize/2: opts.valueSize; 2334 } 2335 2336 private void runTest(final Class<? extends TestBase> cmd, TestOptions opts) throws IOException, 2337 InterruptedException, ClassNotFoundException, ExecutionException { 2338 // Log the configuration we're going to run with. Uses JSON mapper because lazy. It'll do 2339 // the TestOptions introspection for us and dump the output in a readable format. 2340 LOG.info(cmd.getSimpleName() + " test run options=" + MAPPER.writeValueAsString(opts)); 2341 Admin admin = null; 2342 Connection connection = null; 2343 try { 2344 connection = ConnectionFactory.createConnection(getConf()); 2345 admin = connection.getAdmin(); 2346 checkTable(admin, opts); 2347 } finally { 2348 if (admin != null) admin.close(); 2349 if (connection != null) connection.close(); 2350 } 2351 if (opts.nomapred) { 2352 doLocalClients(opts, getConf()); 2353 } else { 2354 doMapReduce(opts, getConf()); 2355 } 2356 } 2357 2358 protected void printUsage() { 2359 printUsage(this.getClass().getName(), null); 2360 } 2361 2362 protected static void printUsage(final String message) { 2363 printUsage(PerformanceEvaluation.class.getName(), message); 2364 } 2365 2366 protected static void printUsageAndExit(final String message, final int exitCode) { 2367 printUsage(message); 2368 System.exit(exitCode); 2369 } 2370 2371 protected static void printUsage(final String className, final String message) { 2372 if (message != null && message.length() > 0) { 2373 System.err.println(message); 2374 } 2375 System.err.println("Usage: java " + className + " \\"); 2376 System.err.println(" <OPTIONS> [-D<property=value>]* <command> <nclients>"); 2377 System.err.println(); 2378 System.err.println("General Options:"); 2379 System.err.println(" nomapred Run multiple clients using threads " + 2380 "(rather than use mapreduce)"); 2381 System.err.println(" oneCon all the threads share the same connection. Default: False"); 2382 System.err.println(" sampleRate Execute test on a sample of total " + 2383 "rows. Only supported by randomRead. Default: 1.0"); 2384 System.err.println(" period Report every 'period' rows: " + 2385 "Default: opts.perClientRunRows / 10 = " + DEFAULT_OPTS.getPerClientRunRows()/10); 2386 System.err.println(" cycles How many times to cycle the test. Defaults: 1."); 2387 System.err.println(" traceRate Enable HTrace spans. Initiate tracing every N rows. " + 2388 "Default: 0"); 2389 System.err.println(" latency Set to report operation latencies. Default: False"); 2390 System.err.println(" measureAfter Start to measure the latency once 'measureAfter'" + 2391 " rows have been treated. Default: 0"); 2392 System.err.println(" valueSize Pass value size to use: Default: " 2393 + DEFAULT_OPTS.getValueSize()); 2394 System.err.println(" valueRandom Set if we should vary value size between 0 and " + 2395 "'valueSize'; set on read for stats on size: Default: Not set."); 2396 System.err.println(" blockEncoding Block encoding to use. Value should be one of " 2397 + Arrays.toString(DataBlockEncoding.values()) + ". Default: NONE"); 2398 System.err.println(); 2399 System.err.println("Table Creation / Write Tests:"); 2400 System.err.println(" table Alternate table name. Default: 'TestTable'"); 2401 System.err.println(" rows Rows each client runs. Default: " 2402 + DEFAULT_OPTS.getPerClientRunRows() 2403 + ". In case of randomReads and randomSeekScans this could" 2404 + " be specified along with --size to specify the number of rows to be scanned within" 2405 + " the total range specified by the size."); 2406 System.err.println( 2407 " size Total size in GiB. Mutually exclusive with --rows for writes and scans" 2408 + ". But for randomReads and randomSeekScans when you use size with --rows you could" 2409 + " use size to specify the end range and --rows" 2410 + " specifies the number of rows within that range. " + "Default: 1.0."); 2411 System.err.println(" compress Compression type to use (GZ, LZO, ...). Default: 'NONE'"); 2412 System.err.println(" flushCommits Used to determine if the test should flush the table. " + 2413 "Default: false"); 2414 System.err.println(" valueZipf Set if we should vary value size between 0 and " + 2415 "'valueSize' in zipf form: Default: Not set."); 2416 System.err.println(" writeToWAL Set writeToWAL on puts. Default: True"); 2417 System.err.println(" autoFlush Set autoFlush on htable. Default: False"); 2418 System.err.println(" presplit Create presplit table. If a table with same name exists," 2419 + " it'll be deleted and recreated (instead of verifying count of its existing regions). " 2420 + "Recommended for accurate perf analysis (see guide). Default: disabled"); 2421 System.err.println(" usetags Writes tags along with KVs. Use with HFile V3. " + 2422 "Default: false"); 2423 System.err.println(" numoftags Specify the no of tags that would be needed. " + 2424 "This works only if usetags is true. Default: " + DEFAULT_OPTS.noOfTags); 2425 System.err.println(" splitPolicy Specify a custom RegionSplitPolicy for the table."); 2426 System.err.println(" columns Columns to write per row. Default: 1"); 2427 System.err.println(" families Specify number of column families for the table. Default: 1"); 2428 System.err.println(); 2429 System.err.println("Read Tests:"); 2430 System.err.println(" filterAll Helps to filter out all the rows on the server side" 2431 + " there by not returning any thing back to the client. Helps to check the server side" 2432 + " performance. Uses FilterAllFilter internally. "); 2433 System.err.println(" multiGet Batch gets together into groups of N. Only supported " + 2434 "by randomRead. Default: disabled"); 2435 System.err.println(" inmemory Tries to keep the HFiles of the CF " + 2436 "inmemory as far as possible. Not guaranteed that reads are always served " + 2437 "from memory. Default: false"); 2438 System.err.println(" bloomFilter Bloom filter type, one of " 2439 + Arrays.toString(BloomType.values())); 2440 System.err.println(" blockSize Blocksize to use when writing out hfiles. "); 2441 System.err.println(" inmemoryCompaction Makes the column family to do inmemory flushes/compactions. " 2442 + "Uses the CompactingMemstore"); 2443 System.err.println(" addColumns Adds columns to scans/gets explicitly. Default: true"); 2444 System.err.println(" replicas Enable region replica testing. Defaults: 1."); 2445 System.err.println(" randomSleep Do a random sleep before each get between 0 and entered value. Defaults: 0"); 2446 System.err.println(" caching Scan caching to use. Default: 30"); 2447 System.err.println(" asyncPrefetch Enable asyncPrefetch for scan"); 2448 System.err.println(" cacheBlocks Set the cacheBlocks option for scan. Default: true"); 2449 System.err.println(" scanReadType Set the readType option for scan, stream/pread/default. Default: default"); 2450 System.err.println(" bufferSize Set the value of client side buffering. Default: 2MB"); 2451 System.err.println(); 2452 System.err.println(" Note: -D properties will be applied to the conf used. "); 2453 System.err.println(" For example: "); 2454 System.err.println(" -Dmapreduce.output.fileoutputformat.compress=true"); 2455 System.err.println(" -Dmapreduce.task.timeout=60000"); 2456 System.err.println(); 2457 System.err.println("Command:"); 2458 for (CmdDescriptor command : COMMANDS.values()) { 2459 System.err.println(String.format(" %-20s %s", command.getName(), command.getDescription())); 2460 } 2461 System.err.println(); 2462 System.err.println("Args:"); 2463 System.err.println(" nclients Integer. Required. Total number of clients " 2464 + "(and HRegionServers) running. 1 <= value <= 500"); 2465 System.err.println("Examples:"); 2466 System.err.println(" To run a single client doing the default 1M sequentialWrites:"); 2467 System.err.println(" $ hbase " + className + " sequentialWrite 1"); 2468 System.err.println(" To run 10 clients doing increments over ten rows:"); 2469 System.err.println(" $ hbase " + className + " --rows=10 --nomapred increment 10"); 2470 } 2471 2472 /** 2473 * Parse options passed in via an arguments array. Assumes that array has been split 2474 * on white-space and placed into a {@code Queue}. Any unknown arguments will remain 2475 * in the queue at the conclusion of this method call. It's up to the caller to deal 2476 * with these unrecognized arguments. 2477 */ 2478 static TestOptions parseOpts(Queue<String> args) { 2479 TestOptions opts = new TestOptions(); 2480 2481 String cmd = null; 2482 while ((cmd = args.poll()) != null) { 2483 if (cmd.equals("-h") || cmd.startsWith("--h")) { 2484 // place item back onto queue so that caller knows parsing was incomplete 2485 args.add(cmd); 2486 break; 2487 } 2488 2489 final String nmr = "--nomapred"; 2490 if (cmd.startsWith(nmr)) { 2491 opts.nomapred = true; 2492 continue; 2493 } 2494 2495 final String rows = "--rows="; 2496 if (cmd.startsWith(rows)) { 2497 opts.perClientRunRows = Integer.parseInt(cmd.substring(rows.length())); 2498 continue; 2499 } 2500 2501 final String cycles = "--cycles="; 2502 if (cmd.startsWith(cycles)) { 2503 opts.cycles = Integer.parseInt(cmd.substring(cycles.length())); 2504 continue; 2505 } 2506 2507 final String sampleRate = "--sampleRate="; 2508 if (cmd.startsWith(sampleRate)) { 2509 opts.sampleRate = Float.parseFloat(cmd.substring(sampleRate.length())); 2510 continue; 2511 } 2512 2513 final String table = "--table="; 2514 if (cmd.startsWith(table)) { 2515 opts.tableName = cmd.substring(table.length()); 2516 continue; 2517 } 2518 2519 final String startRow = "--startRow="; 2520 if (cmd.startsWith(startRow)) { 2521 opts.startRow = Integer.parseInt(cmd.substring(startRow.length())); 2522 continue; 2523 } 2524 2525 final String compress = "--compress="; 2526 if (cmd.startsWith(compress)) { 2527 opts.compression = Compression.Algorithm.valueOf(cmd.substring(compress.length())); 2528 continue; 2529 } 2530 2531 final String traceRate = "--traceRate="; 2532 if (cmd.startsWith(traceRate)) { 2533 opts.traceRate = Double.parseDouble(cmd.substring(traceRate.length())); 2534 continue; 2535 } 2536 2537 final String blockEncoding = "--blockEncoding="; 2538 if (cmd.startsWith(blockEncoding)) { 2539 opts.blockEncoding = DataBlockEncoding.valueOf(cmd.substring(blockEncoding.length())); 2540 continue; 2541 } 2542 2543 final String flushCommits = "--flushCommits="; 2544 if (cmd.startsWith(flushCommits)) { 2545 opts.flushCommits = Boolean.parseBoolean(cmd.substring(flushCommits.length())); 2546 continue; 2547 } 2548 2549 final String writeToWAL = "--writeToWAL="; 2550 if (cmd.startsWith(writeToWAL)) { 2551 opts.writeToWAL = Boolean.parseBoolean(cmd.substring(writeToWAL.length())); 2552 continue; 2553 } 2554 2555 final String presplit = "--presplit="; 2556 if (cmd.startsWith(presplit)) { 2557 opts.presplitRegions = Integer.parseInt(cmd.substring(presplit.length())); 2558 continue; 2559 } 2560 2561 final String inMemory = "--inmemory="; 2562 if (cmd.startsWith(inMemory)) { 2563 opts.inMemoryCF = Boolean.parseBoolean(cmd.substring(inMemory.length())); 2564 continue; 2565 } 2566 2567 final String autoFlush = "--autoFlush="; 2568 if (cmd.startsWith(autoFlush)) { 2569 opts.autoFlush = Boolean.parseBoolean(cmd.substring(autoFlush.length())); 2570 continue; 2571 } 2572 2573 final String onceCon = "--oneCon="; 2574 if (cmd.startsWith(onceCon)) { 2575 opts.oneCon = Boolean.parseBoolean(cmd.substring(onceCon.length())); 2576 continue; 2577 } 2578 2579 final String latency = "--latency"; 2580 if (cmd.startsWith(latency)) { 2581 opts.reportLatency = true; 2582 continue; 2583 } 2584 2585 final String multiGet = "--multiGet="; 2586 if (cmd.startsWith(multiGet)) { 2587 opts.multiGet = Integer.parseInt(cmd.substring(multiGet.length())); 2588 continue; 2589 } 2590 2591 final String useTags = "--usetags="; 2592 if (cmd.startsWith(useTags)) { 2593 opts.useTags = Boolean.parseBoolean(cmd.substring(useTags.length())); 2594 continue; 2595 } 2596 2597 final String noOfTags = "--numoftags="; 2598 if (cmd.startsWith(noOfTags)) { 2599 opts.noOfTags = Integer.parseInt(cmd.substring(noOfTags.length())); 2600 continue; 2601 } 2602 2603 final String replicas = "--replicas="; 2604 if (cmd.startsWith(replicas)) { 2605 opts.replicas = Integer.parseInt(cmd.substring(replicas.length())); 2606 continue; 2607 } 2608 2609 final String filterOutAll = "--filterAll"; 2610 if (cmd.startsWith(filterOutAll)) { 2611 opts.filterAll = true; 2612 continue; 2613 } 2614 2615 final String size = "--size="; 2616 if (cmd.startsWith(size)) { 2617 opts.size = Float.parseFloat(cmd.substring(size.length())); 2618 if (opts.size <= 1.0f) throw new IllegalStateException("Size must be > 1; i.e. 1GB"); 2619 continue; 2620 } 2621 2622 final String splitPolicy = "--splitPolicy="; 2623 if (cmd.startsWith(splitPolicy)) { 2624 opts.splitPolicy = cmd.substring(splitPolicy.length()); 2625 continue; 2626 } 2627 2628 final String randomSleep = "--randomSleep="; 2629 if (cmd.startsWith(randomSleep)) { 2630 opts.randomSleep = Integer.parseInt(cmd.substring(randomSleep.length())); 2631 continue; 2632 } 2633 2634 final String measureAfter = "--measureAfter="; 2635 if (cmd.startsWith(measureAfter)) { 2636 opts.measureAfter = Integer.parseInt(cmd.substring(measureAfter.length())); 2637 continue; 2638 } 2639 2640 final String bloomFilter = "--bloomFilter="; 2641 if (cmd.startsWith(bloomFilter)) { 2642 opts.bloomType = BloomType.valueOf(cmd.substring(bloomFilter.length())); 2643 continue; 2644 } 2645 2646 final String blockSize = "--blockSize="; 2647 if(cmd.startsWith(blockSize) ) { 2648 opts.blockSize = Integer.parseInt(cmd.substring(blockSize.length())); 2649 } 2650 2651 final String valueSize = "--valueSize="; 2652 if (cmd.startsWith(valueSize)) { 2653 opts.valueSize = Integer.parseInt(cmd.substring(valueSize.length())); 2654 continue; 2655 } 2656 2657 final String valueRandom = "--valueRandom"; 2658 if (cmd.startsWith(valueRandom)) { 2659 opts.valueRandom = true; 2660 if (opts.valueZipf) { 2661 throw new IllegalStateException("Either valueZipf or valueRandom but not both"); 2662 } 2663 continue; 2664 } 2665 2666 final String valueZipf = "--valueZipf"; 2667 if (cmd.startsWith(valueZipf)) { 2668 opts.valueZipf = true; 2669 if (opts.valueRandom) { 2670 throw new IllegalStateException("Either valueZipf or valueRandom but not both"); 2671 } 2672 continue; 2673 } 2674 2675 final String period = "--period="; 2676 if (cmd.startsWith(period)) { 2677 opts.period = Integer.parseInt(cmd.substring(period.length())); 2678 continue; 2679 } 2680 2681 final String addColumns = "--addColumns="; 2682 if (cmd.startsWith(addColumns)) { 2683 opts.addColumns = Boolean.parseBoolean(cmd.substring(addColumns.length())); 2684 continue; 2685 } 2686 2687 final String inMemoryCompaction = "--inmemoryCompaction="; 2688 if (cmd.startsWith(inMemoryCompaction)) { 2689 opts.inMemoryCompaction = 2690 MemoryCompactionPolicy.valueOf(cmd.substring(inMemoryCompaction.length())); 2691 continue; 2692 } 2693 2694 final String columns = "--columns="; 2695 if (cmd.startsWith(columns)) { 2696 opts.columns = Integer.parseInt(cmd.substring(columns.length())); 2697 continue; 2698 } 2699 2700 final String families = "--families="; 2701 if (cmd.startsWith(families)) { 2702 opts.families = Integer.parseInt(cmd.substring(families.length())); 2703 continue; 2704 } 2705 2706 final String caching = "--caching="; 2707 if (cmd.startsWith(caching)) { 2708 opts.caching = Integer.parseInt(cmd.substring(caching.length())); 2709 continue; 2710 } 2711 2712 final String asyncPrefetch = "--asyncPrefetch"; 2713 if (cmd.startsWith(asyncPrefetch)) { 2714 opts.asyncPrefetch = true; 2715 continue; 2716 } 2717 2718 final String cacheBlocks = "--cacheBlocks="; 2719 if (cmd.startsWith(cacheBlocks)) { 2720 opts.cacheBlocks = Boolean.parseBoolean(cmd.substring(cacheBlocks.length())); 2721 continue; 2722 } 2723 2724 final String scanReadType = "--scanReadType="; 2725 if (cmd.startsWith(scanReadType)) { 2726 opts.scanReadType = 2727 Scan.ReadType.valueOf(cmd.substring(scanReadType.length()).toUpperCase()); 2728 continue; 2729 } 2730 2731 final String bufferSize = "--bufferSize="; 2732 if (cmd.startsWith(bufferSize)) { 2733 opts.bufferSize = Long.parseLong(cmd.substring(bufferSize.length())); 2734 continue; 2735 } 2736 2737 if (isCommandClass(cmd)) { 2738 opts.cmdName = cmd; 2739 try { 2740 opts.numClientThreads = Integer.parseInt(args.remove()); 2741 } catch (NoSuchElementException | NumberFormatException e) { 2742 throw new IllegalArgumentException("Command " + cmd + " does not have threads number", e); 2743 } 2744 opts = calculateRowsAndSize(opts); 2745 break; 2746 } else { 2747 printUsageAndExit("ERROR: Unrecognized option/command: " + cmd, -1); 2748 } 2749 2750 // Not matching any option or command. 2751 System.err.println("Error: Wrong option or command: " + cmd); 2752 args.add(cmd); 2753 break; 2754 } 2755 return opts; 2756 } 2757 2758 static TestOptions calculateRowsAndSize(final TestOptions opts) { 2759 int rowsPerGB = getRowsPerGB(opts); 2760 if ((opts.getCmdName() != null 2761 && (opts.getCmdName().equals(RANDOM_READ) || opts.getCmdName().equals(RANDOM_SEEK_SCAN))) 2762 && opts.size != DEFAULT_OPTS.size 2763 && opts.perClientRunRows != DEFAULT_OPTS.perClientRunRows) { 2764 opts.totalRows = (int) opts.size * rowsPerGB; 2765 } else if (opts.size != DEFAULT_OPTS.size) { 2766 // total size in GB specified 2767 opts.totalRows = (int) opts.size * rowsPerGB; 2768 opts.perClientRunRows = opts.totalRows / opts.numClientThreads; 2769 } else { 2770 opts.totalRows = opts.perClientRunRows * opts.numClientThreads; 2771 opts.size = opts.totalRows / rowsPerGB; 2772 } 2773 return opts; 2774 } 2775 2776 static int getRowsPerGB(final TestOptions opts) { 2777 return ONE_GB / ((opts.valueRandom? opts.valueSize/2: opts.valueSize) * opts.getFamilies() * 2778 opts.getColumns()); 2779 } 2780 2781 @Override 2782 public int run(String[] args) throws Exception { 2783 // Process command-line args. TODO: Better cmd-line processing 2784 // (but hopefully something not as painful as cli options). 2785 int errCode = -1; 2786 if (args.length < 1) { 2787 printUsage(); 2788 return errCode; 2789 } 2790 2791 try { 2792 LinkedList<String> argv = new LinkedList<>(); 2793 argv.addAll(Arrays.asList(args)); 2794 TestOptions opts = parseOpts(argv); 2795 2796 // args remaining, print help and exit 2797 if (!argv.isEmpty()) { 2798 errCode = 0; 2799 printUsage(); 2800 return errCode; 2801 } 2802 2803 // must run at least 1 client 2804 if (opts.numClientThreads <= 0) { 2805 throw new IllegalArgumentException("Number of clients must be > 0"); 2806 } 2807 2808 // cmdName should not be null, print help and exit 2809 if (opts.cmdName == null) { 2810 printUsage(); 2811 return errCode; 2812 } 2813 2814 Class<? extends TestBase> cmdClass = determineCommandClass(opts.cmdName); 2815 if (cmdClass != null) { 2816 runTest(cmdClass, opts); 2817 errCode = 0; 2818 } 2819 2820 } catch (Exception e) { 2821 e.printStackTrace(); 2822 } 2823 2824 return errCode; 2825 } 2826 2827 private static boolean isCommandClass(String cmd) { 2828 return COMMANDS.containsKey(cmd); 2829 } 2830 2831 private static Class<? extends TestBase> determineCommandClass(String cmd) { 2832 CmdDescriptor descriptor = COMMANDS.get(cmd); 2833 return descriptor != null ? descriptor.getCmdClass() : null; 2834 } 2835 2836 public static void main(final String[] args) throws Exception { 2837 int res = ToolRunner.run(new PerformanceEvaluation(HBaseConfiguration.create()), args); 2838 System.exit(res); 2839 } 2840}