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 static org.apache.hadoop.hbase.util.test.LoadTestDataGenerator.INCREMENT;
20  import static org.apache.hadoop.hbase.util.test.LoadTestDataGenerator.MUTATE_INFO;
21  
22  import java.io.IOException;
23  import java.util.Arrays;
24  import java.util.Collection;
25  import java.util.HashMap;
26  import java.util.Map;
27  import java.util.Random;
28  import java.util.Set;
29  import java.util.concurrent.atomic.AtomicInteger;
30  import java.util.concurrent.atomic.AtomicLong;
31  
32  import org.apache.commons.logging.Log;
33  import org.apache.commons.logging.LogFactory;
34  import org.apache.hadoop.conf.Configuration;
35  import org.apache.hadoop.hbase.Cell;
36  import org.apache.hadoop.hbase.CellUtil;
37  import org.apache.hadoop.hbase.HBaseTestingUtility;
38  import org.apache.hadoop.hbase.HRegionLocation;
39  import org.apache.hadoop.hbase.RegionLocations;
40  import org.apache.hadoop.hbase.TableName;
41  import org.apache.hadoop.hbase.client.ClusterConnection;
42  import org.apache.hadoop.hbase.client.HConnection;
43  import org.apache.hadoop.hbase.client.HConnectionManager;
44  import org.apache.hadoop.hbase.client.Result;
45  import org.apache.hadoop.hbase.io.compress.Compression.Algorithm;
46  import org.apache.hadoop.hbase.io.encoding.DataBlockEncoding;
47  import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.MutationProto.MutationType;
48  import org.apache.hadoop.hbase.util.test.LoadTestDataGenerator;
49  import org.apache.hadoop.util.StringUtils;
50  
51  import com.google.common.base.Preconditions;
52  
53  /**
54   * Common base class for reader and writer parts of multi-thread HBase load
55   * test ({@link LoadTestTool}).
56   */
57  public abstract class MultiThreadedAction {
58    private static final Log LOG = LogFactory.getLog(MultiThreadedAction.class);
59  
60    protected final TableName tableName;
61    protected final Configuration conf;
62    protected final HConnection connection; // all reader / writer threads will share this connection
63  
64    protected int numThreads = 1;
65  
66    /** The start key of the key range, inclusive */
67    protected long startKey = 0;
68  
69    /** The end key of the key range, exclusive */
70    protected long endKey = 1;
71  
72    protected AtomicInteger numThreadsWorking = new AtomicInteger();
73    protected AtomicLong numKeys = new AtomicLong();
74    protected AtomicLong numCols = new AtomicLong();
75    protected AtomicLong totalOpTimeMs = new AtomicLong();
76    protected boolean verbose = false;
77  
78    protected LoadTestDataGenerator dataGenerator = null;
79  
80    /**
81     * Default implementation of LoadTestDataGenerator that uses LoadTestKVGenerator, fixed
82     * set of column families, and random number of columns in range. The table for it can
83     * be created manually or, for example, via
84     * {@link HBaseTestingUtility#createPreSplitLoadTestTable(
85     * org.apache.hadoop.hbase.Configuration, byte[], byte[], Algorithm, DataBlockEncoding)}
86     */
87    public static class DefaultDataGenerator extends LoadTestDataGenerator {
88      private byte[][] columnFamilies = null;
89      private int minColumnsPerKey;
90      private int maxColumnsPerKey;
91      private final Random random = new Random();
92  
93      public DefaultDataGenerator(int minValueSize, int maxValueSize,
94          int minColumnsPerKey, int maxColumnsPerKey, byte[]... columnFamilies) {
95        super(minValueSize, maxValueSize);
96        this.columnFamilies = columnFamilies;
97        this.minColumnsPerKey = minColumnsPerKey;
98        this.maxColumnsPerKey = maxColumnsPerKey;
99      }
100 
101     public DefaultDataGenerator(byte[]... columnFamilies) {
102       // Default values for tests that didn't care to provide theirs.
103       this(256, 1024, 1, 10, columnFamilies);
104     }
105 
106     @Override
107     public byte[] getDeterministicUniqueKey(long keyBase) {
108       return LoadTestKVGenerator.md5PrefixedKey(keyBase).getBytes();
109     }
110 
111     @Override
112     public byte[][] getColumnFamilies() {
113       return columnFamilies;
114     }
115 
116     @Override
117     public byte[][] generateColumnsForCf(byte[] rowKey, byte[] cf) {
118       int numColumns = minColumnsPerKey + random.nextInt(maxColumnsPerKey - minColumnsPerKey + 1);
119       byte[][] columns = new byte[numColumns][];
120       for (int i = 0; i < numColumns; ++i) {
121         columns[i] = Integer.toString(i).getBytes();
122       }
123       return columns;
124     }
125 
126     @Override
127     public byte[] generateValue(byte[] rowKey, byte[] cf, byte[] column) {
128       return kvGenerator.generateRandomSizeValue(rowKey, cf, column);
129     }
130 
131     @Override
132     public boolean verify(byte[] rowKey, byte[] cf, byte[] column, byte[] value) {
133       return LoadTestKVGenerator.verify(value, rowKey, cf, column);
134     }
135 
136     @Override
137     public boolean verify(byte[] rowKey, byte[] cf, Set<byte[]> columnSet) {
138       return (columnSet.size() >= minColumnsPerKey) && (columnSet.size() <= maxColumnsPerKey);
139     }
140   }
141 
142   /** "R" or "W" */
143   private String actionLetter;
144 
145   /** Whether we need to print out Hadoop Streaming-style counters */
146   private boolean streamingCounters;
147 
148   public static final int REPORTING_INTERVAL_MS = 5000;
149 
150   public MultiThreadedAction(LoadTestDataGenerator dataGen, Configuration conf,
151                              TableName tableName,
152                              String actionLetter) throws IOException {
153     this.conf = conf;
154     this.dataGenerator = dataGen;
155     this.tableName = tableName;
156     this.actionLetter = actionLetter;
157     this.connection = HConnectionManager.createConnection(conf);
158   }
159 
160   public void start(long startKey, long endKey, int numThreads) throws IOException {
161     this.startKey = startKey;
162     this.endKey = endKey;
163     this.numThreads = numThreads;
164     (new Thread(new ProgressReporter(actionLetter),
165         "MultiThreadedAction-ProgressReporter-" + System.currentTimeMillis())).start();
166   }
167 
168   private static String formatTime(long elapsedTime) {
169     String format = String.format("%%0%dd", 2);
170     elapsedTime = elapsedTime / 1000;
171     String seconds = String.format(format, elapsedTime % 60);
172     String minutes = String.format(format, (elapsedTime % 3600) / 60);
173     String hours = String.format(format, elapsedTime / 3600);
174     String time =  hours + ":" + minutes + ":" + seconds;
175     return time;
176   }
177 
178   /** Asynchronously reports progress */
179   private class ProgressReporter implements Runnable {
180 
181     private String reporterId = "";
182 
183     public ProgressReporter(String id) {
184       this.reporterId = id;
185     }
186 
187     @Override
188     public void run() {
189       long startTime = System.currentTimeMillis();
190       long priorNumKeys = 0;
191       long priorCumulativeOpTime = 0;
192       int priorAverageKeysPerSecond = 0;
193 
194       // Give other threads time to start.
195       Threads.sleep(REPORTING_INTERVAL_MS);
196 
197       while (numThreadsWorking.get() != 0) {
198         String threadsLeft =
199             "[" + reporterId + ":" + numThreadsWorking.get() + "] ";
200         if (numKeys.get() == 0) {
201           LOG.info(threadsLeft + "Number of keys = 0");
202         } else {
203           long numKeys = MultiThreadedAction.this.numKeys.get();
204           long time = System.currentTimeMillis() - startTime;
205           long totalOpTime = totalOpTimeMs.get();
206 
207           long numKeysDelta = numKeys - priorNumKeys;
208           long totalOpTimeDelta = totalOpTime - priorCumulativeOpTime;
209 
210           double averageKeysPerSecond =
211               (time > 0) ? (numKeys * 1000 / time) : 0;
212 
213           LOG.info(threadsLeft
214               + "Keys="
215               + numKeys
216               + ", cols="
217               + StringUtils.humanReadableInt(numCols.get())
218               + ", time="
219               + formatTime(time)
220               + ((numKeys > 0 && time > 0) ? (" Overall: [" + "keys/s= "
221                   + numKeys * 1000 / time + ", latency="
222                   + String.format("%.2f", (double)totalOpTime / (double)numKeys)
223                   + " ms]") : "")
224               + ((numKeysDelta > 0) ? (" Current: [" + "keys/s="
225                   + numKeysDelta * 1000 / REPORTING_INTERVAL_MS + ", latency="
226                   + String.format("%.2f", (double)totalOpTimeDelta / (double)numKeysDelta)
227                   + " ms]") : "")
228               + progressInfo());
229 
230           if (streamingCounters) {
231             printStreamingCounters(numKeysDelta,
232                 averageKeysPerSecond - priorAverageKeysPerSecond);
233           }
234 
235           priorNumKeys = numKeys;
236           priorCumulativeOpTime = totalOpTime;
237           priorAverageKeysPerSecond = (int) averageKeysPerSecond;
238         }
239 
240         Threads.sleep(REPORTING_INTERVAL_MS);
241       }
242     }
243 
244     private void printStreamingCounters(long numKeysDelta,
245         double avgKeysPerSecondDelta) {
246       // Write stats in a format that can be interpreted as counters by
247       // streaming map-reduce jobs.
248       System.err.println("reporter:counter:numKeys," + reporterId + ","
249           + numKeysDelta);
250       System.err.println("reporter:counter:numCols," + reporterId + ","
251           + numCols.get());
252       System.err.println("reporter:counter:avgKeysPerSecond," + reporterId
253           + "," + (long) (avgKeysPerSecondDelta));
254     }
255   }
256 
257   public void close() {
258     if (connection != null) {
259       try {
260         connection.close();
261       } catch (Exception ex) {
262         LOG.warn("Could not close the connection: " + ex);
263       }
264     }
265   }
266 
267   public void waitForFinish() {
268     while (numThreadsWorking.get() != 0) {
269       Threads.sleepWithoutInterrupt(1000);
270     }
271     close();
272   }
273 
274   public boolean isDone() {
275     return (numThreadsWorking.get() == 0);
276   }
277 
278   protected void startThreads(Collection<? extends Thread> threads) {
279     numThreadsWorking.addAndGet(threads.size());
280     for (Thread thread : threads) {
281       thread.start();
282     }
283   }
284 
285   /** @return the end key of the key range, exclusive */
286   public long getEndKey() {
287     return endKey;
288   }
289 
290   /** Returns a task-specific progress string */
291   protected abstract String progressInfo();
292 
293   protected static void appendToStatus(StringBuilder sb, String desc,
294       long v) {
295     if (v == 0) {
296       return;
297     }
298     sb.append(", ");
299     sb.append(desc);
300     sb.append("=");
301     sb.append(v);
302   }
303 
304   protected static void appendToStatus(StringBuilder sb, String desc,
305       String v) {
306     sb.append(", ");
307     sb.append(desc);
308     sb.append("=");
309     sb.append(v);
310   }
311 
312   /**
313    * See {@link #verifyResultAgainstDataGenerator(Result, boolean, boolean)}.
314    * Does not verify cf/column integrity.
315    */
316   public boolean verifyResultAgainstDataGenerator(Result result, boolean verifyValues) {
317     return verifyResultAgainstDataGenerator(result, verifyValues, false);
318   }
319 
320   /**
321    * Verifies the result from get or scan using the dataGenerator (that was presumably
322    * also used to generate said result).
323    * @param verifyValues verify that values in the result make sense for row/cf/column combination
324    * @param verifyCfAndColumnIntegrity verify that cf/column set in the result is complete. Note
325    *                                   that to use this multiPut should be used, or verification
326    *                                   has to happen after writes, otherwise there can be races.
327    * @return
328    */
329   public boolean verifyResultAgainstDataGenerator(Result result, boolean verifyValues,
330       boolean verifyCfAndColumnIntegrity) {
331     String rowKeyStr = Bytes.toString(result.getRow());
332     // See if we have any data at all.
333     if (result.isEmpty()) {
334       LOG.error("Error checking data for key [" + rowKeyStr + "], no data returned");
335       printLocations(result);
336       return false;
337     }
338 
339     if (!verifyValues && !verifyCfAndColumnIntegrity) {
340       return true; // as long as we have something, we are good.
341     }
342 
343     // See if we have all the CFs.
344     byte[][] expectedCfs = dataGenerator.getColumnFamilies();
345     if (verifyCfAndColumnIntegrity && (expectedCfs.length != result.getMap().size())) {
346       LOG.error("Error checking data for key [" + rowKeyStr
347         + "], bad family count: " + result.getMap().size());
348       printLocations(result);
349       return false;
350     }
351 
352     // Verify each column family from get in the result.
353     for (byte[] cf : result.getMap().keySet()) {
354       String cfStr = Bytes.toString(cf);
355       Map<byte[], byte[]> columnValues = result.getFamilyMap(cf);
356       if (columnValues == null) {
357         LOG.error("Error checking data for key [" + rowKeyStr
358           + "], no data for family [" + cfStr + "]]");
359         printLocations(result);
360         return false;
361       }
362 
363       Map<String, MutationType> mutateInfo = null;
364       if (verifyCfAndColumnIntegrity || verifyValues) {
365         if (!columnValues.containsKey(MUTATE_INFO)) {
366           LOG.error("Error checking data for key [" + rowKeyStr + "], column family ["
367             + cfStr + "], column [" + Bytes.toString(MUTATE_INFO) + "]; value is not found");
368           printLocations(result);
369           return false;
370         }
371 
372         long cfHash = Arrays.hashCode(cf);
373         // Verify deleted columns, and make up column counts if deleted
374         byte[] mutateInfoValue = columnValues.remove(MUTATE_INFO);
375         mutateInfo = parseMutateInfo(mutateInfoValue);
376         for (Map.Entry<String, MutationType> mutate: mutateInfo.entrySet()) {
377           if (mutate.getValue() == MutationType.DELETE) {
378             byte[] column = Bytes.toBytes(mutate.getKey());
379             long columnHash = Arrays.hashCode(column);
380             long hashCode = cfHash + columnHash;
381             if (hashCode % 2 == 0) {
382               if (columnValues.containsKey(column)) {
383                 LOG.error("Error checking data for key [" + rowKeyStr + "], column family ["
384                   + cfStr + "], column [" + mutate.getKey() + "]; should be deleted");
385                 printLocations(result);
386                 return false;
387               }
388               byte[] hashCodeBytes = Bytes.toBytes(hashCode);
389               columnValues.put(column, hashCodeBytes);
390             }
391           }
392         }
393 
394         // Verify increment
395         if (!columnValues.containsKey(INCREMENT)) {
396           LOG.error("Error checking data for key [" + rowKeyStr + "], column family ["
397             + cfStr + "], column [" + Bytes.toString(INCREMENT) + "]; value is not found");
398           printLocations(result);
399           return false;
400         }
401         long currentValue = Bytes.toLong(columnValues.remove(INCREMENT));
402         if (verifyValues) {
403           long amount = mutateInfo.isEmpty() ? 0 : cfHash;
404           long originalValue = Arrays.hashCode(result.getRow());
405           long extra = currentValue - originalValue;
406           if (extra != 0 && (amount == 0 || extra % amount != 0)) {
407             LOG.error("Error checking data for key [" + rowKeyStr + "], column family ["
408               + cfStr + "], column [increment], extra [" + extra + "], amount [" + amount + "]");
409             printLocations(result);
410             return false;
411           }
412           if (amount != 0 && extra != amount) {
413             LOG.warn("Warning checking data for key [" + rowKeyStr + "], column family ["
414               + cfStr + "], column [increment], incremented [" + (extra / amount) + "] times");
415           }
416         }
417 
418         // See if we have correct columns.
419         if (verifyCfAndColumnIntegrity
420             && !dataGenerator.verify(result.getRow(), cf, columnValues.keySet())) {
421           String colsStr = "";
422           for (byte[] col : columnValues.keySet()) {
423             if (colsStr.length() > 0) {
424               colsStr += ", ";
425             }
426             colsStr += "[" + Bytes.toString(col) + "]";
427           }
428           LOG.error("Error checking data for key [" + rowKeyStr
429             + "], bad columns for family [" + cfStr + "]: " + colsStr);
430           printLocations(result);
431           return false;
432         }
433         // See if values check out.
434         if (verifyValues) {
435           for (Map.Entry<byte[], byte[]> kv : columnValues.entrySet()) {
436             String column = Bytes.toString(kv.getKey());
437             MutationType mutation = mutateInfo.get(column);
438             boolean verificationNeeded = true;
439             byte[] bytes = kv.getValue();
440             if (mutation != null) {
441               boolean mutationVerified = true;
442               long columnHash = Arrays.hashCode(kv.getKey());
443               long hashCode = cfHash + columnHash;
444               byte[] hashCodeBytes = Bytes.toBytes(hashCode);
445               if (mutation == MutationType.APPEND) {
446                 int offset = bytes.length - hashCodeBytes.length;
447                 mutationVerified = offset > 0 && Bytes.equals(hashCodeBytes,
448                   0, hashCodeBytes.length, bytes, offset, hashCodeBytes.length);
449                 if (mutationVerified) {
450                   int n = 1;
451                   while (true) {
452                     int newOffset = offset - hashCodeBytes.length;
453                     if (newOffset < 0 || !Bytes.equals(hashCodeBytes, 0,
454                         hashCodeBytes.length, bytes, newOffset, hashCodeBytes.length)) {
455                       break;
456                     }
457                     offset = newOffset;
458                     n++;
459                   }
460                   if (n > 1) {
461                     LOG.warn("Warning checking data for key [" + rowKeyStr + "], column family ["
462                       + cfStr + "], column [" + column + "], appended [" + n + "] times");
463                   }
464                   byte[] dest = new byte[offset];
465                   System.arraycopy(bytes, 0, dest, 0, offset);
466                   bytes = dest;
467                 }
468               } else if (hashCode % 2 == 0) { // checkAndPut
469                 mutationVerified = Bytes.equals(bytes, hashCodeBytes);
470                 verificationNeeded = false;
471               }
472               if (!mutationVerified) {
473                 LOG.error("Error checking data for key [" + rowKeyStr
474                   + "], mutation checking failed for column family [" + cfStr + "], column ["
475                   + column + "]; mutation [" + mutation + "], hashCode ["
476                   + hashCode + "], verificationNeeded ["
477                   + verificationNeeded + "]");
478                 printLocations(result);
479                 return false;
480               }
481             } // end of mutation checking
482             if (verificationNeeded &&
483                 !dataGenerator.verify(result.getRow(), cf, kv.getKey(), bytes)) {
484               LOG.error("Error checking data for key [" + rowKeyStr + "], column family ["
485                 + cfStr + "], column [" + column + "], mutation [" + mutation
486                 + "]; value of length " + bytes.length);
487               printLocations(result);
488               return false;
489             }
490           }
491         }
492       }
493     }
494     return true;
495   }
496 
497   private void printLocations(Result r) {
498     RegionLocations rl = null;
499     if (r == null) {
500       LOG.info("FAILED FOR null Result");
501       return;
502     }
503     LOG.info("FAILED FOR " + resultToString(r) + " Stale " + r.isStale());
504     if (r.getRow() == null) {
505       return;
506     }
507     try {
508       rl = ((ClusterConnection)connection).locateRegion(tableName, r.getRow(), true, true);
509     } catch (IOException e) {
510       LOG.warn("Couldn't get locations for row " + Bytes.toString(r.getRow()));
511     }
512     HRegionLocation locations[] = rl.getRegionLocations();
513     for (HRegionLocation h : locations) {
514       LOG.info("LOCATION " + h);
515     }
516   }
517 
518   private String resultToString(Result result) {
519     StringBuilder sb = new StringBuilder();
520     sb.append("cells=");
521     if(result.isEmpty()) {
522       sb.append("NONE");
523       return sb.toString();
524     }
525     sb.append("{");
526     boolean moreThanOne = false;
527     for(Cell cell : result.listCells()) {
528       if(moreThanOne) {
529         sb.append(", ");
530       } else {
531         moreThanOne = true;
532       }
533       sb.append(CellUtil.toString(cell, true));
534     }
535     sb.append("}");
536     return sb.toString();
537   }
538 
539   // Parse mutate info into a map of <column name> => <update action>
540   private Map<String, MutationType> parseMutateInfo(byte[] mutateInfo) {
541     Map<String, MutationType> mi = new HashMap<String, MutationType>();
542     if (mutateInfo != null) {
543       String mutateInfoStr = Bytes.toString(mutateInfo);
544       String[] mutations = mutateInfoStr.split("#");
545       for (String mutation: mutations) {
546         if (mutation.isEmpty()) continue;
547         Preconditions.checkArgument(mutation.contains(":"),
548           "Invalid mutation info " + mutation);
549         int p = mutation.indexOf(":");
550         String column = mutation.substring(0, p);
551         MutationType type = MutationType.valueOf(
552           Integer.parseInt(mutation.substring(p+1)));
553         mi.put(column, type);
554       }
555     }
556     return mi;
557   }
558 }