1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.apache.hadoop.hbase.tool;
21
22 import static org.apache.hadoop.hbase.HConstants.DEFAULT_ZOOKEEPER_ZNODE_PARENT;
23 import static org.apache.hadoop.hbase.HConstants.ZOOKEEPER_ZNODE_PARENT;
24
25 import java.io.Closeable;
26 import java.io.IOException;
27 import java.net.InetSocketAddress;
28 import java.util.ArrayList;
29 import java.util.Arrays;
30 import java.util.Collections;
31 import java.util.EnumSet;
32 import java.util.HashMap;
33 import java.util.HashSet;
34 import java.util.LinkedList;
35 import java.util.List;
36 import java.util.Map;
37 import java.util.Random;
38 import java.util.Set;
39 import java.util.TreeSet;
40 import java.util.concurrent.Callable;
41 import java.util.concurrent.ConcurrentHashMap;
42 import java.util.concurrent.ExecutionException;
43 import java.util.concurrent.ExecutorService;
44 import java.util.concurrent.Future;
45 import java.util.concurrent.ScheduledThreadPoolExecutor;
46 import java.util.concurrent.atomic.AtomicLong;
47 import java.util.regex.Matcher;
48 import java.util.regex.Pattern;
49
50 import com.google.common.annotations.VisibleForTesting;
51 import com.google.common.collect.Lists;
52
53 import org.apache.commons.lang.time.StopWatch;
54 import org.apache.hadoop.conf.Configuration;
55 import org.apache.hadoop.hbase.AuthUtil;
56 import org.apache.hadoop.hbase.ChoreService;
57 import org.apache.hadoop.hbase.ClusterStatus;
58 import org.apache.hadoop.hbase.DoNotRetryIOException;
59 import org.apache.hadoop.hbase.HBaseConfiguration;
60 import org.apache.hadoop.hbase.HBaseInterfaceAudience;
61 import org.apache.hadoop.hbase.HColumnDescriptor;
62 import org.apache.hadoop.hbase.HConstants;
63 import org.apache.hadoop.hbase.HRegionInfo;
64 import org.apache.hadoop.hbase.HRegionLocation;
65 import org.apache.hadoop.hbase.HTableDescriptor;
66 import org.apache.hadoop.hbase.MetaTableAccessor;
67 import org.apache.hadoop.hbase.NamespaceDescriptor;
68 import org.apache.hadoop.hbase.ScheduledChore;
69 import org.apache.hadoop.hbase.ServerName;
70 import org.apache.hadoop.hbase.TableName;
71 import org.apache.hadoop.hbase.TableNotEnabledException;
72 import org.apache.hadoop.hbase.TableNotFoundException;
73 import org.apache.hadoop.hbase.classification.InterfaceAudience;
74 import org.apache.hadoop.hbase.client.Admin;
75 import org.apache.hadoop.hbase.client.Connection;
76 import org.apache.hadoop.hbase.client.ConnectionFactory;
77 import org.apache.hadoop.hbase.client.Get;
78 import org.apache.hadoop.hbase.client.Put;
79 import org.apache.hadoop.hbase.client.RegionLocator;
80 import org.apache.hadoop.hbase.client.ResultScanner;
81 import org.apache.hadoop.hbase.client.Scan;
82 import org.apache.hadoop.hbase.client.Table;
83 import org.apache.hadoop.hbase.filter.FirstKeyOnlyFilter;
84 import org.apache.hadoop.hbase.tool.CanaryTool.RegionTask.TaskType;
85 import org.apache.hadoop.hbase.util.Bytes;
86 import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
87 import org.apache.hadoop.hbase.util.Pair;
88 import org.apache.hadoop.hbase.util.ReflectionUtils;
89 import org.apache.hadoop.hbase.util.RegionSplitter;
90 import org.apache.hadoop.hbase.zookeeper.EmptyWatcher;
91 import org.apache.hadoop.hbase.zookeeper.ZKConfig;
92 import org.apache.hadoop.util.Tool;
93 import org.apache.hadoop.util.ToolRunner;
94 import org.apache.zookeeper.KeeperException;
95 import org.apache.zookeeper.ZooKeeper;
96 import org.apache.zookeeper.client.ConnectStringParser;
97 import org.apache.zookeeper.data.Stat;
98 import org.slf4j.Logger;
99 import org.slf4j.LoggerFactory;
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119 @InterfaceAudience.LimitedPrivate(HBaseInterfaceAudience.TOOLS)
120 public class CanaryTool implements Tool, Canary {
121
122 @Override
123 public int checkRegions(String[] targets) throws Exception {
124 String configuredReadTableTimeoutsStr = conf.get(HBASE_CANARY_REGION_READ_TABLE_TIMEOUT);
125 try {
126 if (configuredReadTableTimeoutsStr != null) {
127 populateReadTableTimeoutsMap(configuredReadTableTimeoutsStr);
128 }
129 } catch (IllegalArgumentException e) {
130 LOG.error("Constructing read table timeouts map failed ", e);
131 return USAGE_EXIT_CODE;
132 }
133 return runMonitor(targets);
134 }
135
136 @Override
137 public int checkRegionServers(String[] targets) throws Exception {
138 regionServerMode = true;
139 return runMonitor(targets);
140 }
141
142 @Override
143 public int checkZooKeeper() throws Exception {
144 zookeeperMode = true;
145 return runMonitor(null);
146 }
147
148
149
150
151 public interface Sink {
152 long getReadFailureCount();
153 long incReadFailureCount();
154 Map<String,String> getReadFailures();
155 void updateReadFailures(String regionName, String serverName);
156 long getWriteFailureCount();
157 long incWriteFailureCount();
158 Map<String,String> getWriteFailures();
159 void updateWriteFailures(String regionName, String serverName);
160 long getReadSuccessCount();
161 long incReadSuccessCount();
162 long getWriteSuccessCount();
163 long incWriteSuccessCount();
164 }
165
166
167
168
169 public static class StdOutSink implements Sink {
170 private AtomicLong readFailureCount = new AtomicLong(0),
171 writeFailureCount = new AtomicLong(0),
172 readSuccessCount = new AtomicLong(0),
173 writeSuccessCount = new AtomicLong(0);
174 private Map<String, String> readFailures = new ConcurrentHashMap<>();
175 private Map<String, String> writeFailures = new ConcurrentHashMap<>();
176
177 @Override
178 public long getReadFailureCount() {
179 return readFailureCount.get();
180 }
181
182 @Override
183 public long incReadFailureCount() {
184 return readFailureCount.incrementAndGet();
185 }
186
187 @Override
188 public Map<String, String> getReadFailures() {
189 return readFailures;
190 }
191
192 @Override
193 public void updateReadFailures(String regionName, String serverName) {
194 readFailures.put(regionName, serverName);
195 }
196
197 @Override
198 public long getWriteFailureCount() {
199 return writeFailureCount.get();
200 }
201
202 @Override
203 public long incWriteFailureCount() {
204 return writeFailureCount.incrementAndGet();
205 }
206
207 @Override
208 public Map<String, String> getWriteFailures() {
209 return writeFailures;
210 }
211
212 @Override
213 public void updateWriteFailures(String regionName, String serverName) {
214 writeFailures.put(regionName, serverName);
215 }
216
217 @Override
218 public long getReadSuccessCount() {
219 return readSuccessCount.get();
220 }
221
222 @Override
223 public long incReadSuccessCount() {
224 return readSuccessCount.incrementAndGet();
225 }
226
227 @Override
228 public long getWriteSuccessCount() {
229 return writeSuccessCount.get();
230 }
231
232 @Override
233 public long incWriteSuccessCount() {
234 return writeSuccessCount.incrementAndGet();
235 }
236 }
237
238
239
240
241 public static class RegionServerStdOutSink extends StdOutSink {
242 public void publishReadFailure(String table, String server) {
243 incReadFailureCount();
244 LOG.error("Read from {} on {}", table, server);
245 }
246
247 public void publishReadTiming(String table, String server, long msTime) {
248 LOG.info("Read from {} on {} in {}ms", table, server, msTime);
249 }
250 }
251
252
253
254
255 public static class ZookeeperStdOutSink extends StdOutSink {
256 public void publishReadFailure(String znode, String server) {
257 incReadFailureCount();
258 LOG.error("Read from {} on {}", znode, server);
259 }
260
261 public void publishReadTiming(String znode, String server, long msTime) {
262 LOG.info("Read from {} on {} in {}ms", znode, server, msTime);
263 }
264 }
265
266
267
268
269 public static class RegionStdOutSink extends StdOutSink {
270 private Map<String, AtomicLong> perTableReadLatency = new HashMap<>();
271 private AtomicLong writeLatency = new AtomicLong();
272 private final Map<String, RegionTaskResult> regionMap = new ConcurrentHashMap<>();
273
274 public void publishReadFailure(ServerName serverName, HRegionInfo region, Exception e) {
275 incReadFailureCount();
276 LOG.error("Read from {} on {} failed", region.getRegionNameAsString(), serverName, e);
277 }
278
279 public void publishReadFailure(ServerName serverName, HRegionInfo region,
280 HColumnDescriptor column, Exception e) {
281 incReadFailureCount();
282 LOG.error("Read from {} on {} {} failed", region.getRegionNameAsString(), serverName,
283 column.getNameAsString(), e);
284 }
285
286 public void publishReadTiming(ServerName serverName, HRegionInfo region,
287 HColumnDescriptor column, long msTime) {
288 incReadSuccessCount();
289 RegionTaskResult res = this.regionMap.get(region.getRegionNameAsString());
290 res.setReadSuccess();
291 res.setReadLatency(msTime);
292 LOG.info("Read from {} on {} {} in {}ms", region.getRegionNameAsString(), serverName,
293 column.getNameAsString(), msTime);
294 }
295
296 public void publishWriteFailure(ServerName serverName, HRegionInfo region, Exception e) {
297 incWriteFailureCount();
298 LOG.error("Write to {} on {} failed", region.getRegionNameAsString(), serverName, e);
299 }
300
301 public void publishWriteFailure(ServerName serverName, HRegionInfo region,
302 HColumnDescriptor column, Exception e) {
303 incWriteFailureCount();
304 LOG.error("Write to {} on {} {} failed", region.getRegionNameAsString(), serverName,
305 column.getNameAsString(), e);
306 }
307
308 public void publishWriteTiming(ServerName serverName, HRegionInfo region,
309 HColumnDescriptor column, long msTime) {
310 incWriteSuccessCount();
311 RegionTaskResult res = this.regionMap.get(region.getRegionNameAsString());
312 res.setWriteSuccess();
313 res.setWriteLatency(msTime);
314 LOG.info("Write to {} on {} {} in {}ms",
315 region.getRegionNameAsString(), serverName, column.getNameAsString(), msTime);
316 }
317
318 public Map<String, AtomicLong> getReadLatencyMap() {
319 return this.perTableReadLatency;
320 }
321
322 public AtomicLong initializeAndGetReadLatencyForTable(String tableName) {
323 AtomicLong initLatency = new AtomicLong();
324 this.perTableReadLatency.put(tableName, initLatency);
325 return initLatency;
326 }
327
328 public void initializeWriteLatency() {
329 this.writeLatency.set(0);
330 }
331
332 public AtomicLong getWriteLatency() {
333 return this.writeLatency;
334 }
335
336 public Map<String, RegionTaskResult> getRegionMap() {
337 return this.regionMap;
338 }
339
340 public int getTotalExpectedRegions() {
341 return this.regionMap.size();
342 }
343 }
344
345
346
347
348 static class ZookeeperTask implements Callable<Void> {
349 private final Connection connection;
350 private final String host;
351 private String znode;
352 private final int timeout;
353 private ZookeeperStdOutSink sink;
354
355 public ZookeeperTask(Connection connection, String host, String znode, int timeout,
356 ZookeeperStdOutSink sink) {
357 this.connection = connection;
358 this.host = host;
359 this.znode = znode;
360 this.timeout = timeout;
361 this.sink = sink;
362 }
363
364 @Override public Void call() throws Exception {
365 ZooKeeper zooKeeper = null;
366 try {
367 zooKeeper = new ZooKeeper(host, timeout, EmptyWatcher.instance);
368 Stat exists = zooKeeper.exists(znode, false);
369 StopWatch stopwatch = new StopWatch();
370 stopwatch.start();
371 zooKeeper.getData(znode, false, exists);
372 stopwatch.stop();
373 sink.publishReadTiming(znode, host, stopwatch.getTime());
374 } catch (KeeperException | InterruptedException e) {
375 sink.publishReadFailure(znode, host);
376 } finally {
377 if (zooKeeper != null) {
378 zooKeeper.close();
379 }
380 }
381 return null;
382 }
383 }
384
385
386
387
388
389 static class RegionTask implements Callable<Void> {
390 public enum TaskType{
391 READ, WRITE
392 }
393 private Connection connection;
394 private HRegionInfo region;
395 private RegionStdOutSink sink;
396 private TaskType taskType;
397 private boolean rawScanEnabled;
398 private ServerName serverName;
399 private AtomicLong readWriteLatency;
400
401 RegionTask(Connection connection, HRegionInfo region, ServerName serverName,
402 RegionStdOutSink sink, TaskType taskType, boolean rawScanEnabled, AtomicLong rwLatency) {
403 this.connection = connection;
404 this.region = region;
405 this.serverName = serverName;
406 this.sink = sink;
407 this.taskType = taskType;
408 this.rawScanEnabled = rawScanEnabled;
409 this.readWriteLatency = rwLatency;
410 }
411
412 @Override
413 public Void call() {
414 switch (taskType) {
415 case READ:
416 return read();
417 case WRITE:
418 return write();
419 default:
420 return read();
421 }
422 }
423
424 public Void read() {
425 Table table = null;
426 HTableDescriptor tableDesc = null;
427 try {
428 LOG.debug("Reading table descriptor for table {}", region.getTable());
429 table = connection.getTable(region.getTable());
430 tableDesc = table.getTableDescriptor();
431 } catch (IOException e) {
432 LOG.debug("sniffRegion {} of {} failed", region.getEncodedName(), e);
433 sink.publishReadFailure(serverName, region, e);
434 if (table != null) {
435 try {
436 table.close();
437 } catch (IOException ioe) {
438 LOG.error("Close table failed", e);
439 }
440 }
441 return null;
442 }
443
444 byte[] startKey = null;
445 Get get = null;
446 Scan scan = null;
447 ResultScanner rs = null;
448 StopWatch stopWatch = new StopWatch();
449 for (HColumnDescriptor column : tableDesc.getColumnFamilies()) {
450 stopWatch.reset();
451 startKey = region.getStartKey();
452
453 if (startKey.length > 0) {
454 get = new Get(startKey);
455 get.setCacheBlocks(false);
456 get.setFilter(new FirstKeyOnlyFilter());
457 get.addFamily(column.getName());
458 } else {
459 scan = new Scan();
460 LOG.debug("rawScan {} for {}", rawScanEnabled, tableDesc.getTableName());
461 scan.setRaw(rawScanEnabled);
462 scan.setCaching(1);
463 scan.setCacheBlocks(false);
464 scan.setFilter(new FirstKeyOnlyFilter());
465 scan.addFamily(column.getName());
466 scan.setMaxResultSize(1L);
467 scan.setSmall(true);
468 }
469 LOG.debug("Reading from {} {} {} {}", tableDesc.getTableName(),
470 region.getRegionNameAsString(), column.getNameAsString(),
471 Bytes.toStringBinary(startKey));
472 try {
473 stopWatch.start();
474 if (startKey.length > 0) {
475 table.get(get);
476 } else {
477 rs = table.getScanner(scan);
478 rs.next();
479 }
480 stopWatch.stop();
481 this.readWriteLatency.addAndGet(stopWatch.getTime());
482 sink.publishReadTiming(serverName, region, column, stopWatch.getTime());
483 } catch (Exception e) {
484 sink.publishReadFailure(serverName, region, column, e);
485 sink.updateReadFailures(region.getRegionNameAsString(), serverName.getHostname());
486 } finally {
487 if (rs != null) {
488 rs.close();
489 }
490 scan = null;
491 get = null;
492 }
493 }
494 try {
495 table.close();
496 } catch (IOException e) {
497 LOG.error("Close table failed", e);
498 }
499 return null;
500 }
501
502
503
504
505 private Void write() {
506 Table table = null;
507 HTableDescriptor tableDesc = null;
508 try {
509 table = connection.getTable(region.getTable());
510 tableDesc = table.getTableDescriptor();
511 byte[] rowToCheck = region.getStartKey();
512 if (rowToCheck.length == 0) {
513 rowToCheck = new byte[]{0x0};
514 }
515 int writeValueSize =
516 connection.getConfiguration().getInt(HConstants.HBASE_CANARY_WRITE_VALUE_SIZE_KEY, 10);
517 for (HColumnDescriptor column : tableDesc.getColumnFamilies()) {
518 Put put = new Put(rowToCheck);
519 byte[] value = new byte[writeValueSize];
520 Bytes.random(value);
521 put.addColumn(column.getName(), HConstants.EMPTY_BYTE_ARRAY, value);
522
523 LOG.debug("Writing to {} {} {} {}",
524 tableDesc.getTableName(), region.getRegionNameAsString(), column.getNameAsString(),
525 Bytes.toStringBinary(rowToCheck));
526 try {
527 long startTime = System.currentTimeMillis();
528 table.put(put);
529 long time = System.currentTimeMillis() - startTime;
530 this.readWriteLatency.addAndGet(time);
531 sink.publishWriteTiming(serverName, region, column, time);
532 } catch (Exception e) {
533 sink.publishWriteFailure(serverName, region, column, e);
534 }
535 }
536 table.close();
537 } catch (IOException e) {
538 sink.publishWriteFailure(serverName, region, e);
539 sink.updateWriteFailures(region.getRegionNameAsString(), serverName.getHostname() );
540 }
541 return null;
542 }
543 }
544
545
546
547
548
549 static class RegionServerTask implements Callable<Void> {
550 private Connection connection;
551 private String serverName;
552 private HRegionInfo region;
553 private RegionServerStdOutSink sink;
554 private AtomicLong successes;
555
556 RegionServerTask(Connection connection, String serverName, HRegionInfo region,
557 RegionServerStdOutSink sink, AtomicLong successes) {
558 this.connection = connection;
559 this.serverName = serverName;
560 this.region = region;
561 this.sink = sink;
562 this.successes = successes;
563 }
564
565 @Override
566 public Void call() {
567 TableName tableName = null;
568 Table table = null;
569 Get get = null;
570 byte[] startKey = null;
571 Scan scan = null;
572 StopWatch stopWatch = new StopWatch();
573
574 stopWatch.reset();
575 try {
576 tableName = region.getTable();
577 table = connection.getTable(tableName);
578 startKey = region.getStartKey();
579
580 LOG.debug("Reading from {} {} {} {}",
581 serverName, region.getTable(), region.getRegionNameAsString(),
582 Bytes.toStringBinary(startKey));
583 if (startKey.length > 0) {
584 get = new Get(startKey);
585 get.setCacheBlocks(false);
586 get.setFilter(new FirstKeyOnlyFilter());
587 stopWatch.start();
588 table.get(get);
589 stopWatch.stop();
590 } else {
591 scan = new Scan();
592 scan.setCacheBlocks(false);
593 scan.setFilter(new FirstKeyOnlyFilter());
594 scan.setCaching(1);
595 scan.setMaxResultSize(1L);
596 scan.setSmall(true);
597 stopWatch.start();
598 ResultScanner s = table.getScanner(scan);
599 s.next();
600 s.close();
601 stopWatch.stop();
602 }
603 successes.incrementAndGet();
604 sink.publishReadTiming(tableName.getNameAsString(), serverName, stopWatch.getTime());
605 } catch (TableNotFoundException tnfe) {
606 LOG.error("Table may be deleted", tnfe);
607
608 } catch (TableNotEnabledException tnee) {
609
610 successes.incrementAndGet();
611 LOG.debug("The targeted table was disabled. Assuming success.");
612 } catch (DoNotRetryIOException dnrioe) {
613 sink.publishReadFailure(tableName.getNameAsString(), serverName);
614 LOG.error(dnrioe.toString(), dnrioe);
615 } catch (IOException e) {
616 sink.publishReadFailure(tableName.getNameAsString(), serverName);
617 LOG.error(e.toString(), e);
618 } finally {
619 if (table != null) {
620 try {
621 table.close();
622 } catch (IOException e) {
623 LOG.error("Close table failed", e);
624 }
625 }
626 scan = null;
627 get = null;
628 startKey = null;
629 }
630 return null;
631 }
632 }
633
634 private static final int USAGE_EXIT_CODE = 1;
635 private static final int INIT_ERROR_EXIT_CODE = 2;
636 private static final int TIMEOUT_ERROR_EXIT_CODE = 3;
637 private static final int ERROR_EXIT_CODE = 4;
638 private static final int FAILURE_EXIT_CODE = 5;
639
640 private static final long DEFAULT_INTERVAL = 60000;
641
642 private static final long DEFAULT_TIMEOUT = 600000;
643 private static final int MAX_THREADS_NUM = 16;
644
645 private static final Logger LOG = LoggerFactory.getLogger(Canary.class);
646
647 public static final TableName DEFAULT_WRITE_TABLE_NAME = TableName.valueOf(
648 NamespaceDescriptor.SYSTEM_NAMESPACE_NAME_STR, "canary");
649
650 private static final String CANARY_TABLE_FAMILY_NAME = "Test";
651
652 private Configuration conf = null;
653 private long interval = 0;
654 private Sink sink = null;
655
656
657
658
659 private boolean regionServerMode = false;
660
661
662
663
664 private boolean zookeeperMode = false;
665
666
667
668
669
670
671 private HashMap<String, Long> configuredReadTableTimeouts = new HashMap<>();
672
673 public static final String HBASE_CANARY_REGIONSERVER_ALL_REGIONS
674 = "hbase.canary.regionserver_all_regions";
675
676 public static final String HBASE_CANARY_REGION_WRITE_SNIFFING
677 = "hbase.canary.region.write.sniffing";
678 public static final String HBASE_CANARY_REGION_WRITE_TABLE_TIMEOUT
679 = "hbase.canary.region.write.table.timeout";
680 public static final String HBASE_CANARY_REGION_WRITE_TABLE_NAME
681 = "hbase.canary.region.write.table.name";
682 public static final String HBASE_CANARY_REGION_READ_TABLE_TIMEOUT
683 = "hbase.canary.region.read.table.timeout";
684
685 public static final String HBASE_CANARY_ZOOKEEPER_PERMITTED_FAILURES
686 = "hbase.canary.zookeeper.permitted.failures";
687
688 public static final String HBASE_CANARY_USE_REGEX = "hbase.canary.use.regex";
689 public static final String HBASE_CANARY_TIMEOUT = "hbase.canary.timeout";
690 public static final String HBASE_CANARY_FAIL_ON_ERROR = "hbase.canary.fail.on.error";
691
692
693 private ExecutorService executor;
694
695 public CanaryTool() {
696 this(new ScheduledThreadPoolExecutor(1));
697 }
698
699 public CanaryTool(ExecutorService executor) {
700 this(executor, null);
701 }
702
703 @VisibleForTesting
704 CanaryTool(ExecutorService executor, Sink sink) {
705 this.executor = executor;
706 this.sink = sink;
707 }
708
709 CanaryTool(Configuration conf, ExecutorService executor) {
710 this(conf, executor, null);
711 }
712
713 CanaryTool(Configuration conf, ExecutorService executor, Sink sink) {
714 this(executor, sink);
715 setConf(conf);
716 }
717
718 @Override
719 public Configuration getConf() {
720 return conf;
721 }
722
723 @Override
724 public void setConf(Configuration conf) {
725 if (conf == null) {
726 conf = HBaseConfiguration.create();
727 }
728 this.conf = conf;
729 }
730
731 private int parseArgs(String[] args) {
732 int index = -1;
733 long permittedFailures = 0;
734 boolean regionServerAllRegions = false, writeSniffing = false;
735 String readTableTimeoutsStr = null;
736
737
738 for (int i = 0; i < args.length; i++) {
739 String cmd = args[i];
740
741 if (cmd.startsWith("-")) {
742 if (index >= 0) {
743
744 System.err.println("Invalid command line options");
745 printUsageAndExit();
746 }
747
748 if (cmd.equals("-help") || cmd.equals("-h")) {
749
750 printUsageAndExit();
751 } else if (cmd.equals("-daemon") && interval == 0) {
752
753 interval = DEFAULT_INTERVAL;
754 } else if (cmd.equals("-interval")) {
755
756 i++;
757
758 if (i == args.length) {
759 System.err.println("-interval takes a numeric seconds value argument.");
760 printUsageAndExit();
761 }
762
763 try {
764 interval = Long.parseLong(args[i]) * 1000;
765 } catch (NumberFormatException e) {
766 System.err.println("-interval needs a numeric value argument.");
767 printUsageAndExit();
768 }
769 } else if (cmd.equals("-zookeeper")) {
770 this.zookeeperMode = true;
771 } else if(cmd.equals("-regionserver")) {
772 this.regionServerMode = true;
773 } else if(cmd.equals("-allRegions")) {
774 conf.setBoolean(HBASE_CANARY_REGIONSERVER_ALL_REGIONS, true);
775 regionServerAllRegions = true;
776 } else if(cmd.equals("-writeSniffing")) {
777 writeSniffing = true;
778 conf.setBoolean(HBASE_CANARY_REGION_WRITE_SNIFFING, true);
779 } else if(cmd.equals("-treatFailureAsError") || cmd.equals("-failureAsError")) {
780 conf.setBoolean(HBASE_CANARY_FAIL_ON_ERROR, true);
781 } else if (cmd.equals("-e")) {
782 conf.setBoolean(HBASE_CANARY_USE_REGEX, true);
783 } else if (cmd.equals("-t")) {
784 i++;
785
786 if (i == args.length) {
787 System.err.println("-t takes a numeric milliseconds value argument.");
788 printUsageAndExit();
789 }
790 long timeout = 0;
791 try {
792 timeout = Long.parseLong(args[i]);
793 } catch (NumberFormatException e) {
794 System.err.println("-t takes a numeric milliseconds value argument.");
795 printUsageAndExit();
796 }
797 conf.setLong(HBASE_CANARY_TIMEOUT, timeout);
798 } else if(cmd.equals("-writeTableTimeout")) {
799 i++;
800
801 if (i == args.length) {
802 System.err.println("-writeTableTimeout takes a numeric milliseconds value argument.");
803 printUsageAndExit();
804 }
805 long configuredWriteTableTimeout = 0;
806 try {
807 configuredWriteTableTimeout = Long.parseLong(args[i]);
808 } catch (NumberFormatException e) {
809 System.err.println("-writeTableTimeout takes a numeric milliseconds value argument.");
810 printUsageAndExit();
811 }
812 conf.setLong(HBASE_CANARY_REGION_WRITE_TABLE_TIMEOUT, configuredWriteTableTimeout);
813 } else if (cmd.equals("-writeTable")) {
814 i++;
815
816 if (i == args.length) {
817 System.err.println("-writeTable takes a string tablename value argument.");
818 printUsageAndExit();
819 }
820 conf.set(HBASE_CANARY_REGION_WRITE_TABLE_NAME, args[i]);
821 } else if (cmd.equals("-f")) {
822 i++;
823
824 if (i == args.length) {
825 System.err
826 .println("-f needs a boolean value argument (true|false).");
827 printUsageAndExit();
828 }
829
830 conf.setBoolean(HBASE_CANARY_FAIL_ON_ERROR, Boolean.parseBoolean(args[i]));
831 } else if (cmd.equals("-readTableTimeouts")) {
832 i++;
833
834 if (i == args.length) {
835 System.err.println("-readTableTimeouts needs a comma-separated list of read " +
836 "millisecond timeouts per table (without spaces).");
837 printUsageAndExit();
838 }
839 readTableTimeoutsStr = args[i];
840 conf.set(HBASE_CANARY_REGION_READ_TABLE_TIMEOUT, readTableTimeoutsStr);
841 } else if (cmd.equals("-permittedZookeeperFailures")) {
842 i++;
843
844 if (i == args.length) {
845 System.err.println("-permittedZookeeperFailures needs a numeric value argument.");
846 printUsageAndExit();
847 }
848 try {
849 permittedFailures = Long.parseLong(args[i]);
850 } catch (NumberFormatException e) {
851 System.err.println("-permittedZookeeperFailures needs a numeric value argument.");
852 printUsageAndExit();
853 }
854 conf.setLong(HBASE_CANARY_ZOOKEEPER_PERMITTED_FAILURES, permittedFailures);
855 } else {
856
857 System.err.println(cmd + " options is invalid.");
858 printUsageAndExit();
859 }
860 } else if (index < 0) {
861
862 index = i;
863 }
864 }
865 if (regionServerAllRegions && !this.regionServerMode) {
866 System.err.println("-allRegions can only be specified in regionserver mode.");
867 printUsageAndExit();
868 }
869 if (this.zookeeperMode) {
870 if (this.regionServerMode || regionServerAllRegions || writeSniffing) {
871 System.err.println("-zookeeper is exclusive and cannot be combined with "
872 + "other modes.");
873 printUsageAndExit();
874 }
875 }
876 if (permittedFailures != 0 && !this.zookeeperMode) {
877 System.err.println("-permittedZookeeperFailures requires -zookeeper mode.");
878 printUsageAndExit();
879 }
880 if (readTableTimeoutsStr != null && (this.regionServerMode || this.zookeeperMode)) {
881 System.err.println("-readTableTimeouts can only be configured in region mode.");
882 printUsageAndExit();
883 }
884 return index;
885 }
886
887 @Override
888 public int run(String[] args) throws Exception {
889 int index = parseArgs(args);
890 String[] monitorTargets = null;
891
892 if (index >= 0) {
893 int length = args.length - index;
894 monitorTargets = new String[length];
895 System.arraycopy(args, index, monitorTargets, 0, length);
896 }
897
898 if (zookeeperMode) {
899 return checkZooKeeper();
900 } else if (regionServerMode) {
901 return checkRegionServers(monitorTargets);
902 } else {
903 return checkRegions(monitorTargets);
904 }
905 }
906
907 private int runMonitor(String[] monitorTargets) throws Exception {
908 ChoreService choreService = null;
909
910
911
912
913 final ScheduledChore authChore = AuthUtil.getAuthChore(conf);
914 if (authChore != null) {
915 choreService = new ChoreService("CANARY_TOOL");
916 choreService.scheduleChore(authChore);
917 }
918
919
920 Monitor monitor = null;
921 Thread monitorThread;
922 long startTime = 0;
923 long currentTimeLength = 0;
924 boolean failOnError = conf.getBoolean(HBASE_CANARY_FAIL_ON_ERROR, true);
925 long timeout = conf.getLong(HBASE_CANARY_TIMEOUT, DEFAULT_TIMEOUT);
926
927 try (Connection connection = ConnectionFactory.createConnection(this.conf)) {
928 do {
929
930 try {
931 monitor = this.newMonitor(connection, monitorTargets);
932 monitorThread = new Thread(monitor, "CanaryMonitor-" + System.currentTimeMillis());
933 startTime = System.currentTimeMillis();
934 monitorThread.start();
935 while (!monitor.isDone()) {
936
937 Thread.sleep(1000);
938
939 if (failOnError && monitor.hasError()) {
940 monitorThread.interrupt();
941 if (monitor.initialized) {
942 return monitor.errorCode;
943 } else {
944 return INIT_ERROR_EXIT_CODE;
945 }
946 }
947 currentTimeLength = System.currentTimeMillis() - startTime;
948 if (currentTimeLength > timeout) {
949 LOG.error("The monitor is running too long (" + currentTimeLength
950 + ") after timeout limit:" + timeout
951 + " will be killed itself !!");
952 if (monitor.initialized) {
953 return TIMEOUT_ERROR_EXIT_CODE;
954 } else {
955 return INIT_ERROR_EXIT_CODE;
956 }
957 }
958 }
959
960 if (failOnError && monitor.finalCheckForErrors()) {
961 monitorThread.interrupt();
962 return monitor.errorCode;
963 }
964 } finally {
965 if (monitor != null) monitor.close();
966 }
967
968 Thread.sleep(interval);
969 } while (interval > 0);
970 }
971
972 if (choreService != null) {
973 choreService.shutdown();
974 }
975 return monitor.errorCode;
976 }
977
978 @Override
979 public Map<String, String> getReadFailures() {
980 return sink.getReadFailures();
981 }
982
983 @Override
984 public Map<String, String> getWriteFailures() {
985 return sink.getWriteFailures();
986 }
987
988 private void printUsageAndExit() {
989 System.err.println(
990 "Usage: canary [OPTIONS] [<TABLE1> [<TABLE2]...] | [<REGIONSERVER1> [<REGIONSERVER2]..]");
991 System.err.println("Where [OPTIONS] are:");
992 System.err.println(" -h,-help show this help and exit.");
993 System.err.println(" -regionserver set 'regionserver mode'; gets row from random region on " +
994 "server");
995 System.err.println(" -allRegions get from ALL regions when 'regionserver mode', not just " +
996 "random one.");
997 System.err.println(" -zookeeper set 'zookeeper mode'; grab zookeeper.znode.parent on " +
998 "each ensemble member");
999 System.err.println(" -daemon continuous check at defined intervals.");
1000 System.err.println(" -interval <N> interval between checks in seconds");
1001 System.err.println(" -e consider table/regionserver argument as regular " +
1002 "expression");
1003 System.err.println(" -f <B> exit on first error; default=true");
1004 System.err.println(" -failureAsError treat read/write failure as error");
1005 System.err.println(" -t <N> timeout for canary-test run; default=600000ms");
1006 System.err.println(" -writeSniffing enable write sniffing");
1007 System.err.println(" -writeTable the table used for write sniffing; default=hbase:canary");
1008 System.err.println(" -writeTableTimeout <N> timeout for writeTable; default=600000ms");
1009 System.err.println(" -readTableTimeouts <tableName>=<read timeout>," +
1010 "<tableName>=<read timeout>,...");
1011 System.err.println(" comma-separated list of table read timeouts " +
1012 "(no spaces);");
1013 System.err.println(" logs 'ERROR' if takes longer. default=600000ms");
1014 System.err.println(" -permittedZookeeperFailures <N> Ignore first N failures attempting to ");
1015 System.err.println(" connect to individual zookeeper nodes in ensemble");
1016 System.err.println("");
1017 System.err.println(" -D<configProperty>=<value> to assign or override configuration params");
1018 System.err.println(" -Dhbase.canary.read.raw.enabled=<true/false> Set to enable/disable " +
1019 "raw scan; default=false");
1020 System.err.println("");
1021 System.err.println("Canary runs in one of three modes: region (default), regionserver, or " +
1022 "zookeeper.");
1023 System.err.println("To sniff/probe all regions, pass no arguments.");
1024 System.err.println("To sniff/probe all regions of a table, pass tablename.");
1025 System.err.println("To sniff/probe regionservers, pass -regionserver, etc.");
1026 System.err.println("See http://hbase.apache.org/book.html#_canary for Canary documentation.");
1027 System.exit(USAGE_EXIT_CODE);
1028 }
1029
1030 Sink getSink(Configuration configuration, Class clazz) {
1031
1032 return this.sink != null? this.sink:
1033 (Sink)ReflectionUtils.newInstance(configuration.getClass("hbase.canary.sink.class",
1034 clazz, Sink.class));
1035 }
1036
1037
1038
1039
1040
1041 public static class RegionTaskResult {
1042 private HRegionInfo region;
1043 private TableName tableName;
1044 private ServerName serverName;
1045 private AtomicLong readLatency = null;
1046 private AtomicLong writeLatency = null;
1047 private boolean readSuccess = false;
1048 private boolean writeSuccess = false;
1049
1050 public RegionTaskResult(HRegionInfo region, TableName tableName, ServerName serverName) {
1051 this.region = region;
1052 this.tableName = tableName;
1053 this.serverName = serverName;
1054 }
1055
1056 public HRegionInfo getRegionInfo() {
1057 return this.region;
1058 }
1059
1060 public String getRegionNameAsString() {
1061 return this.region.getRegionNameAsString();
1062 }
1063
1064 public TableName getTableName() {
1065 return this.tableName;
1066 }
1067
1068 public String getTableNameAsString() {
1069 return this.tableName.getNameAsString();
1070 }
1071
1072 public ServerName getServerName() {
1073 return this.serverName;
1074 }
1075
1076 public String getServerNameAsString() {
1077 return this.serverName.getServerName();
1078 }
1079
1080 public long getReadLatency() {
1081 if (this.readLatency == null) {
1082 return -1;
1083 }
1084 return this.readLatency.get();
1085 }
1086
1087 public void setReadLatency(long readLatency) {
1088 if (this.readLatency != null) {
1089 this.readLatency.set(readLatency);
1090 } else {
1091 this.readLatency = new AtomicLong(readLatency);
1092 }
1093 }
1094
1095 public long getWriteLatency() {
1096 if (this.writeLatency == null) {
1097 return -1;
1098 }
1099 return this.writeLatency.get();
1100 }
1101
1102 public void setWriteLatency(long writeLatency) {
1103 if (this.writeLatency != null) {
1104 this.writeLatency.set(writeLatency);
1105 } else {
1106 this.writeLatency = new AtomicLong(writeLatency);
1107 }
1108 }
1109
1110 public boolean isReadSuccess() {
1111 return this.readSuccess;
1112 }
1113
1114 public void setReadSuccess() {
1115 this.readSuccess = true;
1116 }
1117
1118 public boolean isWriteSuccess() {
1119 return this.writeSuccess;
1120 }
1121
1122 public void setWriteSuccess() {
1123 this.writeSuccess = true;
1124 }
1125 }
1126
1127
1128
1129
1130
1131
1132 private Monitor newMonitor(final Connection connection, String[] monitorTargets) {
1133 Monitor monitor;
1134 boolean useRegExp = conf.getBoolean(HBASE_CANARY_USE_REGEX, false);
1135 boolean regionServerAllRegions
1136 = conf.getBoolean(HBASE_CANARY_REGIONSERVER_ALL_REGIONS, false);
1137 boolean failOnError
1138 = conf.getBoolean(HBASE_CANARY_FAIL_ON_ERROR, true);
1139 int permittedFailures
1140 = conf.getInt(HBASE_CANARY_ZOOKEEPER_PERMITTED_FAILURES, 0);
1141 boolean writeSniffing
1142 = conf.getBoolean(HBASE_CANARY_REGION_WRITE_SNIFFING, false);
1143 String writeTableName = conf.get(HBASE_CANARY_REGION_WRITE_TABLE_NAME,
1144 DEFAULT_WRITE_TABLE_NAME.getNameAsString());
1145 long configuredWriteTableTimeout
1146 = conf.getLong(HBASE_CANARY_REGION_WRITE_TABLE_TIMEOUT, DEFAULT_TIMEOUT);
1147
1148 if (this.regionServerMode) {
1149 monitor =
1150 new RegionServerMonitor(connection, monitorTargets, useRegExp,
1151 getSink(connection.getConfiguration(), RegionServerStdOutSink.class),
1152 this.executor, regionServerAllRegions,
1153 failOnError, permittedFailures);
1154
1155 } else if (this.zookeeperMode) {
1156 monitor =
1157 new ZookeeperMonitor(connection, monitorTargets, useRegExp,
1158 getSink(connection.getConfiguration(), ZookeeperStdOutSink.class),
1159 this.executor, failOnError, permittedFailures);
1160 } else {
1161 monitor =
1162 new RegionMonitor(connection, monitorTargets, useRegExp,
1163 getSink(connection.getConfiguration(), RegionStdOutSink.class),
1164 this.executor, writeSniffing,
1165 TableName.valueOf(writeTableName), failOnError, configuredReadTableTimeouts,
1166 configuredWriteTableTimeout, permittedFailures);
1167 }
1168 return monitor;
1169 }
1170
1171 private void populateReadTableTimeoutsMap(String configuredReadTableTimeoutsStr) {
1172 String[] tableTimeouts = configuredReadTableTimeoutsStr.split(",");
1173 for (String tT : tableTimeouts) {
1174 String[] nameTimeout = tT.split("=");
1175 if (nameTimeout.length < 2) {
1176 throw new IllegalArgumentException("Each -readTableTimeouts argument must be of the form " +
1177 "<tableName>=<read timeout> (without spaces).");
1178 }
1179 long timeoutVal;
1180 try {
1181 timeoutVal = Long.parseLong(nameTimeout[1]);
1182 } catch (NumberFormatException e) {
1183 throw new IllegalArgumentException("-readTableTimeouts read timeout for each table" +
1184 " must be a numeric value argument.");
1185 }
1186 configuredReadTableTimeouts.put(nameTimeout[0], timeoutVal);
1187 }
1188 }
1189
1190
1191
1192 public static abstract class Monitor implements Runnable, Closeable {
1193 protected Connection connection;
1194 protected Admin admin;
1195
1196
1197
1198
1199 protected String[] targets;
1200 protected boolean useRegExp;
1201 protected boolean treatFailureAsError;
1202 protected boolean initialized = false;
1203
1204 protected boolean done = false;
1205 protected int errorCode = 0;
1206 protected long allowedFailures = 0;
1207 protected Sink sink;
1208 protected ExecutorService executor;
1209
1210 public boolean isDone() {
1211 return done;
1212 }
1213
1214 public boolean hasError() {
1215 return errorCode != 0;
1216 }
1217
1218 public boolean finalCheckForErrors() {
1219 if (errorCode != 0) {
1220 return true;
1221 }
1222 if (treatFailureAsError &&
1223 (sink.getReadFailureCount() > allowedFailures || sink.getWriteFailureCount() > allowedFailures)) {
1224 LOG.error("Too many failures detected, treating failure as error, failing the Canary.");
1225 errorCode = FAILURE_EXIT_CODE;
1226 return true;
1227 }
1228 return false;
1229 }
1230
1231 @Override
1232 public void close() throws IOException {
1233 if (this.admin != null) this.admin.close();
1234 }
1235
1236 protected Monitor(Connection connection, String[] monitorTargets, boolean useRegExp, Sink sink,
1237 ExecutorService executor, boolean treatFailureAsError, long allowedFailures) {
1238 if (null == connection) throw new IllegalArgumentException("connection shall not be null");
1239
1240 this.connection = connection;
1241 this.targets = monitorTargets;
1242 this.useRegExp = useRegExp;
1243 this.treatFailureAsError = treatFailureAsError;
1244 this.sink = sink;
1245 this.executor = executor;
1246 this.allowedFailures = allowedFailures;
1247 }
1248
1249 @Override
1250 public abstract void run();
1251
1252 protected boolean initAdmin() {
1253 if (null == this.admin) {
1254 try {
1255 this.admin = this.connection.getAdmin();
1256 } catch (Exception e) {
1257 LOG.error("Initial HBaseAdmin failed...", e);
1258 this.errorCode = INIT_ERROR_EXIT_CODE;
1259 }
1260 } else if (admin.isAborted()) {
1261 LOG.error("HBaseAdmin aborted");
1262 this.errorCode = INIT_ERROR_EXIT_CODE;
1263 }
1264 return !this.hasError();
1265 }
1266 }
1267
1268
1269
1270
1271 private static class RegionMonitor extends Monitor {
1272
1273 private static final int DEFAULT_WRITE_TABLE_CHECK_PERIOD = 10 * 60 * 1000;
1274
1275 private static final int DEFAULT_WRITE_DATA_TTL = 24 * 60 * 60;
1276
1277 private long lastCheckTime = -1;
1278 private boolean writeSniffing;
1279 private TableName writeTableName;
1280 private int writeDataTTL;
1281 private float regionsLowerLimit;
1282 private float regionsUpperLimit;
1283 private int checkPeriod;
1284 private boolean rawScanEnabled;
1285
1286
1287
1288
1289
1290 private HashMap<String, Long> configuredReadTableTimeouts;
1291
1292 private long configuredWriteTableTimeout;
1293
1294 public RegionMonitor(Connection connection, String[] monitorTargets, boolean useRegExp,
1295 Sink sink, ExecutorService executor, boolean writeSniffing, TableName writeTableName,
1296 boolean treatFailureAsError, HashMap<String, Long> configuredReadTableTimeouts,
1297 long configuredWriteTableTimeout,
1298 long allowedFailures) {
1299 super(connection, monitorTargets, useRegExp, sink, executor, treatFailureAsError,
1300 allowedFailures);
1301 Configuration conf = connection.getConfiguration();
1302 this.writeSniffing = writeSniffing;
1303 this.writeTableName = writeTableName;
1304 this.writeDataTTL =
1305 conf.getInt(HConstants.HBASE_CANARY_WRITE_DATA_TTL_KEY, DEFAULT_WRITE_DATA_TTL);
1306 this.regionsLowerLimit =
1307 conf.getFloat(HConstants.HBASE_CANARY_WRITE_PERSERVER_REGIONS_LOWERLIMIT_KEY, 1.0f);
1308 this.regionsUpperLimit =
1309 conf.getFloat(HConstants.HBASE_CANARY_WRITE_PERSERVER_REGIONS_UPPERLIMIT_KEY, 1.5f);
1310 this.checkPeriod =
1311 conf.getInt(HConstants.HBASE_CANARY_WRITE_TABLE_CHECK_PERIOD_KEY,
1312 DEFAULT_WRITE_TABLE_CHECK_PERIOD);
1313 this.rawScanEnabled = conf.getBoolean(HConstants.HBASE_CANARY_READ_RAW_SCAN_KEY, false);
1314 this.configuredReadTableTimeouts = new HashMap<>(configuredReadTableTimeouts);
1315 this.configuredWriteTableTimeout = configuredWriteTableTimeout;
1316 }
1317
1318 private RegionStdOutSink getSink() {
1319 if (!(sink instanceof RegionStdOutSink)) {
1320 throw new RuntimeException("Can only write to Region sink");
1321 }
1322 return ((RegionStdOutSink) sink);
1323 }
1324
1325 @Override
1326 public void run() {
1327 if (this.initAdmin()) {
1328 try {
1329 List<Future<Void>> taskFutures = new LinkedList<>();
1330 RegionStdOutSink regionSink = this.getSink();
1331 if (this.targets != null && this.targets.length > 0) {
1332 String[] tables = generateMonitorTables(this.targets);
1333
1334
1335 if (!new HashSet<>(Arrays.asList(tables)).
1336 containsAll(this.configuredReadTableTimeouts.keySet())) {
1337 LOG.error("-readTableTimeouts can only specify read timeouts for monitor targets " +
1338 "passed via command line.");
1339 this.errorCode = USAGE_EXIT_CODE;
1340 return;
1341 }
1342 this.initialized = true;
1343 for (String table : tables) {
1344 AtomicLong readLatency = regionSink.initializeAndGetReadLatencyForTable(table);
1345 taskFutures.addAll(CanaryTool.sniff(admin, regionSink, table, executor, TaskType.READ,
1346 this.rawScanEnabled, readLatency));
1347 }
1348 } else {
1349 taskFutures.addAll(sniff(TaskType.READ, regionSink));
1350 }
1351
1352 if (writeSniffing) {
1353 if (EnvironmentEdgeManager.currentTime() - lastCheckTime > checkPeriod) {
1354 try {
1355 checkWriteTableDistribution();
1356 } catch (IOException e) {
1357 LOG.error("Check canary table distribution failed!", e);
1358 }
1359 lastCheckTime = EnvironmentEdgeManager.currentTime();
1360 }
1361
1362 regionSink.initializeWriteLatency();
1363 AtomicLong writeTableLatency = regionSink.getWriteLatency();
1364 taskFutures.addAll(CanaryTool.sniff(admin, regionSink, admin.getTableDescriptor(writeTableName),
1365 executor, TaskType.WRITE, this.rawScanEnabled, writeTableLatency));
1366 }
1367
1368 for (Future<Void> future : taskFutures) {
1369 try {
1370 future.get();
1371 } catch (ExecutionException e) {
1372 LOG.error("Sniff region failed!", e);
1373 }
1374 }
1375 Map<String, AtomicLong> actualReadTableLatency = regionSink.getReadLatencyMap();
1376 for (Map.Entry<String, Long> entry : configuredReadTableTimeouts.entrySet()) {
1377 String tableName = entry.getKey();
1378 if (actualReadTableLatency.containsKey(tableName)) {
1379 Long actual = actualReadTableLatency.get(tableName).longValue();
1380 Long configured = entry.getValue();
1381 if (actual > configured) {
1382 LOG.error("Read operation for {} took {}ms exceeded the configured read timeout." +
1383 "(Configured read timeout {}ms.", tableName, actual, configured);
1384 } else {
1385 LOG.info("Read operation for {} took {}ms (Configured read timeout {}ms.",
1386 tableName, actual, configured);
1387 }
1388 } else {
1389 LOG.error("Read operation for {} failed!", tableName);
1390 }
1391 }
1392 if (this.writeSniffing) {
1393 String writeTableStringName = this.writeTableName.getNameAsString();
1394 long actualWriteLatency = regionSink.getWriteLatency().longValue();
1395 LOG.info("Write operation for {} took {}ms. Configured write timeout {}ms.",
1396 writeTableStringName, actualWriteLatency, this.configuredWriteTableTimeout);
1397
1398 if (actualWriteLatency > this.configuredWriteTableTimeout) {
1399 LOG.error("Write operation for {} exceeded the configured write timeout.",
1400 writeTableStringName);
1401 }
1402 }
1403 } catch (Exception e) {
1404 LOG.error("Run regionMonitor failed", e);
1405 this.errorCode = ERROR_EXIT_CODE;
1406 } finally {
1407 this.done = true;
1408 }
1409 }
1410 this.done = true;
1411 }
1412
1413
1414
1415
1416 private String[] generateMonitorTables(String[] monitorTargets) throws IOException {
1417 String[] returnTables = null;
1418
1419 if (this.useRegExp) {
1420 Pattern pattern = null;
1421 HTableDescriptor[] tds = null;
1422 Set<String> tmpTables = new TreeSet<>();
1423 try {
1424 LOG.debug(String.format("reading list of tables"));
1425 tds = this.admin.listTables(pattern);
1426 if (tds == null) {
1427 tds = new HTableDescriptor[] {};
1428 }
1429 for (String monitorTarget : monitorTargets) {
1430 pattern = Pattern.compile(monitorTarget);
1431 for (HTableDescriptor td : tds) {
1432 if (pattern.matcher(td.getTableName().getNameAsString()).matches()) {
1433 tmpTables.add(td.getTableName().getNameAsString());
1434 }
1435 }
1436 }
1437 } catch (IOException e) {
1438 LOG.error("Communicate with admin failed", e);
1439 throw e;
1440 }
1441
1442 if (tmpTables.size() > 0) {
1443 returnTables = tmpTables.toArray(new String[tmpTables.size()]);
1444 } else {
1445 String msg = "No HTable found, tablePattern:" + Arrays.toString(monitorTargets);
1446 LOG.error(msg);
1447 this.errorCode = INIT_ERROR_EXIT_CODE;
1448 throw new TableNotFoundException(msg);
1449 }
1450 } else {
1451 returnTables = monitorTargets;
1452 }
1453
1454 return returnTables;
1455 }
1456
1457
1458
1459
1460 private List<Future<Void>> sniff(TaskType taskType, RegionStdOutSink regionSink)
1461 throws Exception {
1462 LOG.debug("Reading list of tables");
1463 List<Future<Void>> taskFutures = new LinkedList<>();
1464 for (HTableDescriptor td: admin.listTables()) {
1465 if (admin.tableExists(td.getTableName()) && admin.isTableEnabled(td.getTableName()) &&
1466 (!td.getTableName().equals(writeTableName))) {
1467 AtomicLong readLatency =
1468 regionSink.initializeAndGetReadLatencyForTable(td.getTableName().getNameAsString());
1469 taskFutures.addAll(CanaryTool.sniff(admin, sink, td, executor, taskType, this.rawScanEnabled,
1470 readLatency));
1471 }
1472 }
1473 return taskFutures;
1474 }
1475
1476 private void checkWriteTableDistribution() throws IOException {
1477 if (!admin.tableExists(writeTableName)) {
1478 int numberOfServers =
1479 admin.getClusterStatus().getServersSize();
1480 if (numberOfServers == 0) {
1481 throw new IllegalStateException("No live regionservers");
1482 }
1483 createWriteTable(numberOfServers);
1484 }
1485
1486 if (!admin.isTableEnabled(writeTableName)) {
1487 admin.enableTable(writeTableName);
1488 }
1489
1490 ClusterStatus status =
1491 admin.getClusterStatus();
1492 int numberOfServers = status.getServersSize();
1493 if (status.getServers().contains(status.getMaster())) {
1494 numberOfServers -= 1;
1495 }
1496
1497 List<HRegionLocation> locations;
1498 RegionLocator locator = connection.getRegionLocator(writeTableName);
1499 try {
1500 locations = locator.getAllRegionLocations();
1501 } finally {
1502 locator.close();
1503 }
1504 int numberOfRegions = locations.size();
1505 if (numberOfRegions < numberOfServers * regionsLowerLimit
1506 || numberOfRegions > numberOfServers * regionsUpperLimit) {
1507 admin.disableTable(writeTableName);
1508 admin.deleteTable(writeTableName);
1509 createWriteTable(numberOfServers);
1510 }
1511 HashSet<ServerName> serverSet = new HashSet<ServerName>();
1512 for (HRegionLocation location: locations) {
1513 serverSet.add(location.getServerName());
1514 }
1515 int numberOfCoveredServers = serverSet.size();
1516 if (numberOfCoveredServers < numberOfServers) {
1517 admin.balancer();
1518 }
1519 }
1520
1521 private void createWriteTable(int numberOfServers) throws IOException {
1522 int numberOfRegions = (int)(numberOfServers * regionsLowerLimit);
1523 LOG.info("Number of live regionservers {}, pre-splitting the canary table into {} regions " +
1524 "(current lower limit of regions per server is {} and you can change it with config {}).",
1525 numberOfServers, numberOfRegions, regionsLowerLimit,
1526 HConstants.HBASE_CANARY_WRITE_PERSERVER_REGIONS_LOWERLIMIT_KEY);
1527 HTableDescriptor desc = new HTableDescriptor(writeTableName);
1528 HColumnDescriptor family = new HColumnDescriptor(CANARY_TABLE_FAMILY_NAME);
1529 family.setMaxVersions(1);
1530 family.setTimeToLive(writeDataTTL);
1531
1532 desc.addFamily(family);
1533 byte[][] splits = new RegionSplitter.HexStringSplit().split(numberOfRegions);
1534 admin.createTable(desc, splits);
1535 }
1536 }
1537
1538
1539
1540
1541
1542 private static List<Future<Void>> sniff(final Admin admin, final Sink sink, String tableName,
1543 ExecutorService executor, TaskType taskType, boolean rawScanEnabled, AtomicLong readLatency)
1544 throws Exception {
1545 LOG.debug("Checking table is enabled and getting table descriptor for table {}", tableName);
1546 if (admin.isTableEnabled(TableName.valueOf(tableName))) {
1547 return CanaryTool.sniff(admin, sink, admin.getTableDescriptor(TableName.valueOf(tableName)),
1548 executor, taskType, rawScanEnabled, readLatency);
1549 } else {
1550 LOG.warn("Table {} is not enabled", tableName);
1551 }
1552 return new LinkedList<>();
1553 }
1554
1555
1556
1557
1558 private static List<Future<Void>> sniff(final Admin admin, final Sink sink,
1559 HTableDescriptor tableDesc, ExecutorService executor, TaskType taskType,
1560 boolean rawScanEnabled, AtomicLong rwLatency) throws Exception {
1561 LOG.debug("Reading list of regions for table {}", tableDesc.getTableName());
1562 try (Table table = admin.getConnection().getTable(tableDesc.getTableName())) {
1563 List<RegionTask> tasks = new ArrayList<>();
1564 try (RegionLocator regionLocator =
1565 admin.getConnection().getRegionLocator(tableDesc.getTableName())) {
1566 for (HRegionLocation location: regionLocator.getAllRegionLocations()) {
1567 ServerName rs = location.getServerName();
1568 HRegionInfo region = location.getRegionInfo();
1569 tasks.add(new RegionTask(admin.getConnection(), region, rs, (RegionStdOutSink)sink,
1570 taskType, rawScanEnabled, rwLatency));
1571 Map<String, RegionTaskResult> regionMap = ((RegionStdOutSink) sink).getRegionMap();
1572 regionMap.put(region.getRegionNameAsString(), new RegionTaskResult(region,
1573 region.getTable(), rs));
1574 }
1575 return executor.invokeAll(tasks);
1576 }
1577 } catch (TableNotFoundException e) {
1578 return Collections.EMPTY_LIST;
1579 }
1580 }
1581
1582
1583 private static class ZookeeperMonitor extends Monitor {
1584 private List<String> hosts;
1585 private final String znode;
1586 private final int timeout;
1587
1588 protected ZookeeperMonitor(Connection connection, String[] monitorTargets, boolean useRegExp,
1589 Sink sink, ExecutorService executor, boolean treatFailureAsError, long allowedFailures) {
1590 super(connection, monitorTargets, useRegExp,
1591 sink, executor, treatFailureAsError, allowedFailures);
1592 Configuration configuration = connection.getConfiguration();
1593 znode =
1594 configuration.get(ZOOKEEPER_ZNODE_PARENT,
1595 DEFAULT_ZOOKEEPER_ZNODE_PARENT);
1596 timeout = configuration
1597 .getInt(HConstants.ZK_SESSION_TIMEOUT, HConstants.DEFAULT_ZK_SESSION_TIMEOUT);
1598 ConnectStringParser parser =
1599 new ConnectStringParser(ZKConfig.getZKQuorumServersString(configuration));
1600 hosts = Lists.newArrayList();
1601 for (InetSocketAddress server : parser.getServerAddresses()) {
1602 hosts.add(server.toString());
1603 }
1604 if (allowedFailures > (hosts.size() - 1) / 2) {
1605 LOG.warn("Confirm allowable number of failed ZooKeeper nodes, as quorum will " +
1606 "already be lost. Setting of {} failures is unexpected for {} ensemble size.",
1607 allowedFailures, hosts.size());
1608 }
1609 }
1610
1611 @Override public void run() {
1612 List<ZookeeperTask> tasks = Lists.newArrayList();
1613 ZookeeperStdOutSink zkSink = null;
1614 try {
1615 zkSink = this.getSink();
1616 } catch (RuntimeException e) {
1617 LOG.error("Run ZooKeeperMonitor failed!", e);
1618 this.errorCode = ERROR_EXIT_CODE;
1619 }
1620 this.initialized = true;
1621 for (final String host : hosts) {
1622 tasks.add(new ZookeeperTask(connection, host, znode, timeout, zkSink));
1623 }
1624 try {
1625 for (Future<Void> future : this.executor.invokeAll(tasks)) {
1626 try {
1627 future.get();
1628 } catch (ExecutionException e) {
1629 LOG.error("Sniff zookeeper failed!", e);
1630 this.errorCode = ERROR_EXIT_CODE;
1631 }
1632 }
1633 } catch (InterruptedException e) {
1634 this.errorCode = ERROR_EXIT_CODE;
1635 Thread.currentThread().interrupt();
1636 LOG.error("Sniff zookeeper interrupted!", e);
1637 }
1638 this.done = true;
1639 }
1640
1641 private ZookeeperStdOutSink getSink() {
1642 if (!(sink instanceof ZookeeperStdOutSink)) {
1643 throw new RuntimeException("Can only write to zookeeper sink");
1644 }
1645 return ((ZookeeperStdOutSink) sink);
1646 }
1647 }
1648
1649
1650
1651
1652
1653 private static class RegionServerMonitor extends Monitor {
1654 private boolean allRegions;
1655
1656 public RegionServerMonitor(Connection connection, String[] monitorTargets, boolean useRegExp,
1657 Sink sink, ExecutorService executor, boolean allRegions,
1658 boolean treatFailureAsError, long allowedFailures) {
1659 super(connection, monitorTargets, useRegExp, sink, executor, treatFailureAsError,
1660 allowedFailures);
1661 this.allRegions = allRegions;
1662 }
1663
1664 private RegionServerStdOutSink getSink() {
1665 if (!(sink instanceof RegionServerStdOutSink)) {
1666 throw new RuntimeException("Can only write to regionserver sink");
1667 }
1668 return ((RegionServerStdOutSink) sink);
1669 }
1670
1671 @Override
1672 public void run() {
1673 if (this.initAdmin() && this.checkNoTableNames()) {
1674 RegionServerStdOutSink regionServerSink = null;
1675 try {
1676 regionServerSink = this.getSink();
1677 } catch (RuntimeException e) {
1678 LOG.error("Run RegionServerMonitor failed!", e);
1679 this.errorCode = ERROR_EXIT_CODE;
1680 }
1681 Map<String, List<HRegionInfo>> rsAndRMap = this.filterRegionServerByName();
1682 this.initialized = true;
1683 this.monitorRegionServers(rsAndRMap, regionServerSink);
1684 }
1685 this.done = true;
1686 }
1687
1688 private boolean checkNoTableNames() {
1689 List<String> foundTableNames = new ArrayList<>();
1690 TableName[] tableNames = null;
1691 LOG.debug("Reading list of tables");
1692 try {
1693 tableNames = this.admin.listTableNames();
1694 } catch (IOException e) {
1695 LOG.error("Get listTableNames failed", e);
1696 this.errorCode = INIT_ERROR_EXIT_CODE;
1697 return false;
1698 }
1699
1700 if (this.targets == null || this.targets.length == 0) return true;
1701
1702 for (String target : this.targets) {
1703 for (TableName tableName : tableNames) {
1704 if (target.equals(tableName.getNameAsString())) {
1705 foundTableNames.add(target);
1706 }
1707 }
1708 }
1709
1710 if (foundTableNames.size() > 0) {
1711 System.err.println("Cannot pass a tablename when using the -regionserver " +
1712 "option, tablenames:" + foundTableNames.toString());
1713 this.errorCode = USAGE_EXIT_CODE;
1714 }
1715 return foundTableNames.isEmpty();
1716 }
1717
1718 private void monitorRegionServers(Map<String, List<HRegionInfo>> rsAndRMap, RegionServerStdOutSink regionServerSink) {
1719 List<RegionServerTask> tasks = new ArrayList<>();
1720 Map<String, AtomicLong> successMap = new HashMap<>();
1721 Random rand = new Random();
1722 for (Map.Entry<String, List<HRegionInfo>> entry : rsAndRMap.entrySet()) {
1723 String serverName = entry.getKey();
1724 AtomicLong successes = new AtomicLong(0);
1725 successMap.put(serverName, successes);
1726 if (entry.getValue().isEmpty()) {
1727 LOG.error("Regionserver not serving any regions - {}", serverName);
1728 } else if (this.allRegions) {
1729 for (HRegionInfo region : entry.getValue()) {
1730 tasks.add(new RegionServerTask(this.connection,
1731 serverName,
1732 region,
1733 regionServerSink,
1734 successes));
1735 }
1736 } else {
1737
1738 HRegionInfo region = entry.getValue().get(rand.nextInt(entry.getValue().size()));
1739 tasks.add(new RegionServerTask(this.connection,
1740 serverName,
1741 region,
1742 regionServerSink,
1743 successes));
1744 }
1745 }
1746 try {
1747 for (Future<Void> future : this.executor.invokeAll(tasks)) {
1748 try {
1749 future.get();
1750 } catch (ExecutionException e) {
1751 LOG.error("Sniff regionserver failed!", e);
1752 this.errorCode = ERROR_EXIT_CODE;
1753 }
1754 }
1755 if (this.allRegions) {
1756 for (Map.Entry<String, List<HRegionInfo>> entry : rsAndRMap.entrySet()) {
1757 String serverName = entry.getKey();
1758 LOG.info("Successfully read {} regions out of {} on regionserver {}",
1759 successMap.get(serverName), entry.getValue().size(), serverName);
1760 }
1761 }
1762 } catch (InterruptedException e) {
1763 this.errorCode = ERROR_EXIT_CODE;
1764 LOG.error("Sniff regionserver interrupted!", e);
1765 }
1766 }
1767
1768 private Map<String, List<HRegionInfo>> filterRegionServerByName() {
1769 Map<String, List<HRegionInfo>> regionServerAndRegionsMap = this.getAllRegionServerByName();
1770 regionServerAndRegionsMap = this.doFilterRegionServerByName(regionServerAndRegionsMap);
1771 return regionServerAndRegionsMap;
1772 }
1773
1774 private Map<String, List<HRegionInfo>> getAllRegionServerByName() {
1775 Map<String, List<HRegionInfo>> rsAndRMap = new HashMap<>();
1776 try {
1777 LOG.debug("Reading list of tables and locations");
1778 HTableDescriptor[] tableDescs = this.admin.listTables();
1779 List<HRegionInfo> regions = null;
1780 for (HTableDescriptor tableDesc: tableDescs) {
1781 try (RegionLocator regionLocator =
1782 this.admin.getConnection().getRegionLocator(tableDesc.getTableName())) {
1783 for (HRegionLocation location : regionLocator.getAllRegionLocations()) {
1784 ServerName rs = location.getServerName();
1785 String rsName = rs.getHostname();
1786 HRegionInfo r = location.getRegionInfo();
1787 if (rsAndRMap.containsKey(rsName)) {
1788 regions = rsAndRMap.get(rsName);
1789 } else {
1790 regions = new ArrayList<>();
1791 rsAndRMap.put(rsName, regions);
1792 }
1793 regions.add(r);
1794 }
1795 }
1796 }
1797
1798
1799 for (ServerName rs: this.admin.getClusterStatus()
1800 .getServers()) {
1801 String rsName = rs.getHostname();
1802 if (!rsAndRMap.containsKey(rsName)) {
1803 rsAndRMap.put(rsName, Collections.<HRegionInfo> emptyList());
1804 }
1805 }
1806 } catch (IOException e) {
1807 LOG.error("Get HTables info failed", e);
1808 this.errorCode = INIT_ERROR_EXIT_CODE;
1809 }
1810 return rsAndRMap;
1811 }
1812
1813 private Map<String, List<HRegionInfo>> doFilterRegionServerByName(
1814 Map<String, List<HRegionInfo>> fullRsAndRMap) {
1815
1816 Map<String, List<HRegionInfo>> filteredRsAndRMap = null;
1817
1818 if (this.targets != null && this.targets.length > 0) {
1819 filteredRsAndRMap = new HashMap<>();
1820 Pattern pattern = null;
1821 Matcher matcher = null;
1822 boolean regExpFound = false;
1823 for (String rsName : this.targets) {
1824 if (this.useRegExp) {
1825 regExpFound = false;
1826 pattern = Pattern.compile(rsName);
1827 for (Map.Entry<String, List<HRegionInfo>> entry : fullRsAndRMap.entrySet()) {
1828 matcher = pattern.matcher(entry.getKey());
1829 if (matcher.matches()) {
1830 filteredRsAndRMap.put(entry.getKey(), entry.getValue());
1831 regExpFound = true;
1832 }
1833 }
1834 if (!regExpFound) {
1835 LOG.info("No RegionServerInfo found, regionServerPattern {}", rsName);
1836 }
1837 } else {
1838 if (fullRsAndRMap.containsKey(rsName)) {
1839 filteredRsAndRMap.put(rsName, fullRsAndRMap.get(rsName));
1840 } else {
1841 LOG.info("No RegionServerInfo found, regionServerName {}", rsName);
1842 }
1843 }
1844 }
1845 } else {
1846 filteredRsAndRMap = fullRsAndRMap;
1847 }
1848 return filteredRsAndRMap;
1849 }
1850 }
1851
1852 public static void main(String[] args) throws Exception {
1853 final Configuration conf = HBaseConfiguration.create();
1854
1855 int numThreads = conf.getInt("hbase.canary.threads.num", MAX_THREADS_NUM);
1856 LOG.info("Execution thread count={}", numThreads);
1857
1858 int exitCode;
1859 ExecutorService executor = new ScheduledThreadPoolExecutor(numThreads);
1860 try {
1861 exitCode = ToolRunner.run(conf, new CanaryTool(executor), args);
1862 } finally {
1863 executor.shutdown();
1864 }
1865 System.exit(exitCode);
1866 }
1867 }