View Javadoc

1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements. See the NOTICE file distributed with this
4    * work for additional information regarding copyright ownership. The ASF
5    * licenses this file to you under the Apache License, Version 2.0 (the
6    * "License"); you may not use this file except in compliance with the License.
7    * You may obtain a copy of the License at
8    *
9    * http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
13   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
14   * License for the specific language governing permissions and limitations
15   * under the License.
16   */
17  package org.apache.hadoop.hbase.util;
18  
19  import java.io.IOException;
20  import java.io.InterruptedIOException;
21  import java.lang.reflect.Constructor;
22  import java.net.InetAddress;
23  import java.security.SecureRandom;
24  import java.util.ArrayList;
25  import java.util.Arrays;
26  import java.util.List;
27  import java.util.Locale;
28  import java.util.Properties;
29  import java.util.Random;
30  import java.util.concurrent.atomic.AtomicReference;
31  
32  import javax.crypto.spec.SecretKeySpec;
33  
34  import org.apache.commons.cli.CommandLine;
35  import org.apache.commons.logging.Log;
36  import org.apache.commons.logging.LogFactory;
37  import org.apache.hadoop.conf.Configuration;
38  import org.apache.hadoop.hbase.HBaseConfiguration;
39  import org.apache.hadoop.hbase.HBaseInterfaceAudience;
40  import org.apache.hadoop.hbase.HBaseTestingUtility;
41  import org.apache.hadoop.hbase.HColumnDescriptor;
42  import org.apache.hadoop.hbase.HConstants;
43  import org.apache.hadoop.hbase.HTableDescriptor;
44  import org.apache.hadoop.hbase.TableName;
45  import org.apache.hadoop.hbase.classification.InterfaceAudience;
46  import org.apache.hadoop.hbase.client.Admin;
47  import org.apache.hadoop.hbase.client.ConnectionFactory;
48  import org.apache.hadoop.hbase.client.Durability;
49  import org.apache.hadoop.hbase.client.HBaseAdmin;
50  import org.apache.hadoop.hbase.io.compress.Compression;
51  import org.apache.hadoop.hbase.io.crypto.Cipher;
52  import org.apache.hadoop.hbase.io.crypto.Encryption;
53  import org.apache.hadoop.hbase.io.encoding.DataBlockEncoding;
54  import org.apache.hadoop.hbase.regionserver.BloomType;
55  import org.apache.hadoop.hbase.security.EncryptionUtil;
56  import org.apache.hadoop.hbase.security.User;
57  import org.apache.hadoop.hbase.security.access.AccessControlClient;
58  import org.apache.hadoop.hbase.security.access.Permission;
59  import org.apache.hadoop.hbase.util.test.LoadTestDataGenerator;
60  import org.apache.hadoop.hbase.util.test.LoadTestDataGeneratorWithACL;
61  import org.apache.hadoop.security.SecurityUtil;
62  import org.apache.hadoop.security.UserGroupInformation;
63  import org.apache.hadoop.util.ToolRunner;
64  
65  /**
66   * A command-line utility that reads, writes, and verifies data. Unlike
67   * {@link PerformanceEvaluation}, this tool validates the data written,
68   * and supports simultaneously writing and reading the same set of keys.
69   */
70  @InterfaceAudience.LimitedPrivate(HBaseInterfaceAudience.TOOLS)
71  public class LoadTestTool extends AbstractHBaseTool {
72  
73    private static final Log LOG = LogFactory.getLog(LoadTestTool.class);
74    private static final String COLON = ":";
75  
76    /** Table name for the test */
77    private TableName tableName;
78  
79    /** Column families for the test */
80    private byte[][] families;
81  
82    /** Table name to use of not overridden on the command line */
83    protected static final String DEFAULT_TABLE_NAME = "cluster_test";
84  
85    /** Column family used by the test */
86    public static byte[] DEFAULT_COLUMN_FAMILY = Bytes.toBytes("test_cf");
87  
88    /** Column families used by the test */
89    public static final byte[][] DEFAULT_COLUMN_FAMILIES = { DEFAULT_COLUMN_FAMILY };
90  
91    /** The default data size if not specified */
92    protected static final int DEFAULT_DATA_SIZE = 64;
93  
94    /** The number of reader/writer threads if not specified */
95    protected static final int DEFAULT_NUM_THREADS = 20;
96  
97    /** Usage string for the load option */
98    protected static final String OPT_USAGE_LOAD =
99        "<avg_cols_per_key>:<avg_data_size>" +
100       "[:<#threads=" + DEFAULT_NUM_THREADS + ">]";
101 
102   /** Usage string for the read option */
103   protected static final String OPT_USAGE_READ =
104       "<verify_percent>[:<#threads=" + DEFAULT_NUM_THREADS + ">]";
105 
106   /** Usage string for the update option */
107   protected static final String OPT_USAGE_UPDATE =
108       "<update_percent>[:<#threads=" + DEFAULT_NUM_THREADS
109       + ">][:<#whether to ignore nonce collisions=0>]";
110 
111   protected static final String OPT_USAGE_BLOOM = "Bloom filter type, one of " +
112       Arrays.toString(BloomType.values());
113 
114   protected static final String OPT_USAGE_COMPRESSION = "Compression type, " +
115       "one of " + Arrays.toString(Compression.Algorithm.values());
116 
117   public static final String OPT_DATA_BLOCK_ENCODING_USAGE =
118     "Encoding algorithm (e.g. prefix "
119         + "compression) to use for data blocks in the test column family, "
120         + "one of " + Arrays.toString(DataBlockEncoding.values()) + ".";
121 
122   public static final String OPT_BLOOM = "bloom";
123   public static final String OPT_COMPRESSION = "compression";
124   public static final String OPT_DEFERRED_LOG_FLUSH = "deferredlogflush";
125   public static final String OPT_DEFERRED_LOG_FLUSH_USAGE = "Enable deferred log flush.";
126 
127   public static final String OPT_DATA_BLOCK_ENCODING =
128       HColumnDescriptor.DATA_BLOCK_ENCODING.toLowerCase(Locale.ROOT);
129 
130   public static final String OPT_INMEMORY = "in_memory";
131   public static final String OPT_USAGE_IN_MEMORY = "Tries to keep the HFiles of the CF " +
132       "inmemory as far as possible.  Not guaranteed that reads are always served from inmemory";
133 
134   public static final String OPT_GENERATOR = "generator";
135   public static final String OPT_GENERATOR_USAGE = "The class which generates load for the tool."
136       + " Any args for this class can be passed as colon separated after class name";
137 
138   public static final String OPT_WRITER = "writer";
139   public static final String OPT_WRITER_USAGE = "The class for executing the write requests";
140 
141   public static final String OPT_UPDATER = "updater";
142   public static final String OPT_UPDATER_USAGE = "The class for executing the update requests";
143 
144   public static final String OPT_READER = "reader";
145   public static final String OPT_READER_USAGE = "The class for executing the read requests";
146 
147   protected static final String OPT_KEY_WINDOW = "key_window";
148   protected static final String OPT_WRITE = "write";
149   protected static final String OPT_MAX_READ_ERRORS = "max_read_errors";
150   public static final String OPT_MULTIPUT = "multiput";
151   public static final String OPT_MULTIGET = "multiget_batchsize";
152   protected static final String OPT_NUM_KEYS = "num_keys";
153   protected static final String OPT_READ = "read";
154   protected static final String OPT_START_KEY = "start_key";
155   public static final String OPT_TABLE_NAME = "tn";
156   public static final String OPT_COLUMN_FAMILIES = "families";
157   protected static final String OPT_ZK_QUORUM = "zk";
158   protected static final String OPT_ZK_PARENT_NODE = "zk_root";
159   protected static final String OPT_SKIP_INIT = "skip_init";
160   protected static final String OPT_INIT_ONLY = "init_only";
161   protected static final String NUM_TABLES = "num_tables";
162   protected static final String OPT_BATCHUPDATE = "batchupdate";
163   protected static final String OPT_UPDATE = "update";
164 
165   public static final String OPT_ENCRYPTION = "encryption";
166   protected static final String OPT_ENCRYPTION_USAGE =
167     "Enables transparent encryption on the test table, one of " +
168     Arrays.toString(Encryption.getSupportedCiphers());
169 
170   public static final String OPT_NUM_REGIONS_PER_SERVER = "num_regions_per_server";
171   protected static final String OPT_NUM_REGIONS_PER_SERVER_USAGE
172     = "Desired number of regions per region server. Defaults to 5.";
173   public static int DEFAULT_NUM_REGIONS_PER_SERVER = 5;
174 
175   public static final String OPT_REGION_REPLICATION = "region_replication";
176   protected static final String OPT_REGION_REPLICATION_USAGE =
177       "Desired number of replicas per region";
178 
179   public static final String OPT_REGION_REPLICA_ID = "region_replica_id";
180   protected static final String OPT_REGION_REPLICA_ID_USAGE =
181       "Region replica id to do the reads from";
182 
183   protected static final long DEFAULT_START_KEY = 0;
184 
185   /** This will be removed as we factor out the dependency on command line */
186   protected CommandLine cmd;
187 
188   protected MultiThreadedWriter writerThreads = null;
189   protected MultiThreadedReader readerThreads = null;
190   protected MultiThreadedUpdater updaterThreads = null;
191 
192   protected long startKey, endKey;
193 
194   protected boolean isWrite, isRead, isUpdate;
195   protected boolean deferredLogFlush;
196 
197   // Column family options
198   protected DataBlockEncoding dataBlockEncodingAlgo;
199   protected Compression.Algorithm compressAlgo;
200   protected BloomType bloomType;
201   private boolean inMemoryCF;
202 
203   private User userOwner;
204   // Writer options
205   protected int numWriterThreads = DEFAULT_NUM_THREADS;
206   protected int minColsPerKey, maxColsPerKey;
207   protected int minColDataSize = DEFAULT_DATA_SIZE, maxColDataSize = DEFAULT_DATA_SIZE;
208   protected boolean isMultiPut;
209 
210   // Updater options
211   protected int numUpdaterThreads = DEFAULT_NUM_THREADS;
212   protected int updatePercent;
213   protected boolean ignoreConflicts = false;
214   protected boolean isBatchUpdate;
215 
216   // Reader options
217   private int numReaderThreads = DEFAULT_NUM_THREADS;
218   private int keyWindow = MultiThreadedReader.DEFAULT_KEY_WINDOW;
219   private int multiGetBatchSize = MultiThreadedReader.DEFAULT_BATCH_SIZE;
220   private int maxReadErrors = MultiThreadedReader.DEFAULT_MAX_ERRORS;
221   private int verifyPercent;
222 
223   private int numTables = 1;
224 
225   private String superUser;
226 
227   private String userNames;
228   //This file is used to read authentication information in secure clusters.
229   private String authnFileName;
230 
231   private int numRegionsPerServer = DEFAULT_NUM_REGIONS_PER_SERVER;
232   private int regionReplication = -1; // not set
233   private int regionReplicaId = -1; // not set
234 
235   // TODO: refactor LoadTestToolImpl somewhere to make the usage from tests less bad,
236   //       console tool itself should only be used from console.
237   protected boolean isSkipInit = false;
238   protected boolean isInitOnly = false;
239 
240   protected Cipher cipher = null;
241 
242   protected String[] splitColonSeparated(String option,
243       int minNumCols, int maxNumCols) {
244     String optVal = cmd.getOptionValue(option);
245     String[] cols = optVal.split(COLON);
246     if (cols.length < minNumCols || cols.length > maxNumCols) {
247       throw new IllegalArgumentException("Expected at least "
248           + minNumCols + " columns but no more than " + maxNumCols +
249           " in the colon-separated value '" + optVal + "' of the " +
250           "-" + option + " option");
251     }
252     return cols;
253   }
254 
255   protected int getNumThreads(String numThreadsStr) {
256     return parseInt(numThreadsStr, 1, Short.MAX_VALUE);
257   }
258 
259   public byte[][] getColumnFamilies() {
260     return families;
261   }
262 
263   /**
264    * Apply column family options such as Bloom filters, compression, and data
265    * block encoding.
266    */
267   protected void applyColumnFamilyOptions(TableName tableName,
268       byte[][] columnFamilies) throws IOException {
269     Admin admin = new HBaseAdmin(conf);
270     HTableDescriptor tableDesc = admin.getTableDescriptor(tableName);
271     LOG.info("Disabling table " + tableName);
272     admin.disableTable(tableName);
273     for (byte[] cf : columnFamilies) {
274       HColumnDescriptor columnDesc = tableDesc.getFamily(cf);
275       boolean isNewCf = columnDesc == null;
276       if (isNewCf) {
277         columnDesc = new HColumnDescriptor(cf);
278       }
279       if (bloomType != null) {
280         columnDesc.setBloomFilterType(bloomType);
281       }
282       if (compressAlgo != null) {
283         columnDesc.setCompressionType(compressAlgo);
284       }
285       if (dataBlockEncodingAlgo != null) {
286         columnDesc.setDataBlockEncoding(dataBlockEncodingAlgo);
287       }
288       if (inMemoryCF) {
289         columnDesc.setInMemory(inMemoryCF);
290       }
291       if (cipher != null) {
292         byte[] keyBytes = new byte[cipher.getKeyLength()];
293         new SecureRandom().nextBytes(keyBytes);
294         columnDesc.setEncryptionType(cipher.getName());
295         columnDesc.setEncryptionKey(EncryptionUtil.wrapKey(conf,
296           User.getCurrent().getShortName(),
297           new SecretKeySpec(keyBytes, cipher.getName())));
298       }
299       if (isNewCf) {
300         admin.addColumn(tableName, columnDesc);
301       } else {
302         admin.modifyColumn(tableName, columnDesc);
303       }
304     }
305     LOG.info("Enabling table " + tableName);
306     admin.enableTable(tableName);
307     admin.close();
308   }
309 
310   @Override
311   protected void addOptions() {
312     addOptWithArg(OPT_ZK_QUORUM, "ZK quorum as comma-separated host names " +
313         "without port numbers");
314     addOptWithArg(OPT_ZK_PARENT_NODE, "name of parent znode in zookeeper");
315     addOptWithArg(OPT_TABLE_NAME, "The name of the table to read or write");
316     addOptWithArg(OPT_COLUMN_FAMILIES, "The name of the column families to use separated by comma");
317     addOptWithArg(OPT_WRITE, OPT_USAGE_LOAD);
318     addOptWithArg(OPT_READ, OPT_USAGE_READ);
319     addOptWithArg(OPT_UPDATE, OPT_USAGE_UPDATE);
320     addOptNoArg(OPT_INIT_ONLY, "Initialize the test table only, don't do any loading");
321     addOptWithArg(OPT_BLOOM, OPT_USAGE_BLOOM);
322     addOptWithArg(OPT_COMPRESSION, OPT_USAGE_COMPRESSION);
323     addOptWithArg(OPT_DATA_BLOCK_ENCODING, OPT_DATA_BLOCK_ENCODING_USAGE);
324     addOptWithArg(OPT_MAX_READ_ERRORS, "The maximum number of read errors " +
325         "to tolerate before terminating all reader threads. The default is " +
326         MultiThreadedReader.DEFAULT_MAX_ERRORS + ".");
327     addOptWithArg(OPT_MULTIGET, "Whether to use multi-gets as opposed to " +
328         "separate gets for every column in a row");
329     addOptWithArg(OPT_KEY_WINDOW, "The 'key window' to maintain between " +
330         "reads and writes for concurrent write/read workload. The default " +
331         "is " + MultiThreadedReader.DEFAULT_KEY_WINDOW + ".");
332 
333     addOptNoArg(OPT_MULTIPUT, "Whether to use multi-puts as opposed to " +
334         "separate puts for every column in a row");
335     addOptNoArg(OPT_BATCHUPDATE, "Whether to use batch as opposed to " +
336         "separate updates for every column in a row");
337     addOptNoArg(OPT_INMEMORY, OPT_USAGE_IN_MEMORY);
338     addOptWithArg(OPT_GENERATOR, OPT_GENERATOR_USAGE);
339     addOptWithArg(OPT_WRITER, OPT_WRITER_USAGE);
340     addOptWithArg(OPT_UPDATER, OPT_UPDATER_USAGE);
341     addOptWithArg(OPT_READER, OPT_READER_USAGE);
342 
343     addOptWithArg(OPT_NUM_KEYS, "The number of keys to read/write");
344     addOptWithArg(OPT_START_KEY, "The first key to read/write " +
345         "(a 0-based index). The default value is " +
346         DEFAULT_START_KEY + ".");
347     addOptNoArg(OPT_SKIP_INIT, "Skip the initialization; assume test table "
348         + "already exists");
349 
350     addOptWithArg(NUM_TABLES,
351       "A positive integer number. When a number n is speicfied, load test "
352           + "tool  will load n table parallely. -tn parameter value becomes "
353           + "table name prefix. Each table name is in format <tn>_1...<tn>_n");
354 
355     addOptWithArg(OPT_ENCRYPTION, OPT_ENCRYPTION_USAGE);
356     addOptNoArg(OPT_DEFERRED_LOG_FLUSH, OPT_DEFERRED_LOG_FLUSH_USAGE);
357     addOptWithArg(OPT_NUM_REGIONS_PER_SERVER, OPT_NUM_REGIONS_PER_SERVER_USAGE);
358     addOptWithArg(OPT_REGION_REPLICATION, OPT_REGION_REPLICATION_USAGE);
359     addOptWithArg(OPT_REGION_REPLICA_ID, OPT_REGION_REPLICA_ID_USAGE);
360   }
361 
362   @Override
363   protected void processOptions(CommandLine cmd) {
364     this.cmd = cmd;
365 
366     tableName = TableName.valueOf(cmd.getOptionValue(OPT_TABLE_NAME,
367         DEFAULT_TABLE_NAME));
368 
369     if (cmd.hasOption(OPT_COLUMN_FAMILIES)) {
370       String[] list = cmd.getOptionValue(OPT_COLUMN_FAMILIES).split(",");
371       families = new byte[list.length][];
372       for (int i = 0; i < list.length; i++) {
373         families[i] = Bytes.toBytes(list[i]);
374       }
375     } else {
376       families = DEFAULT_COLUMN_FAMILIES;
377     }
378 
379     isWrite = cmd.hasOption(OPT_WRITE);
380     isRead = cmd.hasOption(OPT_READ);
381     isUpdate = cmd.hasOption(OPT_UPDATE);
382     isInitOnly = cmd.hasOption(OPT_INIT_ONLY);
383     deferredLogFlush = cmd.hasOption(OPT_DEFERRED_LOG_FLUSH);
384 
385     if (!isWrite && !isRead && !isUpdate && !isInitOnly) {
386       throw new IllegalArgumentException("Either -" + OPT_WRITE + " or " +
387         "-" + OPT_UPDATE + " or -" + OPT_READ + " has to be specified");
388     }
389 
390     if (isInitOnly && (isRead || isWrite || isUpdate)) {
391       throw new IllegalArgumentException(OPT_INIT_ONLY + " cannot be specified with"
392           + " either -" + OPT_WRITE + " or -" + OPT_UPDATE + " or -" + OPT_READ);
393     }
394 
395     if (!isInitOnly) {
396       if (!cmd.hasOption(OPT_NUM_KEYS)) {
397         throw new IllegalArgumentException(OPT_NUM_KEYS + " must be specified in "
398             + "read or write mode");
399       }
400       startKey = parseLong(cmd.getOptionValue(OPT_START_KEY,
401           String.valueOf(DEFAULT_START_KEY)), 0, Long.MAX_VALUE);
402       long numKeys = parseLong(cmd.getOptionValue(OPT_NUM_KEYS), 1,
403           Long.MAX_VALUE - startKey);
404       endKey = startKey + numKeys;
405       isSkipInit = cmd.hasOption(OPT_SKIP_INIT);
406       System.out.println("Key range: [" + startKey + ".." + (endKey - 1) + "]");
407     }
408 
409     parseColumnFamilyOptions(cmd);
410 
411     if (isWrite) {
412       String[] writeOpts = splitColonSeparated(OPT_WRITE, 2, 3);
413 
414       int colIndex = 0;
415       minColsPerKey = 1;
416       maxColsPerKey = 2 * Integer.parseInt(writeOpts[colIndex++]);
417       int avgColDataSize =
418           parseInt(writeOpts[colIndex++], 1, Integer.MAX_VALUE);
419       minColDataSize = avgColDataSize / 2;
420       maxColDataSize = avgColDataSize * 3 / 2;
421 
422       if (colIndex < writeOpts.length) {
423         numWriterThreads = getNumThreads(writeOpts[colIndex++]);
424       }
425 
426       isMultiPut = cmd.hasOption(OPT_MULTIPUT);
427 
428       System.out.println("Multi-puts: " + isMultiPut);
429       System.out.println("Columns per key: " + minColsPerKey + ".."
430           + maxColsPerKey);
431       System.out.println("Data size per column: " + minColDataSize + ".."
432           + maxColDataSize);
433     }
434 
435     if (isUpdate) {
436       String[] mutateOpts = splitColonSeparated(OPT_UPDATE, 1, 3);
437       int colIndex = 0;
438       updatePercent = parseInt(mutateOpts[colIndex++], 0, 100);
439       if (colIndex < mutateOpts.length) {
440         numUpdaterThreads = getNumThreads(mutateOpts[colIndex++]);
441       }
442       if (colIndex < mutateOpts.length) {
443         ignoreConflicts = parseInt(mutateOpts[colIndex++], 0, 1) == 1;
444       }
445 
446       isBatchUpdate = cmd.hasOption(OPT_BATCHUPDATE);
447 
448       System.out.println("Batch updates: " + isBatchUpdate);
449       System.out.println("Percent of keys to update: " + updatePercent);
450       System.out.println("Updater threads: " + numUpdaterThreads);
451       System.out.println("Ignore nonce conflicts: " + ignoreConflicts);
452     }
453 
454     if (isRead) {
455       String[] readOpts = splitColonSeparated(OPT_READ, 1, 2);
456       int colIndex = 0;
457       verifyPercent = parseInt(readOpts[colIndex++], 0, 100);
458       if (colIndex < readOpts.length) {
459         numReaderThreads = getNumThreads(readOpts[colIndex++]);
460       }
461 
462       if (cmd.hasOption(OPT_MAX_READ_ERRORS)) {
463         maxReadErrors = parseInt(cmd.getOptionValue(OPT_MAX_READ_ERRORS),
464             0, Integer.MAX_VALUE);
465       }
466 
467       if (cmd.hasOption(OPT_KEY_WINDOW)) {
468         keyWindow = parseInt(cmd.getOptionValue(OPT_KEY_WINDOW),
469             0, Integer.MAX_VALUE);
470       }
471 
472       if (cmd.hasOption(OPT_MULTIGET)) {
473         multiGetBatchSize = parseInt(cmd.getOptionValue(OPT_MULTIGET),
474             0, Integer.MAX_VALUE);
475       }
476 
477       System.out.println("Multi-gets (value of 1 means no multigets): " + multiGetBatchSize);
478       System.out.println("Percent of keys to verify: " + verifyPercent);
479       System.out.println("Reader threads: " + numReaderThreads);
480     }
481 
482     numTables = 1;
483     if (cmd.hasOption(NUM_TABLES)) {
484       numTables = parseInt(cmd.getOptionValue(NUM_TABLES), 1, Short.MAX_VALUE);
485     }
486 
487     numRegionsPerServer = DEFAULT_NUM_REGIONS_PER_SERVER;
488     if (cmd.hasOption(OPT_NUM_REGIONS_PER_SERVER)) {
489       numRegionsPerServer = Integer.parseInt(cmd.getOptionValue(OPT_NUM_REGIONS_PER_SERVER));
490     }
491 
492     regionReplication = 1;
493     if (cmd.hasOption(OPT_REGION_REPLICATION)) {
494       regionReplication = Integer.parseInt(cmd.getOptionValue(OPT_REGION_REPLICATION));
495     }
496 
497     regionReplicaId = -1;
498     if (cmd.hasOption(OPT_REGION_REPLICA_ID)) {
499       regionReplicaId = Integer.parseInt(cmd.getOptionValue(OPT_REGION_REPLICA_ID));
500     }
501   }
502 
503   private void parseColumnFamilyOptions(CommandLine cmd) {
504     String dataBlockEncodingStr = cmd.getOptionValue(OPT_DATA_BLOCK_ENCODING);
505     dataBlockEncodingAlgo = dataBlockEncodingStr == null ? null :
506         DataBlockEncoding.valueOf(dataBlockEncodingStr);
507 
508     String compressStr = cmd.getOptionValue(OPT_COMPRESSION);
509     compressAlgo = compressStr == null ? Compression.Algorithm.NONE :
510         Compression.Algorithm.valueOf(compressStr);
511 
512     String bloomStr = cmd.getOptionValue(OPT_BLOOM);
513     bloomType = bloomStr == null ? BloomType.ROW :
514         BloomType.valueOf(bloomStr);
515 
516     inMemoryCF = cmd.hasOption(OPT_INMEMORY);
517     if (cmd.hasOption(OPT_ENCRYPTION)) {
518       cipher = Encryption.getCipher(conf, cmd.getOptionValue(OPT_ENCRYPTION));
519     }
520 
521   }
522 
523   public void initTestTable() throws IOException {
524     Durability durability = Durability.USE_DEFAULT;
525     if (deferredLogFlush) {
526       durability = Durability.ASYNC_WAL;
527     }
528 
529     HBaseTestingUtility.createPreSplitLoadTestTable(conf, tableName,
530       getColumnFamilies(), compressAlgo, dataBlockEncodingAlgo, numRegionsPerServer,
531         regionReplication, durability);
532     applyColumnFamilyOptions(tableName, getColumnFamilies());
533   }
534 
535   @Override
536   protected int doWork() throws IOException {
537     if (numTables > 1) {
538       return parallelLoadTables();
539     } else {
540       return loadTable();
541     }
542   }
543 
544   protected int loadTable() throws IOException {
545     if (cmd.hasOption(OPT_ZK_QUORUM)) {
546       conf.set(HConstants.ZOOKEEPER_QUORUM, cmd.getOptionValue(OPT_ZK_QUORUM));
547     }
548     if (cmd.hasOption(OPT_ZK_PARENT_NODE)) {
549       conf.set(HConstants.ZOOKEEPER_ZNODE_PARENT, cmd.getOptionValue(OPT_ZK_PARENT_NODE));
550     }
551 
552     if (isInitOnly) {
553       LOG.info("Initializing only; no reads or writes");
554       initTestTable();
555       return 0;
556     }
557 
558     if (!isSkipInit) {
559       initTestTable();
560     }
561     LoadTestDataGenerator dataGen = null;
562     if (cmd.hasOption(OPT_GENERATOR)) {
563       String[] clazzAndArgs = cmd.getOptionValue(OPT_GENERATOR).split(COLON);
564       dataGen = getLoadGeneratorInstance(clazzAndArgs[0]);
565       String[] args;
566       if (dataGen instanceof LoadTestDataGeneratorWithACL) {
567         LOG.info("Using LoadTestDataGeneratorWithACL");
568         if (User.isHBaseSecurityEnabled(conf)) {
569           LOG.info("Security is enabled");
570           authnFileName = clazzAndArgs[1];
571           superUser = clazzAndArgs[2];
572           userNames = clazzAndArgs[3];
573           args = Arrays.copyOfRange(clazzAndArgs, 2, clazzAndArgs.length);
574           Properties authConfig = new Properties();
575           authConfig.load(this.getClass().getClassLoader().getResourceAsStream(authnFileName));
576           try {
577             addAuthInfoToConf(authConfig, conf, superUser, userNames);
578           } catch (IOException exp) {
579             LOG.error(exp);
580             return EXIT_FAILURE;
581           }
582           userOwner = User.create(loginAndReturnUGI(conf, superUser));
583         } else {
584           superUser = clazzAndArgs[1];
585           userNames = clazzAndArgs[2];
586           args = Arrays.copyOfRange(clazzAndArgs, 1, clazzAndArgs.length);
587           userOwner = User.createUserForTesting(conf, superUser, new String[0]);
588         }
589       } else {
590         args = clazzAndArgs.length == 1 ? new String[0] : Arrays.copyOfRange(clazzAndArgs, 1,
591             clazzAndArgs.length);
592       }
593       dataGen.initialize(args);
594     } else {
595       // Default DataGenerator is MultiThreadedAction.DefaultDataGenerator
596       dataGen = new MultiThreadedAction.DefaultDataGenerator(minColDataSize, maxColDataSize,
597           minColsPerKey, maxColsPerKey, families);
598     }
599 
600     if (userOwner != null) {
601       LOG.info("Granting permissions for user " + userOwner.getShortName());
602       Permission.Action[] actions = {
603         Permission.Action.ADMIN, Permission.Action.CREATE,
604         Permission.Action.READ, Permission.Action.WRITE };
605       try {
606         AccessControlClient.grant(ConnectionFactory.createConnection(conf),
607             tableName, userOwner.getShortName(), null, null, actions);
608       } catch (Throwable e) {
609         LOG.fatal("Error in granting permission for the user " + userOwner.getShortName(), e);
610         return EXIT_FAILURE;
611       }
612     }
613 
614     if (userNames != null) {
615       // This will be comma separated list of expressions.
616       String users[] = userNames.split(",");
617       User user = null;
618       for (String userStr : users) {
619         if (User.isHBaseSecurityEnabled(conf)) {
620           user = User.create(loginAndReturnUGI(conf, userStr));
621         } else {
622           user = User.createUserForTesting(conf, userStr, new String[0]);
623         }
624       }
625     }
626 
627     if (isWrite) {
628       if (userOwner != null) {
629         writerThreads = new MultiThreadedWriterWithACL(dataGen, conf, tableName, userOwner);
630       } else {
631         String writerClass = null;
632         if (cmd.hasOption(OPT_WRITER)) {
633           writerClass = cmd.getOptionValue(OPT_WRITER);
634         } else {
635           writerClass = MultiThreadedWriter.class.getCanonicalName();
636         }
637 
638         writerThreads = getMultiThreadedWriterInstance(writerClass, dataGen);
639       }
640       writerThreads.setMultiPut(isMultiPut);
641     }
642 
643     if (isUpdate) {
644       if (userOwner != null) {
645         updaterThreads = new MultiThreadedUpdaterWithACL(dataGen, conf, tableName, updatePercent,
646             userOwner, userNames);
647       } else {
648         String updaterClass = null;
649         if (cmd.hasOption(OPT_UPDATER)) {
650           updaterClass = cmd.getOptionValue(OPT_UPDATER);
651         } else {
652           updaterClass = MultiThreadedUpdater.class.getCanonicalName();
653         }
654         updaterThreads = getMultiThreadedUpdaterInstance(updaterClass, dataGen);
655       }
656       updaterThreads.setBatchUpdate(isBatchUpdate);
657       updaterThreads.setIgnoreNonceConflicts(ignoreConflicts);
658     }
659 
660     if (isRead) {
661       if (userOwner != null) {
662         readerThreads = new MultiThreadedReaderWithACL(dataGen, conf, tableName, verifyPercent,
663             userNames);
664       } else {
665         String readerClass = null;
666         if (cmd.hasOption(OPT_READER)) {
667           readerClass = cmd.getOptionValue(OPT_READER);
668         } else {
669           readerClass = MultiThreadedReader.class.getCanonicalName();
670         }
671         readerThreads = getMultiThreadedReaderInstance(readerClass, dataGen);
672       }
673       readerThreads.setMaxErrors(maxReadErrors);
674       readerThreads.setKeyWindow(keyWindow);
675       readerThreads.setMultiGetBatchSize(multiGetBatchSize);
676       readerThreads.setRegionReplicaId(regionReplicaId);
677     }
678 
679     if (isUpdate && isWrite) {
680       LOG.info("Concurrent write/update workload: making updaters aware of the " +
681         "write point");
682       updaterThreads.linkToWriter(writerThreads);
683     }
684 
685     if (isRead && (isUpdate || isWrite)) {
686       LOG.info("Concurrent write/read workload: making readers aware of the " +
687         "write point");
688       readerThreads.linkToWriter(isUpdate ? updaterThreads : writerThreads);
689     }
690 
691     if (isWrite) {
692       System.out.println("Starting to write data...");
693       writerThreads.start(startKey, endKey, numWriterThreads);
694     }
695 
696     if (isUpdate) {
697       LOG.info("Starting to mutate data...");
698       System.out.println("Starting to mutate data...");
699       // TODO : currently append and increment operations not tested with tags
700       // Will update this aftet it is done
701       updaterThreads.start(startKey, endKey, numUpdaterThreads);
702     }
703 
704     if (isRead) {
705       System.out.println("Starting to read data...");
706       readerThreads.start(startKey, endKey, numReaderThreads);
707     }
708 
709     if (isWrite) {
710       writerThreads.waitForFinish();
711     }
712 
713     if (isUpdate) {
714       updaterThreads.waitForFinish();
715     }
716 
717     if (isRead) {
718       readerThreads.waitForFinish();
719     }
720 
721     boolean success = true;
722     if (isWrite) {
723       success = success && writerThreads.getNumWriteFailures() == 0;
724     }
725     if (isUpdate) {
726       success = success && updaterThreads.getNumWriteFailures() == 0;
727     }
728     if (isRead) {
729       success = success && readerThreads.getNumReadErrors() == 0
730           && readerThreads.getNumReadFailures() == 0;
731     }
732     return success ? EXIT_SUCCESS : EXIT_FAILURE;
733   }
734 
735   private LoadTestDataGenerator getLoadGeneratorInstance(String clazzName) throws IOException {
736     try {
737       Class<?> clazz = Class.forName(clazzName);
738       Constructor<?> constructor = clazz.getConstructor(int.class, int.class, int.class, int.class,
739           byte[][].class);
740       return (LoadTestDataGenerator) constructor.newInstance(minColDataSize, maxColDataSize,
741           minColsPerKey, maxColsPerKey, families);
742     } catch (Exception e) {
743       throw new IOException(e);
744     }
745   }
746 
747   private MultiThreadedWriter getMultiThreadedWriterInstance(String clazzName
748       , LoadTestDataGenerator dataGen) throws IOException {
749     try {
750       Class<?> clazz = Class.forName(clazzName);
751       Constructor<?> constructor = clazz.getConstructor(
752         LoadTestDataGenerator.class, Configuration.class, TableName.class);
753       return (MultiThreadedWriter) constructor.newInstance(dataGen, conf, tableName);
754     } catch (Exception e) {
755       throw new IOException(e);
756     }
757   }
758 
759   private MultiThreadedUpdater getMultiThreadedUpdaterInstance(String clazzName
760       , LoadTestDataGenerator dataGen) throws IOException {
761     try {
762       Class<?> clazz = Class.forName(clazzName);
763       Constructor<?> constructor = clazz.getConstructor(
764         LoadTestDataGenerator.class, Configuration.class, TableName.class, double.class);
765       return (MultiThreadedUpdater) constructor.newInstance(
766         dataGen, conf, tableName, updatePercent);
767     } catch (Exception e) {
768       throw new IOException(e);
769     }
770   }
771 
772   private MultiThreadedReader getMultiThreadedReaderInstance(String clazzName
773       , LoadTestDataGenerator dataGen) throws IOException {
774     try {
775       Class<?> clazz = Class.forName(clazzName);
776       Constructor<?> constructor = clazz.getConstructor(
777         LoadTestDataGenerator.class, Configuration.class, TableName.class, double.class);
778       return (MultiThreadedReader) constructor.newInstance(dataGen, conf, tableName, verifyPercent);
779     } catch (Exception e) {
780       throw new IOException(e);
781     }
782   }
783 
784   public static byte[] generateData(final Random r, int length) {
785     byte [] b = new byte [length];
786     int i = 0;
787 
788     for(i = 0; i < (length-8); i += 8) {
789       b[i] = (byte) (65 + r.nextInt(26));
790       b[i+1] = b[i];
791       b[i+2] = b[i];
792       b[i+3] = b[i];
793       b[i+4] = b[i];
794       b[i+5] = b[i];
795       b[i+6] = b[i];
796       b[i+7] = b[i];
797     }
798 
799     byte a = (byte) (65 + r.nextInt(26));
800     for(; i < length; i++) {
801       b[i] = a;
802     }
803     return b;
804   }
805   public static void main(String[] args) {
806     new LoadTestTool().doStaticMain(args);
807   }
808 
809   /**
810    * When NUM_TABLES is specified, the function starts multiple worker threads
811    * which individually start a LoadTestTool instance to load a table. Each
812    * table name is in format <tn>_<index>. For example, "-tn test -num_tables 2"
813    * , table names will be "test_1", "test_2"
814    *
815    * @throws IOException
816    */
817   private int parallelLoadTables()
818       throws IOException {
819     // create new command args
820     String tableName = cmd.getOptionValue(OPT_TABLE_NAME, DEFAULT_TABLE_NAME);
821     String[] newArgs = null;
822     if (!cmd.hasOption(LoadTestTool.OPT_TABLE_NAME)) {
823       newArgs = new String[cmdLineArgs.length + 2];
824       newArgs[0] = "-" + LoadTestTool.OPT_TABLE_NAME;
825       newArgs[1] = LoadTestTool.DEFAULT_TABLE_NAME;
826       System.arraycopy(cmdLineArgs, 0, newArgs, 2, cmdLineArgs.length);
827     } else {
828       newArgs = cmdLineArgs;
829     }
830 
831     int tableNameValueIndex = -1;
832     for (int j = 0; j < newArgs.length; j++) {
833       if (newArgs[j].endsWith(OPT_TABLE_NAME)) {
834         tableNameValueIndex = j + 1;
835       } else if (newArgs[j].endsWith(NUM_TABLES)) {
836         // change NUM_TABLES to 1 so that each worker loads one table
837         newArgs[j + 1] = "1";
838       }
839     }
840 
841     // starting to load multiple tables
842     List<WorkerThread> workers = new ArrayList<WorkerThread>();
843     for (int i = 0; i < numTables; i++) {
844       String[] workerArgs = newArgs.clone();
845       workerArgs[tableNameValueIndex] = tableName + "_" + (i+1);
846       WorkerThread worker = new WorkerThread(i, workerArgs);
847       workers.add(worker);
848       LOG.info(worker + " starting");
849       worker.start();
850     }
851 
852     // wait for all workers finish
853     LOG.info("Waiting for worker threads to finish");
854     for (WorkerThread t : workers) {
855       try {
856         t.join();
857       } catch (InterruptedException ie) {
858         IOException iie = new InterruptedIOException();
859         iie.initCause(ie);
860         throw iie;
861       }
862       checkForErrors();
863     }
864 
865     return EXIT_SUCCESS;
866   }
867 
868   // If an exception is thrown by one of worker threads, it will be
869   // stored here.
870   protected AtomicReference<Throwable> thrown = new AtomicReference<Throwable>();
871 
872   private void workerThreadError(Throwable t) {
873     thrown.compareAndSet(null, t);
874   }
875 
876   /**
877    * Check for errors in the writer threads. If any is found, rethrow it.
878    */
879   private void checkForErrors() throws IOException {
880     Throwable thrown = this.thrown.get();
881     if (thrown == null) return;
882     if (thrown instanceof IOException) {
883       throw (IOException) thrown;
884     } else {
885       throw new RuntimeException(thrown);
886     }
887   }
888 
889   class WorkerThread extends Thread {
890     private String[] workerArgs;
891 
892     WorkerThread(int i, String[] args) {
893       super("WorkerThread-" + i);
894       workerArgs = args;
895     }
896 
897     @Override
898     public void run() {
899       try {
900         int ret = ToolRunner.run(HBaseConfiguration.create(), new LoadTestTool(), workerArgs);
901         if (ret != 0) {
902           throw new RuntimeException("LoadTestTool exit with non-zero return code.");
903         }
904       } catch (Exception ex) {
905         LOG.error("Error in worker thread", ex);
906         workerThreadError(ex);
907       }
908     }
909   }
910 
911   private void addAuthInfoToConf(Properties authConfig, Configuration conf, String owner,
912       String userList) throws IOException {
913     List<String> users = new ArrayList(Arrays.asList(userList.split(",")));
914     users.add(owner);
915     for (String user : users) {
916       String keyTabFileConfKey = "hbase." + user + ".keytab.file";
917       String principalConfKey = "hbase." + user + ".kerberos.principal";
918       if (!authConfig.containsKey(keyTabFileConfKey) || !authConfig.containsKey(principalConfKey)) {
919         throw new IOException("Authentication configs missing for user : " + user);
920       }
921     }
922     for (String key : authConfig.stringPropertyNames()) {
923       conf.set(key, authConfig.getProperty(key));
924     }
925     LOG.debug("Added authentication properties to config successfully.");
926   }
927 
928   public static UserGroupInformation loginAndReturnUGI(Configuration conf, String username)
929       throws IOException {
930     String hostname = InetAddress.getLocalHost().getHostName();
931     String keyTabFileConfKey = "hbase." + username + ".keytab.file";
932     String keyTabFileLocation = conf.get(keyTabFileConfKey);
933     String principalConfKey = "hbase." + username + ".kerberos.principal";
934     String principal = SecurityUtil.getServerPrincipal(conf.get(principalConfKey), hostname);
935     if (keyTabFileLocation == null || principal == null) {
936       LOG.warn("Principal or key tab file null for : " + principalConfKey + ", "
937           + keyTabFileConfKey);
938     }
939     UserGroupInformation ugi =
940         UserGroupInformation.loginUserFromKeytabAndReturnUGI(principal, keyTabFileLocation);
941     return ugi;
942   }
943 }