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