001/*
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *     http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018
019package org.apache.hadoop.hbase.wal;
020
021import static com.codahale.metrics.MetricRegistry.name;
022
023import com.codahale.metrics.ConsoleReporter;
024import com.codahale.metrics.Histogram;
025import com.codahale.metrics.Meter;
026import com.codahale.metrics.MetricFilter;
027import com.codahale.metrics.MetricRegistry;
028import java.io.IOException;
029import java.util.HashMap;
030import java.util.HashSet;
031import java.util.List;
032import java.util.Map;
033import java.util.NavigableMap;
034import java.util.Random;
035import java.util.Set;
036import java.util.TreeMap;
037import java.util.concurrent.TimeUnit;
038import java.util.stream.IntStream;
039import org.apache.hadoop.conf.Configuration;
040import org.apache.hadoop.conf.Configured;
041import org.apache.hadoop.fs.FileStatus;
042import org.apache.hadoop.fs.FileSystem;
043import org.apache.hadoop.fs.Path;
044import org.apache.hadoop.hbase.Cell;
045import org.apache.hadoop.hbase.HBaseConfiguration;
046import org.apache.hadoop.hbase.HBaseTestingUtility;
047import org.apache.hadoop.hbase.HConstants;
048import org.apache.hadoop.hbase.MockRegionServerServices;
049import org.apache.hadoop.hbase.TableName;
050import org.apache.hadoop.hbase.client.ColumnFamilyDescriptorBuilder;
051import org.apache.hadoop.hbase.client.Put;
052import org.apache.hadoop.hbase.client.RegionInfo;
053import org.apache.hadoop.hbase.client.RegionInfoBuilder;
054import org.apache.hadoop.hbase.client.TableDescriptor;
055import org.apache.hadoop.hbase.client.TableDescriptorBuilder;
056import org.apache.hadoop.hbase.io.crypto.KeyProviderForTesting;
057import org.apache.hadoop.hbase.regionserver.HRegion;
058import org.apache.hadoop.hbase.regionserver.LogRoller;
059import org.apache.hadoop.hbase.regionserver.MultiVersionConcurrencyControl;
060import org.apache.hadoop.hbase.regionserver.wal.SecureProtobufLogReader;
061import org.apache.hadoop.hbase.regionserver.wal.SecureProtobufLogWriter;
062import org.apache.hadoop.hbase.regionserver.wal.WALActionsListener;
063import org.apache.hadoop.hbase.trace.HBaseHTraceConfiguration;
064import org.apache.hadoop.hbase.trace.SpanReceiverHost;
065import org.apache.hadoop.hbase.trace.TraceUtil;
066import org.apache.hadoop.hbase.util.Bytes;
067import org.apache.hadoop.hbase.util.FSUtils;
068import org.apache.hadoop.hbase.util.Threads;
069import org.apache.hadoop.hbase.wal.WALProvider.Writer;
070import org.apache.hadoop.util.Tool;
071import org.apache.hadoop.util.ToolRunner;
072import org.apache.htrace.core.ProbabilitySampler;
073import org.apache.htrace.core.Sampler;
074import org.apache.htrace.core.TraceScope;
075import org.apache.htrace.core.Tracer;
076import org.apache.yetus.audience.InterfaceAudience;
077import org.slf4j.Logger;
078import org.slf4j.LoggerFactory;
079
080// imports for things that haven't moved from regionserver.wal yet.
081
082/**
083 * This class runs performance benchmarks for {@link WAL}.
084 * See usage for this tool by running:
085 * <code>$ hbase org.apache.hadoop.hbase.wal.WALPerformanceEvaluation -h</code>
086 */
087@InterfaceAudience.Private
088public final class WALPerformanceEvaluation extends Configured implements Tool {
089  private static final Logger LOG =
090      LoggerFactory.getLogger(WALPerformanceEvaluation.class);
091
092  private final MetricRegistry metrics = new MetricRegistry();
093  private final Meter syncMeter =
094    metrics.meter(name(WALPerformanceEvaluation.class, "syncMeter", "syncs"));
095
096  private final Histogram syncHistogram = metrics.histogram(
097    name(WALPerformanceEvaluation.class, "syncHistogram", "nanos-between-syncs"));
098  private final Histogram syncCountHistogram = metrics.histogram(
099    name(WALPerformanceEvaluation.class, "syncCountHistogram", "countPerSync"));
100  private final Meter appendMeter = metrics.meter(
101    name(WALPerformanceEvaluation.class, "appendMeter", "bytes"));
102  private final Histogram latencyHistogram =
103    metrics.histogram(name(WALPerformanceEvaluation.class, "latencyHistogram", "nanos"));
104
105  private final MultiVersionConcurrencyControl mvcc = new MultiVersionConcurrencyControl();
106
107  private HBaseTestingUtility TEST_UTIL;
108
109  static final String TABLE_NAME = "WALPerformanceEvaluation";
110  static final String QUALIFIER_PREFIX = "q";
111  static final String FAMILY_PREFIX = "cf";
112
113  private int numQualifiers = 1;
114  private int valueSize = 512;
115  private int keySize = 16;
116
117  @Override
118  public void setConf(Configuration conf) {
119    super.setConf(conf);
120    TEST_UTIL = new HBaseTestingUtility(conf);
121  }
122
123  /**
124   * Perform WAL.append() of Put object, for the number of iterations requested.
125   * Keys and Vaues are generated randomly, the number of column families,
126   * qualifiers and key/value size is tunable by the user.
127   */
128  class WALPutBenchmark implements Runnable {
129    private final long numIterations;
130    private final int numFamilies;
131    private final boolean noSync;
132    private final HRegion region;
133    private final int syncInterval;
134    private final Sampler loopSampler;
135    private final NavigableMap<byte[], Integer> scopes;
136
137    WALPutBenchmark(final HRegion region, final TableDescriptor htd,
138        final long numIterations, final boolean noSync, final int syncInterval,
139        final double traceFreq) {
140      this.numIterations = numIterations;
141      this.noSync = noSync;
142      this.syncInterval = syncInterval;
143      this.numFamilies = htd.getColumnFamilyCount();
144      this.region = region;
145      scopes = new TreeMap<>(Bytes.BYTES_COMPARATOR);
146      for(byte[] fam : htd.getColumnFamilyNames()) {
147        scopes.put(fam, 0);
148      }
149      String spanReceivers = getConf().get("hbase.trace.spanreceiver.classes");
150      if (spanReceivers == null || spanReceivers.isEmpty()) {
151        loopSampler = Sampler.NEVER;
152      } else {
153        if (traceFreq <= 0.0) {
154          LOG.warn("Tracing enabled but traceFreq=0.");
155          loopSampler = Sampler.NEVER;
156        } else if (traceFreq >= 1.0) {
157          loopSampler = Sampler.ALWAYS;
158          if (numIterations > 1000) {
159            LOG.warn("Full tracing of all iterations will produce a lot of data. Be sure your"
160              + " SpanReceiver can keep up.");
161          }
162        } else {
163          getConf().setDouble("hbase.sampler.fraction", traceFreq);
164          loopSampler = new ProbabilitySampler(new HBaseHTraceConfiguration(getConf()));
165        }
166      }
167    }
168
169    @Override
170    public void run() {
171      byte[] key = new byte[keySize];
172      byte[] value = new byte[valueSize];
173      Random rand = new Random(Thread.currentThread().getId());
174      WAL wal = region.getWAL();
175
176      try (TraceScope threadScope = TraceUtil.createTrace("WALPerfEval." + Thread.currentThread().getName())) {
177        long startTime = System.currentTimeMillis();
178        int lastSync = 0;
179        TraceUtil.addSampler(loopSampler);
180        for (int i = 0; i < numIterations; ++i) {
181          assert Tracer.getCurrentSpan() == threadScope.getSpan() : "Span leak detected.";
182          try (TraceScope loopScope = TraceUtil.createTrace("runLoopIter" + i)) {
183            long now = System.nanoTime();
184            Put put = setupPut(rand, key, value, numFamilies);
185            WALEdit walEdit = new WALEdit();
186            addFamilyMapToWALEdit(put.getFamilyCellMap(), walEdit);
187            RegionInfo hri = region.getRegionInfo();
188            final WALKeyImpl logkey =
189                new WALKeyImpl(hri.getEncodedNameAsBytes(), hri.getTable(), now, mvcc, scopes);
190            wal.append(hri, logkey, walEdit, true);
191            if (!this.noSync) {
192              if (++lastSync >= this.syncInterval) {
193                wal.sync();
194                lastSync = 0;
195              }
196            }
197            latencyHistogram.update(System.nanoTime() - now);
198          }
199        }
200      } catch (Exception e) {
201        LOG.error(getClass().getSimpleName() + " Thread failed", e);
202      }
203    }
204  }
205
206  @Override
207  public int run(String[] args) throws Exception {
208    Path rootRegionDir = null;
209    int numThreads = 1;
210    long numIterations = 1000000;
211    int numFamilies = 1;
212    int syncInterval = 0;
213    boolean noSync = false;
214    boolean verify = false;
215    boolean verbose = false;
216    boolean cleanup = true;
217    boolean noclosefs = false;
218    long roll = Long.MAX_VALUE;
219    boolean compress = false;
220    String cipher = null;
221    int numRegions = 1;
222    String spanReceivers = getConf().get("hbase.trace.spanreceiver.classes");
223    boolean trace = spanReceivers != null && !spanReceivers.isEmpty();
224    double traceFreq = 1.0;
225    // Process command line args
226    for (int i = 0; i < args.length; i++) {
227      String cmd = args[i];
228      try {
229        if (cmd.equals("-threads")) {
230          numThreads = Integer.parseInt(args[++i]);
231        } else if (cmd.equals("-iterations")) {
232          numIterations = Long.parseLong(args[++i]);
233        } else if (cmd.equals("-path")) {
234          rootRegionDir = new Path(args[++i]);
235        } else if (cmd.equals("-families")) {
236          numFamilies = Integer.parseInt(args[++i]);
237        } else if (cmd.equals("-qualifiers")) {
238          numQualifiers = Integer.parseInt(args[++i]);
239        } else if (cmd.equals("-keySize")) {
240          keySize = Integer.parseInt(args[++i]);
241        } else if (cmd.equals("-valueSize")) {
242          valueSize = Integer.parseInt(args[++i]);
243        } else if (cmd.equals("-syncInterval")) {
244          syncInterval = Integer.parseInt(args[++i]);
245        } else if (cmd.equals("-nosync")) {
246          noSync = true;
247        } else if (cmd.equals("-verify")) {
248          verify = true;
249        } else if (cmd.equals("-verbose")) {
250          verbose = true;
251        } else if (cmd.equals("-nocleanup")) {
252          cleanup = false;
253        } else if (cmd.equals("-noclosefs")) {
254          noclosefs = true;
255        } else if (cmd.equals("-roll")) {
256          roll = Long.parseLong(args[++i]);
257        } else if (cmd.equals("-compress")) {
258          compress = true;
259        } else if (cmd.equals("-encryption")) {
260          cipher = args[++i];
261        } else if (cmd.equals("-regions")) {
262          numRegions = Integer.parseInt(args[++i]);
263        } else if (cmd.equals("-traceFreq")) {
264          traceFreq = Double.parseDouble(args[++i]);
265        } else if (cmd.equals("-h")) {
266          printUsageAndExit();
267        } else if (cmd.equals("--help")) {
268          printUsageAndExit();
269        } else {
270          System.err.println("UNEXPECTED: " + cmd);
271          printUsageAndExit();
272        }
273      } catch (Exception e) {
274        printUsageAndExit();
275      }
276    }
277
278    if (compress) {
279      Configuration conf = getConf();
280      conf.setBoolean(HConstants.ENABLE_WAL_COMPRESSION, true);
281    }
282
283    if (cipher != null) {
284      // Set up WAL for encryption
285      Configuration conf = getConf();
286      conf.set(HConstants.CRYPTO_KEYPROVIDER_CONF_KEY, KeyProviderForTesting.class.getName());
287      conf.set(HConstants.CRYPTO_MASTERKEY_NAME_CONF_KEY, "hbase");
288      conf.setClass("hbase.regionserver.hlog.reader.impl", SecureProtobufLogReader.class,
289        WAL.Reader.class);
290      conf.setClass("hbase.regionserver.hlog.writer.impl", SecureProtobufLogWriter.class,
291        Writer.class);
292      conf.setBoolean(HConstants.ENABLE_WAL_ENCRYPTION, true);
293      conf.set(HConstants.CRYPTO_WAL_ALGORITHM_CONF_KEY, cipher);
294    }
295
296    if (numThreads < numRegions) {
297      LOG.warn("Number of threads is less than the number of regions; some regions will sit idle.");
298    }
299
300    // Internal config. goes off number of threads; if more threads than handlers, stuff breaks.
301    // In regionserver, number of handlers == number of threads.
302    getConf().setInt(HConstants.REGION_SERVER_HANDLER_COUNT, numThreads);
303
304    // Run WAL Performance Evaluation
305    // First set the fs from configs.  In case we are on hadoop1
306    FSUtils.setFsDefault(getConf(), FSUtils.getRootDir(getConf()));
307    FileSystem fs = FileSystem.get(getConf());
308    LOG.info("FileSystem: " + fs);
309
310    SpanReceiverHost receiverHost = trace ? SpanReceiverHost.getInstance(getConf()) : null;
311    final Sampler sampler = trace ? Sampler.ALWAYS : Sampler.NEVER;
312    TraceUtil.addSampler(sampler);
313    TraceScope scope = TraceUtil.createTrace("WALPerfEval");
314
315    try {
316      if (rootRegionDir == null) {
317        rootRegionDir = TEST_UTIL.getDataTestDirOnTestFS("WALPerformanceEvaluation");
318      }
319      rootRegionDir = rootRegionDir.makeQualified(fs.getUri(), fs.getWorkingDirectory());
320      cleanRegionRootDir(fs, rootRegionDir);
321      FSUtils.setRootDir(getConf(), rootRegionDir);
322      final WALFactory wals = new WALFactory(getConf(), "wals");
323      final HRegion[] regions = new HRegion[numRegions];
324      final Runnable[] benchmarks = new Runnable[numRegions];
325      final MockRegionServerServices mockServices = new MockRegionServerServices(getConf());
326      final LogRoller roller = new LogRoller(mockServices, mockServices);
327      Threads.setDaemonThreadRunning(roller.getThread(), "WALPerfEval.logRoller");
328
329      try {
330        for(int i = 0; i < numRegions; i++) {
331          // Initialize Table Descriptor
332          // a table per desired region means we can avoid carving up the key space
333          final TableDescriptor htd = createHTableDescriptor(i, numFamilies);
334          regions[i] = openRegion(fs, rootRegionDir, htd, wals, roll, roller);
335          benchmarks[i] = TraceUtil.wrap(new WALPutBenchmark(regions[i], htd, numIterations, noSync,
336              syncInterval, traceFreq), "");
337        }
338        ConsoleReporter reporter = ConsoleReporter.forRegistry(metrics).
339          outputTo(System.out).convertRatesTo(TimeUnit.SECONDS).filter(MetricFilter.ALL).build();
340        reporter.start(30, TimeUnit.SECONDS);
341
342        long putTime = runBenchmark(benchmarks, numThreads);
343        logBenchmarkResult("Summary: threads=" + numThreads + ", iterations=" + numIterations +
344          ", syncInterval=" + syncInterval, numIterations * numThreads, putTime);
345
346        for (int i = 0; i < numRegions; i++) {
347          if (regions[i] != null) {
348            closeRegion(regions[i]);
349            regions[i] = null;
350          }
351        }
352        if (verify) {
353          LOG.info("verifying written log entries.");
354          Path dir = new Path(FSUtils.getRootDir(getConf()),
355            AbstractFSWALProvider.getWALDirectoryName("wals"));
356          long editCount = 0;
357          FileStatus [] fsss = fs.listStatus(dir);
358          if (fsss.length == 0) throw new IllegalStateException("No WAL found");
359          for (FileStatus fss: fsss) {
360            Path p = fss.getPath();
361            if (!fs.exists(p)) throw new IllegalStateException(p.toString());
362            editCount += verify(wals, p, verbose);
363          }
364          long expected = numIterations * numThreads;
365          if (editCount != expected) {
366            throw new IllegalStateException("Counted=" + editCount + ", expected=" + expected);
367          }
368        }
369      } finally {
370        mockServices.stop("test clean up.");
371        for (int i = 0; i < numRegions; i++) {
372          if (regions[i] != null) {
373            closeRegion(regions[i]);
374          }
375        }
376        if (null != roller) {
377          LOG.info("shutting down log roller.");
378          roller.close();
379        }
380        wals.shutdown();
381        // Remove the root dir for this test region
382        if (cleanup) cleanRegionRootDir(fs, rootRegionDir);
383      }
384    } finally {
385      // We may be called inside a test that wants to keep on using the fs.
386      if (!noclosefs) {
387        fs.close();
388      }
389      if (scope != null) {
390        scope.close();
391      }
392      if (receiverHost != null) {
393        receiverHost.closeReceivers();
394      }
395    }
396
397    return(0);
398  }
399
400  private static TableDescriptor createHTableDescriptor(final int regionNum,
401      final int numFamilies) {
402    TableDescriptorBuilder builder =
403        TableDescriptorBuilder.newBuilder(TableName.valueOf(TABLE_NAME + ":" + regionNum));
404    IntStream.range(0, numFamilies)
405        .mapToObj(i -> ColumnFamilyDescriptorBuilder.of(FAMILY_PREFIX + i))
406        .forEachOrdered(builder::setColumnFamily);
407    return builder.build();
408  }
409
410  /**
411   * Verify the content of the WAL file.
412   * Verify that the file has expected number of edits.
413   * @param wals may not be null
414   * @param wal
415   * @return Count of edits.
416   * @throws IOException
417   */
418  private long verify(final WALFactory wals, final Path wal, final boolean verbose)
419      throws IOException {
420    WAL.Reader reader = wals.createReader(wal.getFileSystem(getConf()), wal);
421    long count = 0;
422    Map<String, Long> sequenceIds = new HashMap<>();
423    try {
424      while (true) {
425        WAL.Entry e = reader.next();
426        if (e == null) {
427          LOG.debug("Read count=" + count + " from " + wal);
428          break;
429        }
430        count++;
431        long seqid = e.getKey().getSequenceId();
432        if (sequenceIds.containsKey(Bytes.toString(e.getKey().getEncodedRegionName()))) {
433          // sequenceIds should be increasing for every regions
434          if (sequenceIds.get(Bytes.toString(e.getKey().getEncodedRegionName())) >= seqid) {
435            throw new IllegalStateException("wal = " + wal.getName() + ", " + "previous seqid = "
436                + sequenceIds.get(Bytes.toString(e.getKey().getEncodedRegionName()))
437                + ", current seqid = " + seqid);
438          }
439        }
440        // update the sequence Id.
441        sequenceIds.put(Bytes.toString(e.getKey().getEncodedRegionName()), seqid);
442        if (verbose) LOG.info("seqid=" + seqid);
443      }
444    } finally {
445      reader.close();
446    }
447    return count;
448  }
449
450  private static void logBenchmarkResult(String testName, long numTests, long totalTime) {
451    float tsec = totalTime / 1000.0f;
452    LOG.info(String.format("%s took %.3fs %.3fops/s", testName, tsec, numTests / tsec));
453
454  }
455
456  private void printUsageAndExit() {
457    System.err.printf("Usage: hbase %s [options]\n", getClass().getName());
458    System.err.println(" where [options] are:");
459    System.err.println("  -h|-help         Show this help and exit.");
460    System.err.println("  -threads <N>     Number of threads writing on the WAL.");
461    System.err.println("  -regions <N>     Number of regions to open in the WAL. Default: 1");
462    System.err.println("  -iterations <N>  Number of iterations per thread.");
463    System.err.println("  -path <PATH>     Path where region's root directory is created.");
464    System.err.println("  -families <N>    Number of column families to write.");
465    System.err.println("  -qualifiers <N>  Number of qualifiers to write.");
466    System.err.println("  -keySize <N>     Row key size in byte.");
467    System.err.println("  -valueSize <N>   Row/Col value size in byte.");
468    System.err.println("  -nocleanup       Do NOT remove test data when done.");
469    System.err.println("  -noclosefs       Do NOT close the filesystem when done.");
470    System.err.println("  -nosync          Append without syncing");
471    System.err.println("  -syncInterval <N> Append N edits and then sync. " +
472      "Default=0, i.e. sync every edit.");
473    System.err.println("  -verify          Verify edits written in sequence");
474    System.err.println("  -verbose         Output extra info; " +
475      "e.g. all edit seq ids when verifying");
476    System.err.println("  -roll <N>        Roll the way every N appends");
477    System.err.println("  -encryption <A>  Encrypt the WAL with algorithm A, e.g. AES");
478    System.err.println("  -traceFreq <N>   Rate of trace sampling. Default: 1.0, " +
479      "only respected when tracing is enabled, ie -Dhbase.trace.spanreceiver.classes=...");
480    System.err.println("");
481    System.err.println("Examples:");
482    System.err.println("");
483    System.err.println(" To run 100 threads on hdfs with log rolling every 10k edits and " +
484      "verification afterward do:");
485    System.err.println(" $ hbase org.apache.hadoop.hbase.wal." +
486      "WALPerformanceEvaluation \\");
487    System.err.println("    -conf ./core-site.xml -path hdfs://example.org:7000/tmp " +
488      "-threads 100 -roll 10000 -verify");
489    System.exit(1);
490  }
491
492  private final Set<WAL> walsListenedTo = new HashSet<>();
493
494  private HRegion openRegion(final FileSystem fs, final Path dir, final TableDescriptor htd,
495      final WALFactory wals, final long whenToRoll, final LogRoller roller) throws IOException {
496    // Initialize HRegion
497    RegionInfo regionInfo = RegionInfoBuilder.newBuilder(htd.getTableName()).build();
498    // Initialize WAL
499    final WAL wal = wals.getWAL(regionInfo);
500    // If we haven't already, attach a listener to this wal to handle rolls and metrics.
501    if (walsListenedTo.add(wal)) {
502      roller.addWAL(wal);
503      wal.registerWALActionsListener(new WALActionsListener() {
504        private int appends = 0;
505
506        @Override
507        public void visitLogEntryBeforeWrite(WALKey logKey, WALEdit logEdit) {
508          this.appends++;
509          if (this.appends % whenToRoll == 0) {
510            LOG.info("Rolling after " + appends + " edits");
511            // We used to do explicit call to rollWriter but changed it to a request
512            // to avoid dead lock (there are less threads going on in this class than
513            // in the regionserver -- regionserver does not have the issue).
514            AbstractFSWALProvider.requestLogRoll(wal);
515          }
516        }
517
518        @Override
519        public void postSync(final long timeInNanos, final int handlerSyncs) {
520          syncMeter.mark();
521          syncHistogram.update(timeInNanos);
522          syncCountHistogram.update(handlerSyncs);
523        }
524
525        @Override
526        public void postAppend(final long size, final long elapsedTime, final WALKey logkey,
527            final WALEdit logEdit) {
528          appendMeter.mark(size);
529        }
530      });
531    }
532
533    return HRegion.createHRegion(regionInfo, dir, getConf(), htd, wal);
534  }
535
536  private void closeRegion(final HRegion region) throws IOException {
537    if (region != null) {
538      region.close();
539      WAL wal = region.getWAL();
540      if (wal != null) {
541        wal.shutdown();
542      }
543    }
544  }
545
546  private void cleanRegionRootDir(final FileSystem fs, final Path dir) throws IOException {
547    if (fs.exists(dir)) {
548      fs.delete(dir, true);
549    }
550  }
551
552  private Put setupPut(Random rand, byte[] key, byte[] value, final int numFamilies) {
553    rand.nextBytes(key);
554    Put put = new Put(key);
555    for (int cf = 0; cf < numFamilies; ++cf) {
556      for (int q = 0; q < numQualifiers; ++q) {
557        rand.nextBytes(value);
558        put.addColumn(Bytes.toBytes(FAMILY_PREFIX + cf),
559            Bytes.toBytes(QUALIFIER_PREFIX + q), value);
560      }
561    }
562    return put;
563  }
564
565  private void addFamilyMapToWALEdit(Map<byte[], List<Cell>> familyMap,
566      WALEdit walEdit) {
567    for (List<Cell> edits : familyMap.values()) {
568      for (Cell cell : edits) {
569        walEdit.add(cell);
570      }
571    }
572  }
573
574  private long runBenchmark(Runnable[] runnable, final int numThreads) throws InterruptedException {
575    Thread[] threads = new Thread[numThreads];
576    long startTime = System.currentTimeMillis();
577    for (int i = 0; i < numThreads; ++i) {
578      threads[i] = new Thread(runnable[i%runnable.length], "t" + i + ",r" + (i%runnable.length));
579      threads[i].start();
580    }
581    for (Thread t : threads) t.join();
582    long endTime = System.currentTimeMillis();
583    return(endTime - startTime);
584  }
585
586  /**
587   * The guts of the {@link #main} method.
588   * Call this method to avoid the {@link #main(String[])} System.exit.
589   * @param args
590   * @return errCode
591   * @throws Exception
592   */
593  static int innerMain(final Configuration c, final String [] args) throws Exception {
594    return ToolRunner.run(c, new WALPerformanceEvaluation(), args);
595  }
596
597  public static void main(String[] args) throws Exception {
598     System.exit(innerMain(HBaseConfiguration.create(), args));
599  }
600}