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 java.io.Closeable;
23 import java.io.IOException;
24 import java.util.ArrayList;
25 import java.util.Arrays;
26 import java.util.HashMap;
27 import java.util.List;
28 import java.util.Map;
29 import java.util.Set;
30 import java.util.TreeSet;
31 import java.util.regex.Matcher;
32 import java.util.regex.Pattern;
33
34 import org.apache.commons.lang.time.StopWatch;
35 import org.apache.commons.logging.Log;
36 import org.apache.commons.logging.LogFactory;
37 import org.apache.hadoop.conf.Configuration;
38 import org.apache.hadoop.hbase.AuthUtil;
39 import org.apache.hadoop.hbase.ChoreService;
40 import org.apache.hadoop.hbase.DoNotRetryIOException;
41 import org.apache.hadoop.hbase.HBaseConfiguration;
42 import org.apache.hadoop.hbase.HColumnDescriptor;
43 import org.apache.hadoop.hbase.HRegionInfo;
44 import org.apache.hadoop.hbase.HRegionLocation;
45 import org.apache.hadoop.hbase.HTableDescriptor;
46 import org.apache.hadoop.hbase.ScheduledChore;
47 import org.apache.hadoop.hbase.ServerName;
48 import org.apache.hadoop.hbase.TableName;
49 import org.apache.hadoop.hbase.TableNotEnabledException;
50 import org.apache.hadoop.hbase.TableNotFoundException;
51 import org.apache.hadoop.hbase.client.Admin;
52 import org.apache.hadoop.hbase.client.Connection;
53 import org.apache.hadoop.hbase.client.ConnectionFactory;
54 import org.apache.hadoop.hbase.client.Get;
55 import org.apache.hadoop.hbase.client.RegionLocator;
56 import org.apache.hadoop.hbase.client.ResultScanner;
57 import org.apache.hadoop.hbase.client.Scan;
58 import org.apache.hadoop.hbase.client.Table;
59 import org.apache.hadoop.util.Tool;
60 import org.apache.hadoop.util.ToolRunner;
61
62
63
64
65
66
67
68
69
70
71
72
73 public final class Canary implements Tool {
74
75 public interface Sink {
76 public void publishReadFailure(HRegionInfo region, Exception e);
77 public void publishReadFailure(HRegionInfo region, HColumnDescriptor column, Exception e);
78 public void publishReadTiming(HRegionInfo region, HColumnDescriptor column, long msTime);
79 }
80
81
82 public interface ExtendedSink extends Sink {
83 public void publishReadFailure(String table, String server);
84 public void publishReadTiming(String table, String server, long msTime);
85 }
86
87
88
89 public static class StdOutSink implements Sink {
90 @Override
91 public void publishReadFailure(HRegionInfo region, Exception e) {
92 LOG.error(String.format("read from region %s failed", region.getRegionNameAsString()), e);
93 }
94
95 @Override
96 public void publishReadFailure(HRegionInfo region, HColumnDescriptor column, Exception e) {
97 LOG.error(String.format("read from region %s column family %s failed",
98 region.getRegionNameAsString(), column.getNameAsString()), e);
99 }
100
101 @Override
102 public void publishReadTiming(HRegionInfo region, HColumnDescriptor column, long msTime) {
103 LOG.info(String.format("read from region %s column family %s in %dms",
104 region.getRegionNameAsString(), column.getNameAsString(), msTime));
105 }
106 }
107
108 public static class RegionServerStdOutSink extends StdOutSink implements ExtendedSink {
109
110 @Override
111 public void publishReadFailure(String table, String server) {
112 LOG.error(String.format("Read from table:%s on region server:%s", table, server));
113 }
114
115 @Override
116 public void publishReadTiming(String table, String server, long msTime) {
117 LOG.info(String.format("Read from table:%s on region server:%s in %dms",
118 table, server, msTime));
119 }
120 }
121
122 private static final int USAGE_EXIT_CODE = 1;
123 private static final int INIT_ERROR_EXIT_CODE = 2;
124 private static final int TIMEOUT_ERROR_EXIT_CODE = 3;
125 private static final int ERROR_EXIT_CODE = 4;
126
127 private static final long DEFAULT_INTERVAL = 6000;
128
129 private static final long DEFAULT_TIMEOUT = 600000;
130
131 private static final Log LOG = LogFactory.getLog(Canary.class);
132
133 private Configuration conf = null;
134 private long interval = 0;
135 private Sink sink = null;
136
137 private boolean useRegExp;
138 private long timeout = DEFAULT_TIMEOUT;
139 private boolean failOnError = true;
140 private boolean regionServerMode = false;
141
142 public Canary() {
143 this(new RegionServerStdOutSink());
144 }
145
146 public Canary(Sink sink) {
147 this.sink = sink;
148 }
149
150 @Override
151 public Configuration getConf() {
152 return conf;
153 }
154
155 @Override
156 public void setConf(Configuration conf) {
157 this.conf = conf;
158 }
159
160 @Override
161 public int run(String[] args) throws Exception {
162 int index = -1;
163 ChoreService choreService = null;
164
165
166 for (int i = 0; i < args.length; i++) {
167 String cmd = args[i];
168
169 if (cmd.startsWith("-")) {
170 if (index >= 0) {
171
172 System.err.println("Invalid command line options");
173 printUsageAndExit();
174 }
175
176 if (cmd.equals("-help")) {
177
178 printUsageAndExit();
179 } else if (cmd.equals("-daemon") && interval == 0) {
180
181 interval = DEFAULT_INTERVAL;
182 } else if (cmd.equals("-interval")) {
183
184 i++;
185
186 if (i == args.length) {
187 System.err.println("-interval needs a numeric value argument.");
188 printUsageAndExit();
189 }
190
191 try {
192 interval = Long.parseLong(args[i]) * 1000;
193 } catch (NumberFormatException e) {
194 System.err.println("-interval needs a numeric value argument.");
195 printUsageAndExit();
196 }
197 } else if(cmd.equals("-regionserver")) {
198 this.regionServerMode = true;
199 } else if (cmd.equals("-e")) {
200 this.useRegExp = true;
201 } else if (cmd.equals("-t")) {
202 i++;
203
204 if (i == args.length) {
205 System.err.println("-t needs a numeric value argument.");
206 printUsageAndExit();
207 }
208
209 try {
210 this.timeout = Long.parseLong(args[i]);
211 } catch (NumberFormatException e) {
212 System.err.println("-t needs a numeric value argument.");
213 printUsageAndExit();
214 }
215
216 } else if (cmd.equals("-f")) {
217 i++;
218
219 if (i == args.length) {
220 System.err
221 .println("-f needs a boolean value argument (true|false).");
222 printUsageAndExit();
223 }
224
225 this.failOnError = Boolean.parseBoolean(args[i]);
226 } else {
227
228 System.err.println(cmd + " options is invalid.");
229 printUsageAndExit();
230 }
231 } else if (index < 0) {
232
233 index = i;
234 }
235 }
236
237
238
239
240 final ScheduledChore authChore = AuthUtil.getAuthChore(conf);
241 if (authChore != null) {
242 choreService = new ChoreService("CANARY_TOOL");
243 choreService.scheduleChore(authChore);
244 }
245
246
247 Monitor monitor = null;
248 Thread monitorThread = null;
249 long startTime = 0;
250 long currentTimeLength = 0;
251
252
253
254 try (Connection connection = ConnectionFactory.createConnection(this.conf)) {
255 do {
256
257 try {
258 monitor = this.newMonitor(connection, index, args);
259 monitorThread = new Thread(monitor);
260 startTime = System.currentTimeMillis();
261 monitorThread.start();
262 while (!monitor.isDone()) {
263
264 Thread.sleep(1000);
265
266 if (this.failOnError && monitor.hasError()) {
267 monitorThread.interrupt();
268 if (monitor.initialized) {
269 System.exit(monitor.errorCode);
270 } else {
271 System.exit(INIT_ERROR_EXIT_CODE);
272 }
273 }
274 currentTimeLength = System.currentTimeMillis() - startTime;
275 if (currentTimeLength > this.timeout) {
276 LOG.error("The monitor is running too long (" + currentTimeLength
277 + ") after timeout limit:" + this.timeout
278 + " will be killed itself !!");
279 if (monitor.initialized) {
280 System.exit(TIMEOUT_ERROR_EXIT_CODE);
281 } else {
282 System.exit(INIT_ERROR_EXIT_CODE);
283 }
284 break;
285 }
286 }
287
288 if (this.failOnError && monitor.hasError()) {
289 monitorThread.interrupt();
290 System.exit(monitor.errorCode);
291 }
292 } finally {
293 if (monitor != null) monitor.close();
294 }
295
296 Thread.sleep(interval);
297 } while (interval > 0);
298 }
299
300 if (choreService != null) {
301 choreService.shutdown();
302 }
303 return(monitor.errorCode);
304 }
305
306 private void printUsageAndExit() {
307 System.err.printf(
308 "Usage: bin/hbase %s [opts] [table1 [table2]...] | [regionserver1 [regionserver2]..]%n",
309 getClass().getName());
310 System.err.println(" where [opts] are:");
311 System.err.println(" -help Show this help and exit.");
312 System.err.println(" -regionserver replace the table argument to regionserver,");
313 System.err.println(" which means to enable regionserver mode");
314 System.err.println(" -daemon Continuous check at defined intervals.");
315 System.err.println(" -interval <N> Interval between checks (sec)");
316 System.err.println(" -e Use region/regionserver as regular expression");
317 System.err.println(" which means the region/regionserver is regular expression pattern");
318 System.err.println(" -f <B> stop whole program if first error occurs," +
319 " default is true");
320 System.err.println(" -t <N> timeout for a check, default is 600000 (milisecs)");
321 System.exit(USAGE_EXIT_CODE);
322 }
323
324
325
326
327
328
329
330
331 public Monitor newMonitor(final Connection connection, int index, String[] args) {
332 Monitor monitor = null;
333 String[] monitorTargets = null;
334
335 if(index >= 0) {
336 int length = args.length - index;
337 monitorTargets = new String[length];
338 System.arraycopy(args, index, monitorTargets, 0, length);
339 }
340
341 if(this.regionServerMode) {
342 monitor = new RegionServerMonitor(
343 connection,
344 monitorTargets,
345 this.useRegExp,
346 (ExtendedSink)this.sink);
347 } else {
348 monitor = new RegionMonitor(connection, monitorTargets, this.useRegExp, this.sink);
349 }
350 return monitor;
351 }
352
353
354 public static abstract class Monitor implements Runnable, Closeable {
355
356 protected Connection connection;
357 protected Admin admin;
358 protected String[] targets;
359 protected boolean useRegExp;
360 protected boolean initialized = false;
361
362 protected boolean done = false;
363 protected int errorCode = 0;
364 protected Sink sink;
365
366 public boolean isDone() {
367 return done;
368 }
369
370 public boolean hasError() {
371 return errorCode != 0;
372 }
373
374 @Override
375 public void close() throws IOException {
376 if (this.admin != null) this.admin.close();
377 }
378
379 protected Monitor(Connection connection, String[] monitorTargets,
380 boolean useRegExp, Sink sink) {
381 if (null == connection) throw new IllegalArgumentException("connection shall not be null");
382
383 this.connection = connection;
384 this.targets = monitorTargets;
385 this.useRegExp = useRegExp;
386 this.sink = sink;
387 }
388
389 public abstract void run();
390
391 protected boolean initAdmin() {
392 if (null == this.admin) {
393 try {
394 this.admin = this.connection.getAdmin();
395 } catch (Exception e) {
396 LOG.error("Initial HBaseAdmin failed...", e);
397 this.errorCode = INIT_ERROR_EXIT_CODE;
398 }
399 } else if (admin.isAborted()) {
400 LOG.error("HBaseAdmin aborted");
401 this.errorCode = INIT_ERROR_EXIT_CODE;
402 }
403 return !this.hasError();
404 }
405 }
406
407
408 private static class RegionMonitor extends Monitor {
409
410 public RegionMonitor(Connection connection, String[] monitorTargets,
411 boolean useRegExp, Sink sink) {
412 super(connection, monitorTargets, useRegExp, sink);
413 }
414
415 @Override
416 public void run() {
417 if(this.initAdmin()) {
418 try {
419 if (this.targets != null && this.targets.length > 0) {
420 String[] tables = generateMonitorTables(this.targets);
421 this.initialized = true;
422 for (String table : tables) {
423 Canary.sniff(admin, sink, table);
424 }
425 } else {
426 sniff();
427 }
428 } catch (Exception e) {
429 LOG.error("Run regionMonitor failed", e);
430 this.errorCode = ERROR_EXIT_CODE;
431 }
432 }
433 this.done = true;
434 }
435
436 private String[] generateMonitorTables(String[] monitorTargets) throws IOException {
437 String[] returnTables = null;
438
439 if(this.useRegExp) {
440 Pattern pattern = null;
441 HTableDescriptor[] tds = null;
442 Set<String> tmpTables = new TreeSet<String>();
443 try {
444 for (String monitorTarget : monitorTargets) {
445 pattern = Pattern.compile(monitorTarget);
446 tds = this.admin.listTables(pattern);
447 if (tds != null) {
448 for (HTableDescriptor td : tds) {
449 tmpTables.add(td.getNameAsString());
450 }
451 }
452 }
453 } catch(IOException e) {
454 LOG.error("Communicate with admin failed", e);
455 throw e;
456 }
457
458 if(tmpTables.size() > 0) {
459 returnTables = tmpTables.toArray(new String[tmpTables.size()]);
460 } else {
461 String msg = "No HTable found, tablePattern:"
462 + Arrays.toString(monitorTargets);
463 LOG.error(msg);
464 this.errorCode = INIT_ERROR_EXIT_CODE;
465 throw new TableNotFoundException(msg);
466 }
467 } else {
468 returnTables = monitorTargets;
469 }
470
471 return returnTables;
472 }
473
474
475
476
477 private void sniff() throws Exception {
478 for (HTableDescriptor table : admin.listTables()) {
479 Canary.sniff(admin, sink, table);
480 }
481 }
482
483 }
484
485
486
487
488
489 public static void sniff(final Admin admin, TableName tableName) throws Exception {
490 sniff(admin, new StdOutSink(), tableName.getNameAsString());
491 }
492
493
494
495
496
497 private static void sniff(final Admin admin, final Sink sink, String tableName)
498 throws Exception {
499 if (admin.isTableAvailable(TableName.valueOf(tableName))) {
500 sniff(admin, sink, admin.getTableDescriptor(TableName.valueOf(tableName)));
501 } else {
502 LOG.warn(String.format("Table %s is not available", tableName));
503 }
504 }
505
506
507
508
509 private static void sniff(final Admin admin, final Sink sink, HTableDescriptor tableDesc)
510 throws Exception {
511 Table table = null;
512
513 try {
514 table = admin.getConnection().getTable(tableDesc.getTableName());
515 } catch (TableNotFoundException e) {
516 return;
517 }
518
519 try {
520 for (HRegionInfo region : admin.getTableRegions(tableDesc.getTableName())) {
521 try {
522 sniffRegion(admin, sink, region, table);
523 } catch (Exception e) {
524 sink.publishReadFailure(region, e);
525 LOG.debug("sniffRegion failed", e);
526 }
527 }
528 } finally {
529 table.close();
530 }
531 }
532
533
534
535
536
537 private static void sniffRegion(
538 final Admin admin,
539 final Sink sink,
540 HRegionInfo region,
541 Table table) throws Exception {
542 HTableDescriptor tableDesc = table.getTableDescriptor();
543 byte[] startKey = null;
544 Get get = null;
545 Scan scan = null;
546 ResultScanner rs = null;
547 StopWatch stopWatch = new StopWatch();
548 for (HColumnDescriptor column : tableDesc.getColumnFamilies()) {
549 stopWatch.reset();
550 startKey = region.getStartKey();
551
552 if (startKey.length > 0) {
553 get = new Get(startKey);
554 get.addFamily(column.getName());
555 } else {
556 scan = new Scan();
557 scan.setCaching(1);
558 scan.addFamily(column.getName());
559 scan.setMaxResultSize(1L);
560 }
561
562 try {
563 if (startKey.length > 0) {
564 stopWatch.start();
565 table.get(get);
566 stopWatch.stop();
567 sink.publishReadTiming(region, column, stopWatch.getTime());
568 } else {
569 stopWatch.start();
570 rs = table.getScanner(scan);
571 stopWatch.stop();
572 sink.publishReadTiming(region, column, stopWatch.getTime());
573 }
574 } catch (Exception e) {
575 sink.publishReadFailure(region, column, e);
576 } finally {
577 if (rs != null) {
578 rs.close();
579 }
580 scan = null;
581 get = null;
582 startKey = null;
583 }
584 }
585 }
586
587 private static class RegionServerMonitor extends Monitor {
588
589 public RegionServerMonitor(Connection connection, String[] monitorTargets,
590 boolean useRegExp, ExtendedSink sink) {
591 super(connection, monitorTargets, useRegExp, sink);
592 }
593
594 private ExtendedSink getSink() {
595 return (ExtendedSink) this.sink;
596 }
597
598 @Override
599 public void run() {
600 if (this.initAdmin() && this.checkNoTableNames()) {
601 Map<String, List<HRegionInfo>> rsAndRMap = this.filterRegionServerByName();
602 this.initialized = true;
603 this.monitorRegionServers(rsAndRMap);
604 }
605 this.done = true;
606 }
607
608 private boolean checkNoTableNames() {
609 List<String> foundTableNames = new ArrayList<String>();
610 TableName[] tableNames = null;
611
612 try {
613 tableNames = this.admin.listTableNames();
614 } catch (IOException e) {
615 LOG.error("Get listTableNames failed", e);
616 this.errorCode = INIT_ERROR_EXIT_CODE;
617 return false;
618 }
619
620 if (this.targets == null || this.targets.length == 0) return true;
621
622 for (String target : this.targets) {
623 for (TableName tableName : tableNames) {
624 if (target.equals(tableName.getNameAsString())) {
625 foundTableNames.add(target);
626 }
627 }
628 }
629
630 if (foundTableNames.size() > 0) {
631 System.err.println("Cannot pass a tablename when using the -regionserver " +
632 "option, tablenames:" + foundTableNames.toString());
633 this.errorCode = USAGE_EXIT_CODE;
634 }
635 return foundTableNames.size() == 0;
636 }
637
638 private void monitorRegionServers(Map<String, List<HRegionInfo>> rsAndRMap) {
639 String serverName = null;
640 TableName tableName = null;
641 HRegionInfo region = null;
642 Table table = null;
643 Get get = null;
644 byte[] startKey = null;
645 Scan scan = null;
646 StopWatch stopWatch = new StopWatch();
647
648 for (Map.Entry<String, List<HRegionInfo>> entry : rsAndRMap.entrySet()) {
649 stopWatch.reset();
650 serverName = entry.getKey();
651
652 region = entry.getValue().get(0);
653 try {
654 tableName = region.getTable();
655 table = admin.getConnection().getTable(tableName);
656 startKey = region.getStartKey();
657
658 if(startKey.length > 0) {
659 get = new Get(startKey);
660 stopWatch.start();
661 table.get(get);
662 stopWatch.stop();
663 } else {
664 scan = new Scan();
665 scan.setCaching(1);
666 scan.setMaxResultSize(1L);
667 stopWatch.start();
668 ResultScanner s = table.getScanner(scan);
669 s.close();
670 stopWatch.stop();
671 }
672 this.getSink().publishReadTiming(tableName.getNameAsString(),
673 serverName, stopWatch.getTime());
674 } catch (TableNotFoundException tnfe) {
675
676 } catch (TableNotEnabledException tnee) {
677
678 LOG.debug("The targeted table was disabled. Assuming success.");
679 } catch (DoNotRetryIOException dnrioe) {
680 this.getSink().publishReadFailure(tableName.getNameAsString(), serverName);
681 LOG.error(dnrioe);
682 } catch (IOException e) {
683 this.getSink().publishReadFailure(tableName.getNameAsString(), serverName);
684 LOG.error(e);
685 this.errorCode = ERROR_EXIT_CODE;
686 } finally {
687 if (table != null) {
688 try {
689 table.close();
690 } catch (IOException e) {
691 }
692 }
693 scan = null;
694 get = null;
695 startKey = null;
696 }
697 }
698 }
699
700 private Map<String, List<HRegionInfo>> filterRegionServerByName() {
701 Map<String, List<HRegionInfo>> regionServerAndRegionsMap = this.getAllRegionServerByName();
702 regionServerAndRegionsMap = this.doFilterRegionServerByName(regionServerAndRegionsMap);
703 return regionServerAndRegionsMap;
704 }
705
706 private Map<String, List<HRegionInfo>> getAllRegionServerByName() {
707 Map<String, List<HRegionInfo>> rsAndRMap = new HashMap<String, List<HRegionInfo>>();
708 Table table = null;
709 RegionLocator regionLocator = null;
710 try {
711 HTableDescriptor[] tableDescs = this.admin.listTables();
712 List<HRegionInfo> regions = null;
713 for (HTableDescriptor tableDesc : tableDescs) {
714 table = this.admin.getConnection().getTable(tableDesc.getTableName());
715 regionLocator = this.admin.getConnection().getRegionLocator(tableDesc.getTableName());
716
717 for (HRegionLocation location: regionLocator.getAllRegionLocations()) {
718 ServerName rs = location.getServerName();
719 String rsName = rs.getHostname();
720 HRegionInfo r = location.getRegionInfo();
721
722 if (rsAndRMap.containsKey(rsName)) {
723 regions = rsAndRMap.get(rsName);
724 } else {
725 regions = new ArrayList<HRegionInfo>();
726 rsAndRMap.put(rsName, regions);
727 }
728 regions.add(r);
729 }
730 table.close();
731 }
732
733 } catch (IOException e) {
734 String msg = "Get HTables info failed";
735 LOG.error(msg, e);
736 this.errorCode = INIT_ERROR_EXIT_CODE;
737 } finally {
738 if (table != null) {
739 try {
740 table.close();
741 } catch (IOException e) {
742 LOG.warn("Close table failed", e);
743 }
744 }
745 }
746
747 return rsAndRMap;
748 }
749
750 private Map<String, List<HRegionInfo>> doFilterRegionServerByName(
751 Map<String, List<HRegionInfo>> fullRsAndRMap) {
752
753 Map<String, List<HRegionInfo>> filteredRsAndRMap = null;
754
755 if (this.targets != null && this.targets.length > 0) {
756 filteredRsAndRMap = new HashMap<String, List<HRegionInfo>>();
757 Pattern pattern = null;
758 Matcher matcher = null;
759 boolean regExpFound = false;
760 for (String rsName : this.targets) {
761 if (this.useRegExp) {
762 regExpFound = false;
763 pattern = Pattern.compile(rsName);
764 for (Map.Entry<String,List<HRegionInfo>> entry : fullRsAndRMap.entrySet()) {
765 matcher = pattern.matcher(entry.getKey());
766 if (matcher.matches()) {
767 filteredRsAndRMap.put(entry.getKey(), entry.getValue());
768 regExpFound = true;
769 }
770 }
771 if (!regExpFound) {
772 LOG.info("No RegionServerInfo found, regionServerPattern:" + rsName);
773 }
774 } else {
775 if (fullRsAndRMap.containsKey(rsName)) {
776 filteredRsAndRMap.put(rsName, fullRsAndRMap.get(rsName));
777 } else {
778 LOG.info("No RegionServerInfo found, regionServerName:" + rsName);
779 }
780 }
781 }
782 } else {
783 filteredRsAndRMap = fullRsAndRMap;
784 }
785 return filteredRsAndRMap;
786 }
787 }
788
789 public static void main(String[] args) throws Exception {
790 final Configuration conf = HBaseConfiguration.create();
791 int exitCode = ToolRunner.run(conf, new Canary(), args);
792 System.exit(exitCode);
793 }
794 }