/
CanaryTool.java
2012 lines (1825 loc) · 74.6 KB
/
CanaryTool.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hbase.tool;
import static org.apache.hadoop.hbase.HConstants.DEFAULT_ZOOKEEPER_ZNODE_PARENT;
import static org.apache.hadoop.hbase.HConstants.ZOOKEEPER_ZNODE_PARENT;
import static org.apache.hadoop.hbase.util.Addressing.inetSocketAddress2String;
import java.io.Closeable;
import java.io.IOException;
import java.net.BindException;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.LongAdder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang3.time.StopWatch;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.AuthUtil;
import org.apache.hadoop.hbase.ChoreService;
import org.apache.hadoop.hbase.ClusterMetrics;
import org.apache.hadoop.hbase.ClusterMetrics.Option;
import org.apache.hadoop.hbase.DoNotRetryIOException;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HBaseInterfaceAudience;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.HRegionLocation;
import org.apache.hadoop.hbase.MetaTableAccessor;
import org.apache.hadoop.hbase.NamespaceDescriptor;
import org.apache.hadoop.hbase.ScheduledChore;
import org.apache.hadoop.hbase.ServerName;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.TableNotEnabledException;
import org.apache.hadoop.hbase.TableNotFoundException;
import org.apache.hadoop.hbase.client.Admin;
import org.apache.hadoop.hbase.client.ColumnFamilyDescriptor;
import org.apache.hadoop.hbase.client.ColumnFamilyDescriptorBuilder;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.RegionInfo;
import org.apache.hadoop.hbase.client.RegionLocator;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.client.Table;
import org.apache.hadoop.hbase.client.TableDescriptor;
import org.apache.hadoop.hbase.client.TableDescriptorBuilder;
import org.apache.hadoop.hbase.filter.FirstKeyOnlyFilter;
import org.apache.hadoop.hbase.http.InfoServer;
import org.apache.hadoop.hbase.tool.CanaryTool.RegionTask.TaskType;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
import org.apache.hadoop.hbase.util.Pair;
import org.apache.hadoop.hbase.util.ReflectionUtils;
import org.apache.hadoop.hbase.util.RegionSplitter;
import org.apache.hadoop.hbase.zookeeper.EmptyWatcher;
import org.apache.hadoop.hbase.zookeeper.ZKConfig;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import org.apache.yetus.audience.InterfaceAudience;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.client.ConnectStringParser;
import org.apache.zookeeper.data.Stat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.hbase.thirdparty.com.google.common.collect.Lists;
/**
* HBase Canary Tool for "canary monitoring" of a running HBase cluster. There are three modes:
* <ol>
* <li>region mode (Default): For each region, try to get one row per column family outputting
* information on failure (ERROR) or else the latency.</li>
* <li>regionserver mode: For each regionserver try to get one row from one table selected randomly
* outputting information on failure (ERROR) or else the latency.</li>
* <li>zookeeper mode: for each zookeeper instance, selects a znode outputting information on
* failure (ERROR) or else the latency.</li>
* </ol>
*/
@InterfaceAudience.LimitedPrivate(HBaseInterfaceAudience.TOOLS)
public class CanaryTool implements Tool, Canary {
public static final String HBASE_CANARY_INFO_PORT = "hbase.canary.info.port";
public static final String HBASE_CANARY_INFO_BINDADDRESS = "hbase.canary.info.bindAddress";
private void putUpWebUI() throws IOException {
int port = conf.getInt(HBASE_CANARY_INFO_PORT, -1);
// -1 is for disabling info server
if (port < 0) {
return;
}
if (zookeeperMode) {
LOG.info("WebUI is not supported in Zookeeper mode");
} else if (regionServerMode) {
LOG.info("WebUI is not supported in RegionServer mode");
} else {
String addr = conf.get(HBASE_CANARY_INFO_BINDADDRESS, "0.0.0.0");
try {
InfoServer infoServer = new InfoServer("canary", addr, port, false, conf);
infoServer.addUnprivilegedServlet("canary", "/canary-status", CanaryStatusServlet.class);
infoServer.setAttribute("sink", getSink(conf, RegionStdOutSink.class));
infoServer.start();
LOG.info("Bind Canary http info server to {}:{} ", addr, port);
} catch (BindException e) {
LOG.warn("Failed binding Canary http info server to {}:{}", addr, port, e);
}
}
}
@Override
public int checkRegions(String[] targets) throws Exception {
String configuredReadTableTimeoutsStr = conf.get(HBASE_CANARY_REGION_READ_TABLE_TIMEOUT);
try {
LOG.info("Canary tool is running in Region mode");
if (configuredReadTableTimeoutsStr != null) {
populateReadTableTimeoutsMap(configuredReadTableTimeoutsStr);
}
} catch (IllegalArgumentException e) {
LOG.error("Constructing read table timeouts map failed ", e);
return USAGE_EXIT_CODE;
}
return runMonitor(targets);
}
@Override
public int checkRegionServers(String[] targets) throws Exception {
regionServerMode = true;
LOG.info("Canary tool is running in RegionServer mode");
return runMonitor(targets);
}
@Override
public int checkZooKeeper() throws Exception {
zookeeperMode = true;
LOG.info("Canary tool is running in ZooKeeper mode");
return runMonitor(null);
}
/**
* Sink interface used by the canary to output information
*/
public interface Sink {
long getReadFailureCount();
long incReadFailureCount();
Map<String, String> getReadFailures();
void updateReadFailures(String regionName, String serverName);
long getWriteFailureCount();
long incWriteFailureCount();
Map<String, String> getWriteFailures();
void updateWriteFailures(String regionName, String serverName);
long getReadSuccessCount();
long incReadSuccessCount();
long getWriteSuccessCount();
long incWriteSuccessCount();
}
/**
* Simple implementation of canary sink that allows plotting to a file or standard output.
*/
public static class StdOutSink implements Sink {
private AtomicLong readFailureCount = new AtomicLong(0), writeFailureCount = new AtomicLong(0),
readSuccessCount = new AtomicLong(0), writeSuccessCount = new AtomicLong(0);
private Map<String, String> readFailures = new ConcurrentHashMap<>();
private Map<String, String> writeFailures = new ConcurrentHashMap<>();
@Override
public long getReadFailureCount() {
return readFailureCount.get();
}
@Override
public long incReadFailureCount() {
return readFailureCount.incrementAndGet();
}
@Override
public Map<String, String> getReadFailures() {
return readFailures;
}
@Override
public void updateReadFailures(String regionName, String serverName) {
readFailures.put(regionName, serverName);
}
@Override
public long getWriteFailureCount() {
return writeFailureCount.get();
}
@Override
public long incWriteFailureCount() {
return writeFailureCount.incrementAndGet();
}
@Override
public Map<String, String> getWriteFailures() {
return writeFailures;
}
@Override
public void updateWriteFailures(String regionName, String serverName) {
writeFailures.put(regionName, serverName);
}
@Override
public long getReadSuccessCount() {
return readSuccessCount.get();
}
@Override
public long incReadSuccessCount() {
return readSuccessCount.incrementAndGet();
}
@Override
public long getWriteSuccessCount() {
return writeSuccessCount.get();
}
@Override
public long incWriteSuccessCount() {
return writeSuccessCount.incrementAndGet();
}
}
/**
* By RegionServer, for 'regionserver' mode.
*/
public static class RegionServerStdOutSink extends StdOutSink {
public void publishReadFailure(String table, String server) {
incReadFailureCount();
LOG.error("Read from {} on {}", table, server);
}
public void publishReadTiming(String table, String server, long msTime) {
LOG.info("Read from {} on {} in {}ms", table, server, msTime);
}
}
/**
* Output for 'zookeeper' mode.
*/
public static class ZookeeperStdOutSink extends StdOutSink {
public void publishReadFailure(String znode, String server) {
incReadFailureCount();
LOG.error("Read from {} on {}", znode, server);
}
public void publishReadTiming(String znode, String server, long msTime) {
LOG.info("Read from {} on {} in {}ms", znode, server, msTime);
}
}
/**
* By Region, for 'region' mode.
*/
public static class RegionStdOutSink extends StdOutSink {
private Map<String, LongAdder> perTableReadLatency = new HashMap<>();
private LongAdder writeLatency = new LongAdder();
private final ConcurrentMap<String, List<RegionTaskResult>> regionMap =
new ConcurrentHashMap<>();
private ConcurrentMap<ServerName, LongAdder> perServerFailuresCount = new ConcurrentHashMap<>();
private ConcurrentMap<String, LongAdder> perTableFailuresCount = new ConcurrentHashMap<>();
public ConcurrentMap<ServerName, LongAdder> getPerServerFailuresCount() {
return perServerFailuresCount;
}
public ConcurrentMap<String, LongAdder> getPerTableFailuresCount() {
return perTableFailuresCount;
}
public void resetFailuresCountDetails() {
perServerFailuresCount.clear();
perTableFailuresCount.clear();
}
private void incFailuresCountDetails(ServerName serverName, RegionInfo region) {
if (serverName != null) {
perServerFailuresCount.compute(serverName, (server, count) -> {
if (count == null) {
count = new LongAdder();
}
count.increment();
return count;
});
}
perTableFailuresCount.compute(region.getTable().getNameAsString(), (tableName, count) -> {
if (count == null) {
count = new LongAdder();
}
count.increment();
return count;
});
}
public void publishReadFailure(ServerName serverName, RegionInfo region, Exception e) {
LOG.error("Read from {} on serverName={} failed", region.getRegionNameAsString(), serverName,
e);
incReadFailureCount();
incFailuresCountDetails(serverName, region);
}
public void publishReadFailure(ServerName serverName, RegionInfo region,
ColumnFamilyDescriptor column, Exception e) {
LOG.error("Read from {} on serverName={}, columnFamily={} failed",
region.getRegionNameAsString(), serverName, column.getNameAsString(), e);
incReadFailureCount();
incFailuresCountDetails(serverName, region);
}
public void publishReadTiming(ServerName serverName, RegionInfo region,
ColumnFamilyDescriptor column, long msTime) {
RegionTaskResult rtr = new RegionTaskResult(region, region.getTable(), serverName, column);
rtr.setReadSuccess();
rtr.setReadLatency(msTime);
List<RegionTaskResult> rtrs = regionMap.get(region.getRegionNameAsString());
rtrs.add(rtr);
// Note that read success count will be equal to total column family read successes.
incReadSuccessCount();
LOG.info("Read from {} on {} {} in {}ms", region.getRegionNameAsString(), serverName,
column.getNameAsString(), msTime);
}
public void publishWriteFailure(ServerName serverName, RegionInfo region, Exception e) {
LOG.error("Write to {} on {} failed", region.getRegionNameAsString(), serverName, e);
incWriteFailureCount();
incFailuresCountDetails(serverName, region);
}
public void publishWriteFailure(ServerName serverName, RegionInfo region,
ColumnFamilyDescriptor column, Exception e) {
LOG.error("Write to {} on {} {} failed", region.getRegionNameAsString(), serverName,
column.getNameAsString(), e);
incWriteFailureCount();
incFailuresCountDetails(serverName, region);
}
public void publishWriteTiming(ServerName serverName, RegionInfo region,
ColumnFamilyDescriptor column, long msTime) {
RegionTaskResult rtr = new RegionTaskResult(region, region.getTable(), serverName, column);
rtr.setWriteSuccess();
rtr.setWriteLatency(msTime);
List<RegionTaskResult> rtrs = regionMap.get(region.getRegionNameAsString());
rtrs.add(rtr);
// Note that write success count will be equal to total column family write successes.
incWriteSuccessCount();
LOG.info("Write to {} on {} {} in {}ms", region.getRegionNameAsString(), serverName,
column.getNameAsString(), msTime);
}
public Map<String, LongAdder> getReadLatencyMap() {
return this.perTableReadLatency;
}
public LongAdder initializeAndGetReadLatencyForTable(String tableName) {
LongAdder initLatency = new LongAdder();
this.perTableReadLatency.put(tableName, initLatency);
return initLatency;
}
public void initializeWriteLatency() {
this.writeLatency.reset();
}
public LongAdder getWriteLatency() {
return this.writeLatency;
}
public ConcurrentMap<String, List<RegionTaskResult>> getRegionMap() {
return this.regionMap;
}
public int getTotalExpectedRegions() {
return this.regionMap.size();
}
}
/**
* Run a single zookeeper Task and then exit.
*/
static class ZookeeperTask implements Callable<Void> {
private final Connection connection;
private final String host;
private String znode;
private final int timeout;
private ZookeeperStdOutSink sink;
public ZookeeperTask(Connection connection, String host, String znode, int timeout,
ZookeeperStdOutSink sink) {
this.connection = connection;
this.host = host;
this.znode = znode;
this.timeout = timeout;
this.sink = sink;
}
@Override
public Void call() throws Exception {
ZooKeeper zooKeeper = null;
try {
zooKeeper = new ZooKeeper(host, timeout, EmptyWatcher.instance);
Stat exists = zooKeeper.exists(znode, false);
StopWatch stopwatch = new StopWatch();
stopwatch.start();
zooKeeper.getData(znode, false, exists);
stopwatch.stop();
sink.publishReadTiming(znode, host, stopwatch.getTime());
} catch (KeeperException | InterruptedException e) {
sink.publishReadFailure(znode, host);
} finally {
if (zooKeeper != null) {
zooKeeper.close();
}
}
return null;
}
}
/**
* Run a single Region Task and then exit. For each column family of the Region, get one row and
* output latency or failure.
*/
static class RegionTask implements Callable<Void> {
public enum TaskType {
READ,
WRITE
}
private Connection connection;
private RegionInfo region;
private RegionStdOutSink sink;
private TaskType taskType;
private boolean rawScanEnabled;
private ServerName serverName;
private LongAdder readWriteLatency;
private boolean readAllCF;
RegionTask(Connection connection, RegionInfo region, ServerName serverName,
RegionStdOutSink sink, TaskType taskType, boolean rawScanEnabled, LongAdder rwLatency,
boolean readAllCF) {
this.connection = connection;
this.region = region;
this.serverName = serverName;
this.sink = sink;
this.taskType = taskType;
this.rawScanEnabled = rawScanEnabled;
this.readWriteLatency = rwLatency;
this.readAllCF = readAllCF;
}
@Override
public Void call() {
switch (taskType) {
case READ:
return read();
case WRITE:
return write();
default:
return read();
}
}
private Void readColumnFamily(Table table, ColumnFamilyDescriptor column) {
byte[] startKey = null;
Scan scan = null;
ResultScanner rs = null;
StopWatch stopWatch = new StopWatch();
startKey = region.getStartKey();
// Can't do a get on empty start row so do a Scan of first element if any instead.
if (startKey.length > 0) {
Get get = new Get(startKey);
get.setCacheBlocks(false);
get.setFilter(new FirstKeyOnlyFilter());
get.addFamily(column.getName());
// Converting get object to scan to enable RAW SCAN.
// This will work for all the regions of the HBase tables except first region of the table.
scan = new Scan(get);
scan.setRaw(rawScanEnabled);
} else {
scan = new Scan();
// In case of first region of the HBase Table, we do not have start-key for the region.
// For Region Canary, we only need to scan a single row/cell in the region to make sure that
// region is accessible.
//
// When HBase table has more than 1 empty regions at start of the row-key space, Canary will
// create multiple scan object to find first available row in the table by scanning all the
// regions in sequence until it can find first available row.
//
// This could result in multiple millions of scans based on the size of table and number of
// empty regions in sequence. In test environment, A table with no data and 1100 empty
// regions, Single canary run was creating close to half million to 1 million scans to
// successfully do canary run for the table.
//
// Since First region of the table doesn't have any start key, We should set End Key as
// stop row and set inclusive=false to limit scan to single region only.
//
// TODO : In future, we can streamline Canary behaviour for all the regions by doing scan
// with startRow inclusive and stopRow exclusive instead of different behaviour for First
// Region of the table and rest of the region of the table. This way implementation is
// simplified. As of now this change has been kept minimal to avoid any unnecessary
// perf impact.
scan.withStopRow(region.getEndKey(), false);
LOG.debug("rawScan {} for {}", rawScanEnabled, region.getTable());
scan.setRaw(rawScanEnabled);
scan.setCaching(1);
scan.setCacheBlocks(false);
scan.setFilter(new FirstKeyOnlyFilter());
scan.addFamily(column.getName());
scan.setMaxResultSize(1L);
scan.setOneRowLimit();
}
LOG.debug("Reading from {} {} {} {}", region.getTable(), region.getRegionNameAsString(),
column.getNameAsString(), Bytes.toStringBinary(startKey));
try {
stopWatch.start();
rs = table.getScanner(scan);
rs.next();
stopWatch.stop();
this.readWriteLatency.add(stopWatch.getTime());
sink.publishReadTiming(serverName, region, column, stopWatch.getTime());
} catch (Exception e) {
sink.publishReadFailure(serverName, region, column, e);
sink.updateReadFailures(region.getRegionNameAsString(),
serverName == null ? "NULL" : serverName.getHostname());
} finally {
if (rs != null) {
rs.close();
}
}
return null;
}
private ColumnFamilyDescriptor randomPickOneColumnFamily(ColumnFamilyDescriptor[] cfs) {
int size = cfs.length;
return cfs[ThreadLocalRandom.current().nextInt(size)];
}
public Void read() {
Table table = null;
TableDescriptor tableDesc = null;
try {
LOG.debug("Reading table descriptor for table {}", region.getTable());
table = connection.getTable(region.getTable());
tableDesc = table.getDescriptor();
} catch (IOException e) {
LOG.debug("sniffRegion {} of {} failed", region.getEncodedName(), e);
sink.publishReadFailure(serverName, region, e);
if (table != null) {
try {
table.close();
} catch (IOException ioe) {
LOG.error("Close table failed", e);
}
}
return null;
}
if (readAllCF) {
for (ColumnFamilyDescriptor column : tableDesc.getColumnFamilies()) {
readColumnFamily(table, column);
}
} else {
readColumnFamily(table, randomPickOneColumnFamily(tableDesc.getColumnFamilies()));
}
try {
table.close();
} catch (IOException e) {
LOG.error("Close table failed", e);
}
return null;
}
/**
* Check writes for the canary table
*/
private Void write() {
Table table = null;
TableDescriptor tableDesc = null;
try {
table = connection.getTable(region.getTable());
tableDesc = table.getDescriptor();
byte[] rowToCheck = region.getStartKey();
if (rowToCheck.length == 0) {
rowToCheck = new byte[] { 0x0 };
}
int writeValueSize =
connection.getConfiguration().getInt(HConstants.HBASE_CANARY_WRITE_VALUE_SIZE_KEY, 10);
for (ColumnFamilyDescriptor column : tableDesc.getColumnFamilies()) {
Put put = new Put(rowToCheck);
byte[] value = new byte[writeValueSize];
Bytes.random(value);
put.addColumn(column.getName(), HConstants.EMPTY_BYTE_ARRAY, value);
LOG.debug("Writing to {} {} {} {}", tableDesc.getTableName(),
region.getRegionNameAsString(), column.getNameAsString(),
Bytes.toStringBinary(rowToCheck));
try {
long startTime = EnvironmentEdgeManager.currentTime();
table.put(put);
long time = EnvironmentEdgeManager.currentTime() - startTime;
this.readWriteLatency.add(time);
sink.publishWriteTiming(serverName, region, column, time);
} catch (Exception e) {
sink.publishWriteFailure(serverName, region, column, e);
}
}
table.close();
} catch (IOException e) {
sink.publishWriteFailure(serverName, region, e);
sink.updateWriteFailures(region.getRegionNameAsString(), serverName.getHostname());
}
return null;
}
}
/**
* Run a single RegionServer Task and then exit. Get one row from a region on the regionserver and
* output latency or the failure.
*/
static class RegionServerTask implements Callable<Void> {
private Connection connection;
private String serverName;
private RegionInfo region;
private RegionServerStdOutSink sink;
private Boolean rawScanEnabled;
private AtomicLong successes;
RegionServerTask(Connection connection, String serverName, RegionInfo region,
RegionServerStdOutSink sink, Boolean rawScanEnabled, AtomicLong successes) {
this.connection = connection;
this.serverName = serverName;
this.region = region;
this.sink = sink;
this.rawScanEnabled = rawScanEnabled;
this.successes = successes;
}
@Override
public Void call() {
TableName tableName = null;
Table table = null;
Get get = null;
byte[] startKey = null;
Scan scan = null;
StopWatch stopWatch = new StopWatch();
// monitor one region on every region server
stopWatch.reset();
try {
tableName = region.getTable();
table = connection.getTable(tableName);
startKey = region.getStartKey();
// Can't do a get on empty start row so do a Scan of first element if any instead.
LOG.debug("Reading from {} {} {} {}", serverName, region.getTable(),
region.getRegionNameAsString(), Bytes.toStringBinary(startKey));
if (startKey.length > 0) {
get = new Get(startKey);
get.setCacheBlocks(false);
get.setFilter(new FirstKeyOnlyFilter());
// Converting get object to scan to enable RAW SCAN.
// This will work for all the regions of the HBase tables except first region.
scan = new Scan(get);
} else {
scan = new Scan();
// In case of first region of the HBase Table, we do not have start-key for the region.
// For Region Canary, we only need scan a single row/cell in the region to make sure that
// region is accessible.
//
// When HBase table has more than 1 empty regions at start of the row-key space, Canary
// will create multiple scan object to find first available row in the table by scanning
// all the regions in sequence until it can find first available row.
//
// Since First region of the table doesn't have any start key, We should set End Key as
// stop row and set inclusive=false to limit scan to first region only.
scan.withStopRow(region.getEndKey(), false);
scan.setCacheBlocks(false);
scan.setFilter(new FirstKeyOnlyFilter());
scan.setCaching(1);
scan.setMaxResultSize(1L);
scan.setOneRowLimit();
}
scan.setRaw(rawScanEnabled);
stopWatch.start();
ResultScanner s = table.getScanner(scan);
s.next();
s.close();
stopWatch.stop();
successes.incrementAndGet();
sink.publishReadTiming(tableName.getNameAsString(), serverName, stopWatch.getTime());
} catch (TableNotFoundException tnfe) {
LOG.error("Table may be deleted", tnfe);
// This is ignored because it doesn't imply that the regionserver is dead
} catch (TableNotEnabledException tnee) {
// This is considered a success since we got a response.
successes.incrementAndGet();
LOG.debug("The targeted table was disabled. Assuming success.");
} catch (DoNotRetryIOException dnrioe) {
sink.publishReadFailure(tableName.getNameAsString(), serverName);
LOG.error(dnrioe.toString(), dnrioe);
} catch (IOException e) {
sink.publishReadFailure(tableName.getNameAsString(), serverName);
LOG.error(e.toString(), e);
} finally {
if (table != null) {
try {
table.close();
} catch (IOException e) {/* DO NOTHING */
LOG.error("Close table failed", e);
}
}
scan = null;
get = null;
startKey = null;
}
return null;
}
}
private static final int USAGE_EXIT_CODE = 1;
private static final int INIT_ERROR_EXIT_CODE = 2;
private static final int TIMEOUT_ERROR_EXIT_CODE = 3;
private static final int ERROR_EXIT_CODE = 4;
private static final int FAILURE_EXIT_CODE = 5;
private static final long DEFAULT_INTERVAL = 60000;
private static final long DEFAULT_TIMEOUT = 600000; // 10 mins
private static final int MAX_THREADS_NUM = 16; // #threads to contact regions
private static final Logger LOG = LoggerFactory.getLogger(Canary.class);
public static final TableName DEFAULT_WRITE_TABLE_NAME =
TableName.valueOf(NamespaceDescriptor.SYSTEM_NAMESPACE_NAME_STR, "canary");
private static final String CANARY_TABLE_FAMILY_NAME = "Test";
private Configuration conf = null;
private long interval = 0;
private Sink sink = null;
/**
* True if we are to run in 'regionServer' mode.
*/
private boolean regionServerMode = false;
/**
* True if we are to run in zookeeper 'mode'.
*/
private boolean zookeeperMode = false;
/**
* This is a Map of table to timeout. The timeout is for reading all regions in the table; i.e. we
* aggregate time to fetch each region and it needs to be less than this value else we log an
* ERROR.
*/
private HashMap<String, Long> configuredReadTableTimeouts = new HashMap<>();
public static final String HBASE_CANARY_REGIONSERVER_ALL_REGIONS =
"hbase.canary.regionserver_all_regions";
public static final String HBASE_CANARY_REGION_WRITE_SNIFFING =
"hbase.canary.region.write.sniffing";
public static final String HBASE_CANARY_REGION_WRITE_TABLE_TIMEOUT =
"hbase.canary.region.write.table.timeout";
public static final String HBASE_CANARY_REGION_WRITE_TABLE_NAME =
"hbase.canary.region.write.table.name";
public static final String HBASE_CANARY_REGION_READ_TABLE_TIMEOUT =
"hbase.canary.region.read.table.timeout";
public static final String HBASE_CANARY_ZOOKEEPER_PERMITTED_FAILURES =
"hbase.canary.zookeeper.permitted.failures";
public static final String HBASE_CANARY_USE_REGEX = "hbase.canary.use.regex";
public static final String HBASE_CANARY_TIMEOUT = "hbase.canary.timeout";
public static final String HBASE_CANARY_FAIL_ON_ERROR = "hbase.canary.fail.on.error";
private ExecutorService executor; // threads to retrieve data from regionservers
public CanaryTool() {
this(new ScheduledThreadPoolExecutor(1));
}
public CanaryTool(ExecutorService executor) {
this(executor, null);
}
@InterfaceAudience.Private
CanaryTool(ExecutorService executor, Sink sink) {
this.executor = executor;
this.sink = sink;
}
CanaryTool(Configuration conf, ExecutorService executor) {
this(conf, executor, null);
}
CanaryTool(Configuration conf, ExecutorService executor, Sink sink) {
this(executor, sink);
setConf(conf);
}
@Override
public Configuration getConf() {
return conf;
}
@Override
public void setConf(Configuration conf) {
if (conf == null) {
conf = HBaseConfiguration.create();
}
this.conf = conf;
}
private int parseArgs(String[] args) {
int index = -1;
long permittedFailures = 0;
boolean regionServerAllRegions = false, writeSniffing = false;
String readTableTimeoutsStr = null;
// Process command line args
for (int i = 0; i < args.length; i++) {
String cmd = args[i];
if (cmd.startsWith("-")) {
if (index >= 0) {
// command line args must be in the form: [opts] [table 1 [table 2 ...]]
System.err.println("Invalid command line options");
printUsageAndExit();
}
if (cmd.equals("-help") || cmd.equals("-h")) {
// user asked for help, print the help and quit.
printUsageAndExit();
} else if (cmd.equals("-daemon") && interval == 0) {
// user asked for daemon mode, set a default interval between checks
interval = DEFAULT_INTERVAL;
} else if (cmd.equals("-interval")) {
// user has specified an interval for canary breaths (-interval N)
i++;
if (i == args.length) {
System.err.println("-interval takes a numeric seconds value argument.");
printUsageAndExit();
}
try {
interval = Long.parseLong(args[i]) * 1000;
} catch (NumberFormatException e) {
System.err.println("-interval needs a numeric value argument.");
printUsageAndExit();
}
} else if (cmd.equals("-zookeeper")) {
this.zookeeperMode = true;
} else if (cmd.equals("-regionserver")) {
this.regionServerMode = true;
} else if (cmd.equals("-allRegions")) {
conf.setBoolean(HBASE_CANARY_REGIONSERVER_ALL_REGIONS, true);
regionServerAllRegions = true;
} else if (cmd.equals("-writeSniffing")) {
writeSniffing = true;
conf.setBoolean(HBASE_CANARY_REGION_WRITE_SNIFFING, true);
} else if (cmd.equals("-treatFailureAsError") || cmd.equals("-failureAsError")) {
conf.setBoolean(HBASE_CANARY_FAIL_ON_ERROR, true);
} else if (cmd.equals("-e")) {
conf.setBoolean(HBASE_CANARY_USE_REGEX, true);
} else if (cmd.equals("-t")) {
i++;
if (i == args.length) {
System.err.println("-t takes a numeric milliseconds value argument.");
printUsageAndExit();
}
long timeout = 0;
try {
timeout = Long.parseLong(args[i]);
} catch (NumberFormatException e) {
System.err.println("-t takes a numeric milliseconds value argument.");
printUsageAndExit();
}
conf.setLong(HBASE_CANARY_TIMEOUT, timeout);
} else if (cmd.equals("-writeTableTimeout")) {
i++;
if (i == args.length) {
System.err.println("-writeTableTimeout takes a numeric milliseconds value argument.");
printUsageAndExit();
}
long configuredWriteTableTimeout = 0;
try {
configuredWriteTableTimeout = Long.parseLong(args[i]);
} catch (NumberFormatException e) {
System.err.println("-writeTableTimeout takes a numeric milliseconds value argument.");
printUsageAndExit();
}
conf.setLong(HBASE_CANARY_REGION_WRITE_TABLE_TIMEOUT, configuredWriteTableTimeout);
} else if (cmd.equals("-writeTable")) {
i++;
if (i == args.length) {
System.err.println("-writeTable takes a string tablename value argument.");
printUsageAndExit();
}
conf.set(HBASE_CANARY_REGION_WRITE_TABLE_NAME, args[i]);
} else if (cmd.equals("-f")) {
i++;
if (i == args.length) {
System.err.println("-f needs a boolean value argument (true|false).");
printUsageAndExit();
}
conf.setBoolean(HBASE_CANARY_FAIL_ON_ERROR, Boolean.parseBoolean(args[i]));
} else if (cmd.equals("-readTableTimeouts")) {
i++;
if (i == args.length) {
System.err.println("-readTableTimeouts needs a comma-separated list of read "
+ "millisecond timeouts per table (without spaces).");
printUsageAndExit();
}
readTableTimeoutsStr = args[i];
conf.set(HBASE_CANARY_REGION_READ_TABLE_TIMEOUT, readTableTimeoutsStr);
} else if (cmd.equals("-permittedZookeeperFailures")) {
i++;
if (i == args.length) {
System.err.println("-permittedZookeeperFailures needs a numeric value argument.");
printUsageAndExit();
}
try {
permittedFailures = Long.parseLong(args[i]);
} catch (NumberFormatException e) {
System.err.println("-permittedZookeeperFailures needs a numeric value argument.");
printUsageAndExit();
}
conf.setLong(HBASE_CANARY_ZOOKEEPER_PERMITTED_FAILURES, permittedFailures);
} else {
// no options match
System.err.println(cmd + " options is invalid.");
printUsageAndExit();
}
} else if (index < 0) {
// keep track of first table name specified by the user
index = i;
}
}
if (regionServerAllRegions && !this.regionServerMode) {
System.err.println("-allRegions can only be specified in regionserver mode.");
printUsageAndExit();
}
if (this.zookeeperMode) {
if (this.regionServerMode || regionServerAllRegions || writeSniffing) {
System.err.println("-zookeeper is exclusive and cannot be combined with " + "other modes.");
printUsageAndExit();
}
}
if (permittedFailures != 0 && !this.zookeeperMode) {