1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.hadoop.hbase.zookeeper;
20
21 import java.io.BufferedReader;
22 import java.io.IOException;
23 import java.io.InputStreamReader;
24 import java.io.PrintWriter;
25 import java.net.InetSocketAddress;
26 import java.net.Socket;
27 import java.util.ArrayList;
28 import java.util.Arrays;
29 import java.util.Deque;
30 import java.util.HashMap;
31 import java.util.LinkedList;
32 import java.util.List;
33 import java.util.Map;
34
35 import javax.security.auth.login.AppConfigurationEntry;
36 import javax.security.auth.login.AppConfigurationEntry.LoginModuleControlFlag;
37
38 import org.apache.commons.lang.StringUtils;
39 import org.apache.commons.logging.Log;
40 import org.apache.commons.logging.LogFactory;
41 import org.apache.hadoop.conf.Configuration;
42 import org.apache.hadoop.hbase.HBaseConfiguration;
43 import org.apache.hadoop.hbase.HConstants;
44 import org.apache.hadoop.hbase.ServerName;
45 import org.apache.hadoop.hbase.classification.InterfaceAudience;
46 import org.apache.hadoop.hbase.exceptions.DeserializationException;
47 import org.apache.hadoop.hbase.protobuf.ProtobufUtil;
48 import org.apache.hadoop.hbase.protobuf.generated.ClusterStatusProtos;
49 import org.apache.hadoop.hbase.protobuf.generated.ClusterStatusProtos.RegionStoreSequenceIds;
50 import org.apache.hadoop.hbase.protobuf.generated.ZooKeeperProtos;
51 import org.apache.hadoop.hbase.util.ByteStringer;
52 import org.apache.hadoop.hbase.util.Bytes;
53 import org.apache.hadoop.hbase.util.Threads;
54 import org.apache.hadoop.hbase.zookeeper.ZKUtil.ZKUtilOp.CreateAndFailSilent;
55 import org.apache.hadoop.hbase.zookeeper.ZKUtil.ZKUtilOp.DeleteNodeFailSilent;
56 import org.apache.hadoop.hbase.zookeeper.ZKUtil.ZKUtilOp.SetData;
57 import org.apache.hadoop.security.SecurityUtil;
58 import org.apache.hadoop.security.authentication.util.KerberosUtil;
59 import org.apache.zookeeper.AsyncCallback;
60 import org.apache.zookeeper.CreateMode;
61 import org.apache.zookeeper.KeeperException;
62 import org.apache.zookeeper.KeeperException.NoNodeException;
63 import org.apache.zookeeper.Op;
64 import org.apache.zookeeper.Watcher;
65 import org.apache.zookeeper.ZooDefs.Ids;
66 import org.apache.zookeeper.ZooDefs.Perms;
67 import org.apache.zookeeper.ZooKeeper;
68 import org.apache.zookeeper.client.ZooKeeperSaslClient;
69 import org.apache.zookeeper.data.ACL;
70 import org.apache.zookeeper.data.Id;
71 import org.apache.zookeeper.data.Stat;
72 import org.apache.zookeeper.proto.CreateRequest;
73 import org.apache.zookeeper.proto.DeleteRequest;
74 import org.apache.zookeeper.proto.SetDataRequest;
75 import org.apache.zookeeper.server.ZooKeeperSaslServer;
76
77 import com.google.common.annotations.VisibleForTesting;
78 import com.google.protobuf.InvalidProtocolBufferException;
79
80
81
82
83
84
85
86
87
88
89 @InterfaceAudience.Private
90 public class ZKUtil {
91 private static final Log LOG = LogFactory.getLog(ZKUtil.class);
92
93
94 public static final char ZNODE_PATH_SEPARATOR = '/';
95 private static int zkDumpConnectionTimeOut;
96
97
98
99
100
101
102
103 @VisibleForTesting
104 public static class ZKClusterKey {
105 public String quorumString;
106 public int clientPort;
107 public String znodeParent;
108
109 ZKClusterKey(String quorumString, int clientPort, String znodeParent) {
110 this.quorumString = quorumString;
111 this.clientPort = clientPort;
112 this.znodeParent = znodeParent;
113 }
114 }
115
116
117
118
119
120
121
122
123
124
125
126
127 public static RecoverableZooKeeper connect(Configuration conf, Watcher watcher)
128 throws IOException {
129 String ensemble = ZKConfig.getZKQuorumServersString(conf);
130 return connect(conf, ensemble, watcher);
131 }
132
133 public static RecoverableZooKeeper connect(Configuration conf, String ensemble,
134 Watcher watcher)
135 throws IOException {
136 return connect(conf, ensemble, watcher, null);
137 }
138
139 public static RecoverableZooKeeper connect(Configuration conf, String ensemble,
140 Watcher watcher, final String identifier)
141 throws IOException {
142 if(ensemble == null) {
143 throw new IOException("Unable to determine ZooKeeper ensemble");
144 }
145 int timeout = conf.getInt(HConstants.ZK_SESSION_TIMEOUT,
146 HConstants.DEFAULT_ZK_SESSION_TIMEOUT);
147 if (LOG.isTraceEnabled()) {
148 LOG.trace(identifier + " opening connection to ZooKeeper ensemble=" + ensemble);
149 }
150 int retry = conf.getInt("zookeeper.recovery.retry", 3);
151 int retryIntervalMillis =
152 conf.getInt("zookeeper.recovery.retry.intervalmill", 1000);
153 zkDumpConnectionTimeOut = conf.getInt("zookeeper.dump.connection.timeout",
154 1000);
155 return new RecoverableZooKeeper(ensemble, timeout, watcher,
156 retry, retryIntervalMillis, identifier);
157 }
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173 public static void loginServer(Configuration conf, String keytabFileKey,
174 String userNameKey, String hostname) throws IOException {
175 login(conf, keytabFileKey, userNameKey, hostname,
176 ZooKeeperSaslServer.LOGIN_CONTEXT_NAME_KEY,
177 JaasConfiguration.SERVER_KEYTAB_KERBEROS_CONFIG_NAME);
178 }
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194 public static void loginClient(Configuration conf, String keytabFileKey,
195 String userNameKey, String hostname) throws IOException {
196 login(conf, keytabFileKey, userNameKey, hostname,
197 ZooKeeperSaslClient.LOGIN_CONTEXT_NAME_KEY,
198 JaasConfiguration.CLIENT_KEYTAB_KERBEROS_CONFIG_NAME);
199 }
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217 private static void login(Configuration conf, String keytabFileKey,
218 String userNameKey, String hostname,
219 String loginContextProperty, String loginContextName)
220 throws IOException {
221 if (!isSecureZooKeeper(conf))
222 return;
223
224
225
226 if (System.getProperty("java.security.auth.login.config") != null)
227 return;
228
229
230 String keytabFilename = conf.get(keytabFileKey);
231 if (keytabFilename == null) {
232 LOG.warn("no keytab specified for: " + keytabFileKey);
233 return;
234 }
235
236 String principalConfig = conf.get(userNameKey, System.getProperty("user.name"));
237 String principalName = SecurityUtil.getServerPrincipal(principalConfig, hostname);
238
239
240
241
242 JaasConfiguration jaasConf = new JaasConfiguration(loginContextName,
243 principalName, keytabFilename);
244 javax.security.auth.login.Configuration.setConfiguration(jaasConf);
245 System.setProperty(loginContextProperty, loginContextName);
246 }
247
248
249
250
251 private static class JaasConfiguration extends javax.security.auth.login.Configuration {
252 private static final String SERVER_KEYTAB_KERBEROS_CONFIG_NAME =
253 "zookeeper-server-keytab-kerberos";
254 private static final String CLIENT_KEYTAB_KERBEROS_CONFIG_NAME =
255 "zookeeper-client-keytab-kerberos";
256
257 private static final Map<String, String> BASIC_JAAS_OPTIONS =
258 new HashMap<String,String>();
259 static {
260 String jaasEnvVar = System.getenv("HBASE_JAAS_DEBUG");
261 if (jaasEnvVar != null && "true".equalsIgnoreCase(jaasEnvVar)) {
262 BASIC_JAAS_OPTIONS.put("debug", "true");
263 }
264 }
265
266 private static final Map<String,String> KEYTAB_KERBEROS_OPTIONS =
267 new HashMap<String,String>();
268 static {
269 KEYTAB_KERBEROS_OPTIONS.put("doNotPrompt", "true");
270 KEYTAB_KERBEROS_OPTIONS.put("storeKey", "true");
271 KEYTAB_KERBEROS_OPTIONS.put("refreshKrb5Config", "true");
272 KEYTAB_KERBEROS_OPTIONS.putAll(BASIC_JAAS_OPTIONS);
273 }
274
275 private static final AppConfigurationEntry KEYTAB_KERBEROS_LOGIN =
276 new AppConfigurationEntry(KerberosUtil.getKrb5LoginModuleName(),
277 LoginModuleControlFlag.REQUIRED,
278 KEYTAB_KERBEROS_OPTIONS);
279
280 private static final AppConfigurationEntry[] KEYTAB_KERBEROS_CONF =
281 new AppConfigurationEntry[]{KEYTAB_KERBEROS_LOGIN};
282
283 private javax.security.auth.login.Configuration baseConfig;
284 private final String loginContextName;
285 private final boolean useTicketCache;
286 private final String keytabFile;
287 private final String principal;
288
289 public JaasConfiguration(String loginContextName, String principal) {
290 this(loginContextName, principal, null, true);
291 }
292
293 public JaasConfiguration(String loginContextName, String principal, String keytabFile) {
294 this(loginContextName, principal, keytabFile, keytabFile == null || keytabFile.length() == 0);
295 }
296
297 private JaasConfiguration(String loginContextName, String principal,
298 String keytabFile, boolean useTicketCache) {
299 try {
300 this.baseConfig = javax.security.auth.login.Configuration.getConfiguration();
301 } catch (SecurityException e) {
302 this.baseConfig = null;
303 }
304 this.loginContextName = loginContextName;
305 this.useTicketCache = useTicketCache;
306 this.keytabFile = keytabFile;
307 this.principal = principal;
308 LOG.info("JaasConfiguration loginContextName=" + loginContextName +
309 " principal=" + principal + " useTicketCache=" + useTicketCache +
310 " keytabFile=" + keytabFile);
311 }
312
313 @Override
314 public AppConfigurationEntry[] getAppConfigurationEntry(String appName) {
315 if (loginContextName.equals(appName)) {
316 if (!useTicketCache) {
317 KEYTAB_KERBEROS_OPTIONS.put("keyTab", keytabFile);
318 KEYTAB_KERBEROS_OPTIONS.put("useKeyTab", "true");
319 }
320 KEYTAB_KERBEROS_OPTIONS.put("principal", principal);
321 KEYTAB_KERBEROS_OPTIONS.put("useTicketCache", useTicketCache ? "true" : "false");
322 return KEYTAB_KERBEROS_CONF;
323 }
324 if (baseConfig != null) return baseConfig.getAppConfigurationEntry(appName);
325 return(null);
326 }
327 }
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343 public static String joinZNode(String prefix, String suffix) {
344 return prefix + ZNODE_PATH_SEPARATOR + suffix;
345 }
346
347
348
349
350
351
352 public static String getParent(String node) {
353 int idx = node.lastIndexOf(ZNODE_PATH_SEPARATOR);
354 return idx <= 0 ? null : node.substring(0, idx);
355 }
356
357
358
359
360
361
362 public static String getNodeName(String path) {
363 return path.substring(path.lastIndexOf("/")+1);
364 }
365
366
367
368
369
370
371
372 public static String getZooKeeperClusterKey(Configuration conf) {
373 return getZooKeeperClusterKey(conf, null);
374 }
375
376
377
378
379
380
381
382
383 public static String getZooKeeperClusterKey(Configuration conf, String name) {
384 String ensemble = conf.get(HConstants.ZOOKEEPER_QUORUM.replaceAll(
385 "[\\t\\n\\x0B\\f\\r]", ""));
386 StringBuilder builder = new StringBuilder(ensemble);
387 builder.append(":");
388 builder.append(conf.get(HConstants.ZOOKEEPER_CLIENT_PORT));
389 builder.append(":");
390 builder.append(conf.get(HConstants.ZOOKEEPER_ZNODE_PARENT));
391 if (name != null && !name.isEmpty()) {
392 builder.append(",");
393 builder.append(name);
394 }
395 return builder.toString();
396 }
397
398
399
400
401
402
403
404
405 public static void applyClusterKeyToConf(Configuration conf, String key)
406 throws IOException{
407 ZKClusterKey zkClusterKey = transformClusterKey(key);
408 conf.set(HConstants.ZOOKEEPER_QUORUM, zkClusterKey.quorumString);
409 conf.setInt(HConstants.ZOOKEEPER_CLIENT_PORT, zkClusterKey.clientPort);
410 conf.set(HConstants.ZOOKEEPER_ZNODE_PARENT, zkClusterKey.znodeParent);
411 }
412
413
414
415
416
417
418
419
420
421 public static ZKClusterKey transformClusterKey(String key) throws IOException {
422 String[] parts = key.split(":");
423
424 if (parts.length == 3) {
425 return new ZKClusterKey(parts [0], Integer.parseInt(parts [1]), parts [2]);
426 }
427
428 if (parts.length > 3) {
429
430 String zNodeParent = parts [parts.length - 1];
431 String clientPort = parts [parts.length - 2];
432
433
434 int endQuorumIndex = key.length() - zNodeParent.length() - clientPort.length() - 2;
435 String quorumStringInput = key.substring(0, endQuorumIndex);
436 String[] serverHosts = quorumStringInput.split(",");
437
438
439
440
441 if ((parts.length - 2) == (serverHosts.length + 1)) {
442 return new ZKClusterKey(quorumStringInput, Integer.parseInt(clientPort), zNodeParent);
443 }
444
445
446
447 return new ZKClusterKey(
448 ZKConfig.buildQuorumServerString(serverHosts, clientPort),
449 Integer.parseInt(clientPort),
450 zNodeParent);
451 }
452
453 throw new IOException("Cluster key passed " + key + " is invalid, the format should be:" +
454 HConstants.ZOOKEEPER_QUORUM + ":" + HConstants.ZOOKEEPER_CLIENT_PORT + ":"
455 + HConstants.ZOOKEEPER_ZNODE_PARENT);
456 }
457
458
459
460
461
462
463
464 @VisibleForTesting
465 public static String standardizeQuorumServerString(String quorumStringInput, String clientPort) {
466 String[] serverHosts = quorumStringInput.split(",");
467 return ZKConfig.buildQuorumServerString(serverHosts, clientPort);
468 }
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484 public static boolean watchAndCheckExists(ZooKeeperWatcher zkw, String znode)
485 throws KeeperException {
486 try {
487 Stat s = zkw.getRecoverableZooKeeper().exists(znode, zkw);
488 boolean exists = s != null ? true : false;
489 if (exists) {
490 LOG.debug(zkw.prefix("Set watcher on existing znode=" + znode));
491 } else {
492 LOG.debug(zkw.prefix("Set watcher on znode that does not yet exist, " + znode));
493 }
494 return exists;
495 } catch (KeeperException e) {
496 LOG.warn(zkw.prefix("Unable to set watcher on znode " + znode), e);
497 zkw.keeperException(e);
498 return false;
499 } catch (InterruptedException e) {
500 LOG.warn(zkw.prefix("Unable to set watcher on znode " + znode), e);
501 zkw.interruptedException(e);
502 return false;
503 }
504 }
505
506
507
508
509
510
511
512
513
514
515
516 public static boolean setWatchIfNodeExists(ZooKeeperWatcher zkw, String znode)
517 throws KeeperException {
518 try {
519 zkw.getRecoverableZooKeeper().getData(znode, true, null);
520 return true;
521 } catch (NoNodeException e) {
522 return false;
523 } catch (InterruptedException e) {
524 LOG.warn(zkw.prefix("Unable to set watcher on znode " + znode), e);
525 zkw.interruptedException(e);
526 return false;
527 }
528 }
529
530
531
532
533
534
535
536
537
538 public static int checkExists(ZooKeeperWatcher zkw, String znode)
539 throws KeeperException {
540 try {
541 Stat s = zkw.getRecoverableZooKeeper().exists(znode, null);
542 return s != null ? s.getVersion() : -1;
543 } catch (KeeperException e) {
544 LOG.warn(zkw.prefix("Unable to set watcher on znode (" + znode + ")"), e);
545 zkw.keeperException(e);
546 return -1;
547 } catch (InterruptedException e) {
548 LOG.warn(zkw.prefix("Unable to set watcher on znode (" + znode + ")"), e);
549 zkw.interruptedException(e);
550 return -1;
551 }
552 }
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574 public static List<String> listChildrenAndWatchForNewChildren(
575 ZooKeeperWatcher zkw, String znode)
576 throws KeeperException {
577 try {
578 List<String> children = zkw.getRecoverableZooKeeper().getChildren(znode, zkw);
579 return children;
580 } catch(KeeperException.NoNodeException ke) {
581 LOG.debug(zkw.prefix("Unable to list children of znode " + znode + " " +
582 "because node does not exist (not an error)"));
583 return null;
584 } catch (KeeperException e) {
585 LOG.warn(zkw.prefix("Unable to list children of znode " + znode + " "), e);
586 zkw.keeperException(e);
587 return null;
588 } catch (InterruptedException e) {
589 LOG.warn(zkw.prefix("Unable to list children of znode " + znode + " "), e);
590 zkw.interruptedException(e);
591 return null;
592 }
593 }
594
595
596
597
598
599
600
601
602
603
604 public static List<String> listChildrenAndWatchThem(ZooKeeperWatcher zkw,
605 String znode) throws KeeperException {
606 List<String> children = listChildrenAndWatchForNewChildren(zkw, znode);
607 if (children == null) {
608 return null;
609 }
610 for (String child : children) {
611 watchAndCheckExists(zkw, joinZNode(znode, child));
612 }
613 return children;
614 }
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630 public static List<String> listChildrenNoWatch(ZooKeeperWatcher zkw, String znode)
631 throws KeeperException {
632 List<String> children = null;
633 try {
634
635 children = zkw.getRecoverableZooKeeper().getChildren(znode, null);
636 } catch(KeeperException.NoNodeException nne) {
637 return null;
638 } catch(InterruptedException ie) {
639 zkw.interruptedException(ie);
640 }
641 return children;
642 }
643
644
645
646
647
648 @Deprecated
649 public static class NodeAndData {
650 private String node;
651 private byte [] data;
652 public NodeAndData(String node, byte [] data) {
653 this.node = node;
654 this.data = data;
655 }
656 public String getNode() {
657 return node;
658 }
659 public byte [] getData() {
660 return data;
661 }
662 @Override
663 public String toString() {
664 return node;
665 }
666 public boolean isEmpty() {
667 return (data.length == 0);
668 }
669 }
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687 public static boolean nodeHasChildren(ZooKeeperWatcher zkw, String znode)
688 throws KeeperException {
689 try {
690 return !zkw.getRecoverableZooKeeper().getChildren(znode, null).isEmpty();
691 } catch(KeeperException.NoNodeException ke) {
692 LOG.debug(zkw.prefix("Unable to list children of znode " + znode + " " +
693 "because node does not exist (not an error)"));
694 return false;
695 } catch (KeeperException e) {
696 LOG.warn(zkw.prefix("Unable to list children of znode " + znode), e);
697 zkw.keeperException(e);
698 return false;
699 } catch (InterruptedException e) {
700 LOG.warn(zkw.prefix("Unable to list children of znode " + znode), e);
701 zkw.interruptedException(e);
702 return false;
703 }
704 }
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719 public static int getNumberOfChildren(ZooKeeperWatcher zkw, String znode)
720 throws KeeperException {
721 try {
722 Stat stat = zkw.getRecoverableZooKeeper().exists(znode, null);
723 return stat == null ? 0 : stat.getNumChildren();
724 } catch(KeeperException e) {
725 LOG.warn(zkw.prefix("Unable to get children of node " + znode));
726 zkw.keeperException(e);
727 } catch(InterruptedException e) {
728 zkw.interruptedException(e);
729 }
730 return 0;
731 }
732
733
734
735
736
737
738
739
740
741
742 public static byte [] getData(ZooKeeperWatcher zkw, String znode)
743 throws KeeperException, InterruptedException {
744 try {
745 byte [] data = zkw.getRecoverableZooKeeper().getData(znode, null, null);
746 logRetrievedMsg(zkw, znode, data, false);
747 return data;
748 } catch (KeeperException.NoNodeException e) {
749 LOG.debug(zkw.prefix("Unable to get data of znode " + znode + " " +
750 "because node does not exist (not an error)"));
751 return null;
752 } catch (KeeperException e) {
753 LOG.warn(zkw.prefix("Unable to get data of znode " + znode), e);
754 zkw.keeperException(e);
755 return null;
756 }
757 }
758
759
760
761
762
763
764
765
766
767
768
769
770 public static byte [] getDataAndWatch(ZooKeeperWatcher zkw, String znode)
771 throws KeeperException {
772 return getDataInternal(zkw, znode, null, true);
773 }
774
775
776
777
778
779
780
781
782
783
784
785
786
787 public static byte[] getDataAndWatch(ZooKeeperWatcher zkw, String znode,
788 Stat stat) throws KeeperException {
789 return getDataInternal(zkw, znode, stat, true);
790 }
791
792 private static byte[] getDataInternal(ZooKeeperWatcher zkw, String znode, Stat stat,
793 boolean watcherSet)
794 throws KeeperException {
795 try {
796 byte [] data = zkw.getRecoverableZooKeeper().getData(znode, zkw, stat);
797 logRetrievedMsg(zkw, znode, data, watcherSet);
798 return data;
799 } catch (KeeperException.NoNodeException e) {
800
801
802 LOG.trace(zkw.prefix("Unable to get data of znode " + znode + " " +
803 "because node does not exist (not an error)"));
804 return null;
805 } catch (KeeperException e) {
806 LOG.warn(zkw.prefix("Unable to get data of znode " + znode), e);
807 zkw.keeperException(e);
808 return null;
809 } catch (InterruptedException e) {
810 LOG.warn(zkw.prefix("Unable to get data of znode " + znode), e);
811 zkw.interruptedException(e);
812 return null;
813 }
814 }
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831 public static byte [] getDataNoWatch(ZooKeeperWatcher zkw, String znode,
832 Stat stat)
833 throws KeeperException {
834 try {
835 byte [] data = zkw.getRecoverableZooKeeper().getData(znode, null, stat);
836 logRetrievedMsg(zkw, znode, data, false);
837 return data;
838 } catch (KeeperException.NoNodeException e) {
839 LOG.debug(zkw.prefix("Unable to get data of znode " + znode + " " +
840 "because node does not exist (not necessarily an error)"));
841 return null;
842 } catch (KeeperException e) {
843 LOG.warn(zkw.prefix("Unable to get data of znode " + znode), e);
844 zkw.keeperException(e);
845 return null;
846 } catch (InterruptedException e) {
847 LOG.warn(zkw.prefix("Unable to get data of znode " + znode), e);
848 zkw.interruptedException(e);
849 return null;
850 }
851 }
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870 public static List<NodeAndData> getChildDataAndWatchForNewChildren(
871 ZooKeeperWatcher zkw, String baseNode) throws KeeperException {
872 List<String> nodes =
873 ZKUtil.listChildrenAndWatchForNewChildren(zkw, baseNode);
874 if (nodes != null) {
875 List<NodeAndData> newNodes = new ArrayList<NodeAndData>();
876 for (String node : nodes) {
877 String nodePath = ZKUtil.joinZNode(baseNode, node);
878 byte[] data = ZKUtil.getDataAndWatch(zkw, nodePath);
879 newNodes.add(new NodeAndData(nodePath, data));
880 }
881 return newNodes;
882 }
883 return null;
884 }
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902 public static void updateExistingNodeData(ZooKeeperWatcher zkw, String znode,
903 byte [] data, int expectedVersion)
904 throws KeeperException {
905 try {
906 zkw.getRecoverableZooKeeper().setData(znode, data, expectedVersion);
907 } catch(InterruptedException ie) {
908 zkw.interruptedException(ie);
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 public static boolean setData(ZooKeeperWatcher zkw, String znode,
937 byte [] data, int expectedVersion)
938 throws KeeperException, KeeperException.NoNodeException {
939 try {
940 return zkw.getRecoverableZooKeeper().setData(znode, data, expectedVersion) != null;
941 } catch (InterruptedException e) {
942 zkw.interruptedException(e);
943 return false;
944 }
945 }
946
947
948
949
950
951
952
953
954
955
956 public static void createSetData(final ZooKeeperWatcher zkw, final String znode,
957 final byte [] data)
958 throws KeeperException {
959 if (checkExists(zkw, znode) == -1) {
960 ZKUtil.createWithParents(zkw, znode, data);
961 } else {
962 ZKUtil.setData(zkw, znode, data);
963 }
964 }
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982 public static void setData(ZooKeeperWatcher zkw, String znode, byte [] data)
983 throws KeeperException, KeeperException.NoNodeException {
984 setData(zkw, (SetData)ZKUtilOp.setData(znode, data));
985 }
986
987 private static void setData(ZooKeeperWatcher zkw, SetData setData)
988 throws KeeperException, KeeperException.NoNodeException {
989 SetDataRequest sd = (SetDataRequest)toZooKeeperOp(zkw, setData).toRequestRecord();
990 setData(zkw, sd.getPath(), sd.getData(), sd.getVersion());
991 }
992
993
994
995
996
997
998 public static boolean isSecureZooKeeper(Configuration conf) {
999
1000
1001 try {
1002 javax.security.auth.login.Configuration testConfig =
1003 javax.security.auth.login.Configuration.getConfiguration();
1004 if (testConfig.getAppConfigurationEntry("Client") == null
1005 && testConfig.getAppConfigurationEntry(
1006 JaasConfiguration.CLIENT_KEYTAB_KERBEROS_CONFIG_NAME) == null
1007 && testConfig.getAppConfigurationEntry(
1008 JaasConfiguration.SERVER_KEYTAB_KERBEROS_CONFIG_NAME) == null) {
1009 return false;
1010 }
1011 } catch(Exception e) {
1012
1013 return false;
1014 }
1015
1016
1017 return("kerberos".equalsIgnoreCase(conf.get("hbase.security.authentication")));
1018 }
1019
1020 private static ArrayList<ACL> createACL(ZooKeeperWatcher zkw, String node) {
1021 if (!node.startsWith(zkw.baseZNode)) {
1022 return Ids.OPEN_ACL_UNSAFE;
1023 }
1024 if (isSecureZooKeeper(zkw.getConfiguration())) {
1025 String superUser = zkw.getConfiguration().get("hbase.superuser");
1026 ArrayList<ACL> acls = new ArrayList<ACL>();
1027
1028 if (superUser != null) {
1029 acls.add(new ACL(Perms.ALL, new Id("auth", superUser)));
1030 }
1031
1032
1033 if ((node.equals(zkw.baseZNode) == true) ||
1034 (zkw.isAnyMetaReplicaZnode(node)) ||
1035 (node.equals(zkw.getMasterAddressZNode()) == true) ||
1036 (node.equals(zkw.clusterIdZNode) == true) ||
1037 (node.equals(zkw.rsZNode) == true) ||
1038 (node.equals(zkw.backupMasterAddressesZNode) == true) ||
1039 (node.startsWith(zkw.assignmentZNode) == true) ||
1040 (node.startsWith(zkw.tableZNode) == true)) {
1041 acls.addAll(Ids.CREATOR_ALL_ACL);
1042 acls.addAll(Ids.READ_ACL_UNSAFE);
1043 } else {
1044 acls.addAll(Ids.CREATOR_ALL_ACL);
1045 }
1046 return acls;
1047 } else {
1048 return Ids.OPEN_ACL_UNSAFE;
1049 }
1050 }
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074 public static boolean createEphemeralNodeAndWatch(ZooKeeperWatcher zkw,
1075 String znode, byte [] data)
1076 throws KeeperException {
1077 boolean ret = true;
1078 try {
1079 zkw.getRecoverableZooKeeper().create(znode, data, createACL(zkw, znode),
1080 CreateMode.EPHEMERAL);
1081 } catch (KeeperException.NodeExistsException nee) {
1082 ret = false;
1083 } catch (InterruptedException e) {
1084 LOG.info("Interrupted", e);
1085 Thread.currentThread().interrupt();
1086 }
1087 if(!watchAndCheckExists(zkw, znode)) {
1088
1089 return createEphemeralNodeAndWatch(zkw, znode, data);
1090 }
1091 return ret;
1092 }
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114 public static boolean createNodeIfNotExistsAndWatch(
1115 ZooKeeperWatcher zkw, String znode, byte [] data)
1116 throws KeeperException {
1117 boolean ret = true;
1118 try {
1119 zkw.getRecoverableZooKeeper().create(znode, data, createACL(zkw, znode),
1120 CreateMode.PERSISTENT);
1121 } catch (KeeperException.NodeExistsException nee) {
1122 ret = false;
1123 } catch (InterruptedException e) {
1124 zkw.interruptedException(e);
1125 return false;
1126 }
1127 try {
1128 zkw.getRecoverableZooKeeper().exists(znode, zkw);
1129 } catch (InterruptedException e) {
1130 zkw.interruptedException(e);
1131 return false;
1132 }
1133 return ret;
1134 }
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150 public static String createNodeIfNotExistsNoWatch(ZooKeeperWatcher zkw, String znode,
1151 byte[] data, CreateMode createMode) throws KeeperException {
1152
1153 String createdZNode = null;
1154 try {
1155 createdZNode = zkw.getRecoverableZooKeeper().create(znode, data,
1156 createACL(zkw, znode), createMode);
1157 } catch (KeeperException.NodeExistsException nee) {
1158 return znode;
1159 } catch (InterruptedException e) {
1160 zkw.interruptedException(e);
1161 return null;
1162 }
1163 return createdZNode;
1164 }
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182 public static int createAndWatch(ZooKeeperWatcher zkw,
1183 String znode, byte [] data)
1184 throws KeeperException, KeeperException.NodeExistsException {
1185 try {
1186 zkw.getRecoverableZooKeeper().create(znode, data, createACL(zkw, znode),
1187 CreateMode.PERSISTENT);
1188 Stat stat = zkw.getRecoverableZooKeeper().exists(znode, zkw);
1189 if (stat == null){
1190
1191 throw KeeperException.create(KeeperException.Code.SYSTEMERROR,
1192 "ZK.exists returned null (i.e.: znode does not exist) for znode=" + znode);
1193 }
1194 return stat.getVersion();
1195 } catch (InterruptedException e) {
1196 zkw.interruptedException(e);
1197 return -1;
1198 }
1199 }
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216 public static void asyncCreate(ZooKeeperWatcher zkw,
1217 String znode, byte [] data, final AsyncCallback.StringCallback cb,
1218 final Object ctx) {
1219 zkw.getRecoverableZooKeeper().getZooKeeper().create(znode, data,
1220 createACL(zkw, znode), CreateMode.PERSISTENT, cb, ctx);
1221 }
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233 public static void createAndFailSilent(ZooKeeperWatcher zkw,
1234 String znode) throws KeeperException {
1235 createAndFailSilent(zkw, znode, new byte[0]);
1236 }
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249 public static void createAndFailSilent(ZooKeeperWatcher zkw,
1250 String znode, byte[] data)
1251 throws KeeperException {
1252 createAndFailSilent(zkw,
1253 (CreateAndFailSilent)ZKUtilOp.createAndFailSilent(znode, data));
1254 }
1255
1256 private static void createAndFailSilent(ZooKeeperWatcher zkw, CreateAndFailSilent cafs)
1257 throws KeeperException {
1258 CreateRequest create = (CreateRequest)toZooKeeperOp(zkw, cafs).toRequestRecord();
1259 String znode = create.getPath();
1260 try {
1261 RecoverableZooKeeper zk = zkw.getRecoverableZooKeeper();
1262 if (zk.exists(znode, false) == null) {
1263 zk.create(znode, create.getData(), create.getAcl(), CreateMode.fromFlag(create.getFlags()));
1264 }
1265 } catch(KeeperException.NodeExistsException nee) {
1266 } catch(KeeperException.NoAuthException nee){
1267 try {
1268 if (null == zkw.getRecoverableZooKeeper().exists(znode, false)) {
1269
1270 throw(nee);
1271 }
1272 } catch (InterruptedException ie) {
1273 zkw.interruptedException(ie);
1274 }
1275 } catch(InterruptedException ie) {
1276 zkw.interruptedException(ie);
1277 }
1278 }
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291 public static void createWithParents(ZooKeeperWatcher zkw, String znode)
1292 throws KeeperException {
1293 createWithParents(zkw, znode, new byte[0]);
1294 }
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309 public static void createWithParents(ZooKeeperWatcher zkw, String znode, byte[] data)
1310 throws KeeperException {
1311 try {
1312 if(znode == null) {
1313 return;
1314 }
1315 zkw.getRecoverableZooKeeper().create(znode, data, createACL(zkw, znode),
1316 CreateMode.PERSISTENT);
1317 } catch(KeeperException.NodeExistsException nee) {
1318 return;
1319 } catch(KeeperException.NoNodeException nne) {
1320 createWithParents(zkw, getParent(znode));
1321 createWithParents(zkw, znode, data);
1322 } catch(InterruptedException ie) {
1323 zkw.interruptedException(ie);
1324 }
1325 }
1326
1327
1328
1329
1330
1331
1332
1333
1334 public static void deleteNode(ZooKeeperWatcher zkw, String node)
1335 throws KeeperException {
1336 deleteNode(zkw, node, -1);
1337 }
1338
1339
1340
1341
1342
1343 public static boolean deleteNode(ZooKeeperWatcher zkw, String node,
1344 int version)
1345 throws KeeperException {
1346 try {
1347 zkw.getRecoverableZooKeeper().delete(node, version);
1348 return true;
1349 } catch(KeeperException.BadVersionException bve) {
1350 return false;
1351 } catch(InterruptedException ie) {
1352 zkw.interruptedException(ie);
1353 return false;
1354 }
1355 }
1356
1357
1358
1359
1360
1361
1362
1363 public static void deleteNodeFailSilent(ZooKeeperWatcher zkw, String node)
1364 throws KeeperException {
1365 deleteNodeFailSilent(zkw,
1366 (DeleteNodeFailSilent)ZKUtilOp.deleteNodeFailSilent(node));
1367 }
1368
1369 private static void deleteNodeFailSilent(ZooKeeperWatcher zkw,
1370 DeleteNodeFailSilent dnfs) throws KeeperException {
1371 DeleteRequest delete = (DeleteRequest)toZooKeeperOp(zkw, dnfs).toRequestRecord();
1372 try {
1373 zkw.getRecoverableZooKeeper().delete(delete.getPath(), delete.getVersion());
1374 } catch(KeeperException.NoNodeException nne) {
1375 } catch(InterruptedException ie) {
1376 zkw.interruptedException(ie);
1377 }
1378 }
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389 public static void deleteNodeRecursively(ZooKeeperWatcher zkw, String node)
1390 throws KeeperException {
1391 try {
1392 List<String> children = ZKUtil.listChildrenNoWatch(zkw, node);
1393
1394 if (children == null) return;
1395
1396 if(!children.isEmpty()) {
1397 for(String child : children) {
1398 deleteNodeRecursively(zkw, joinZNode(node, child));
1399 }
1400 }
1401
1402
1403
1404 if (zkw.getRecoverableZooKeeper().exists(node, zkw) != null){
1405 zkw.getRecoverableZooKeeper().delete(node, -1);
1406 }
1407 } catch(InterruptedException ie) {
1408 zkw.interruptedException(ie);
1409 }
1410 }
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423 public static void deleteChildrenRecursively(ZooKeeperWatcher zkw, String node)
1424 throws KeeperException {
1425 deleteChildrenRecursivelyMultiOrSequential(zkw, true, node);
1426 }
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462 public static void deleteChildrenRecursivelyMultiOrSequential(
1463 ZooKeeperWatcher zkw, boolean runSequentialOnMultiFailure,
1464 String... pathRoots) throws KeeperException {
1465 if (pathRoots == null || pathRoots.length <= 0) {
1466 LOG.warn("Given path is not valid!");
1467 return;
1468 }
1469 List<ZKUtilOp> ops = new ArrayList<ZKUtil.ZKUtilOp>();
1470 for (String eachRoot : pathRoots) {
1471 List<String> children = listChildrenBFSNoWatch(zkw, eachRoot);
1472
1473 for (int i = children.size() - 1; i >= 0; --i) {
1474 ops.add(ZKUtilOp.deleteNodeFailSilent(children.get(i)));
1475 }
1476 }
1477
1478 if (ops.size() > 0) {
1479 multiOrSequential(zkw, ops, runSequentialOnMultiFailure);
1480 }
1481 }
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496 private static List<String> listChildrenBFSNoWatch(ZooKeeperWatcher zkw,
1497 final String znode) throws KeeperException {
1498 Deque<String> queue = new LinkedList<String>();
1499 List<String> tree = new ArrayList<String>();
1500 queue.add(znode);
1501 while (true) {
1502 String node = queue.pollFirst();
1503 if (node == null) {
1504 break;
1505 }
1506 List<String> children = listChildrenNoWatch(zkw, node);
1507 if (children == null) {
1508 continue;
1509 }
1510 for (final String child : children) {
1511 final String childPath = node + "/" + child;
1512 queue.add(childPath);
1513 tree.add(childPath);
1514 }
1515 }
1516 return tree;
1517 }
1518
1519
1520
1521
1522
1523
1524 public abstract static class ZKUtilOp {
1525 private String path;
1526
1527 private ZKUtilOp(String path) {
1528 this.path = path;
1529 }
1530
1531
1532
1533
1534 public static ZKUtilOp createAndFailSilent(String path, byte[] data) {
1535 return new CreateAndFailSilent(path, data);
1536 }
1537
1538
1539
1540
1541 public static ZKUtilOp deleteNodeFailSilent(String path) {
1542 return new DeleteNodeFailSilent(path);
1543 }
1544
1545
1546
1547
1548 public static ZKUtilOp setData(String path, byte [] data) {
1549 return new SetData(path, data);
1550 }
1551
1552
1553
1554
1555 public String getPath() {
1556 return path;
1557 }
1558
1559
1560
1561
1562
1563 public static class CreateAndFailSilent extends ZKUtilOp {
1564 private byte [] data;
1565
1566 private CreateAndFailSilent(String path, byte [] data) {
1567 super(path);
1568 this.data = data;
1569 }
1570
1571 public byte[] getData() {
1572 return data;
1573 }
1574
1575 @Override
1576 public boolean equals(Object o) {
1577 if (this == o) return true;
1578 if (!(o instanceof CreateAndFailSilent)) return false;
1579
1580 CreateAndFailSilent op = (CreateAndFailSilent) o;
1581 return getPath().equals(op.getPath()) && Arrays.equals(data, op.data);
1582 }
1583
1584 @Override
1585 public int hashCode() {
1586 int ret = 17 + getPath().hashCode() * 31;
1587 return ret * 31 + Bytes.hashCode(data);
1588 }
1589 }
1590
1591
1592
1593
1594
1595 public static class DeleteNodeFailSilent extends ZKUtilOp {
1596 private DeleteNodeFailSilent(String path) {
1597 super(path);
1598 }
1599
1600 @Override
1601 public boolean equals(Object o) {
1602 if (this == o) return true;
1603 if (!(o instanceof DeleteNodeFailSilent)) return false;
1604
1605 return super.equals(o);
1606 }
1607
1608 @Override
1609 public int hashCode() {
1610 return getPath().hashCode();
1611 }
1612 }
1613
1614
1615
1616
1617 public static class SetData extends ZKUtilOp {
1618 private byte [] data;
1619
1620 private SetData(String path, byte [] data) {
1621 super(path);
1622 this.data = data;
1623 }
1624
1625 public byte[] getData() {
1626 return data;
1627 }
1628
1629 @Override
1630 public boolean equals(Object o) {
1631 if (this == o) return true;
1632 if (!(o instanceof SetData)) return false;
1633
1634 SetData op = (SetData) o;
1635 return getPath().equals(op.getPath()) && Arrays.equals(data, op.data);
1636 }
1637
1638 @Override
1639 public int hashCode() {
1640 int ret = getPath().hashCode();
1641 return ret * 31 + Bytes.hashCode(data);
1642 }
1643 }
1644 }
1645
1646
1647
1648
1649 private static Op toZooKeeperOp(ZooKeeperWatcher zkw, ZKUtilOp op)
1650 throws UnsupportedOperationException {
1651 if(op == null) return null;
1652
1653 if (op instanceof CreateAndFailSilent) {
1654 CreateAndFailSilent cafs = (CreateAndFailSilent)op;
1655 return Op.create(cafs.getPath(), cafs.getData(), createACL(zkw, cafs.getPath()),
1656 CreateMode.PERSISTENT);
1657 } else if (op instanceof DeleteNodeFailSilent) {
1658 DeleteNodeFailSilent dnfs = (DeleteNodeFailSilent)op;
1659 return Op.delete(dnfs.getPath(), -1);
1660 } else if (op instanceof SetData) {
1661 SetData sd = (SetData)op;
1662 return Op.setData(sd.getPath(), sd.getData(), -1);
1663 } else {
1664 throw new UnsupportedOperationException("Unexpected ZKUtilOp type: "
1665 + op.getClass().getName());
1666 }
1667 }
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690 public static void multiOrSequential(ZooKeeperWatcher zkw, List<ZKUtilOp> ops,
1691 boolean runSequentialOnMultiFailure) throws KeeperException {
1692 if (ops == null) return;
1693 boolean useMulti = zkw.getConfiguration().getBoolean(HConstants.ZOOKEEPER_USEMULTI, false);
1694
1695 if (useMulti) {
1696 List<Op> zkOps = new LinkedList<Op>();
1697 for (ZKUtilOp op : ops) {
1698 zkOps.add(toZooKeeperOp(zkw, op));
1699 }
1700 try {
1701 zkw.getRecoverableZooKeeper().multi(zkOps);
1702 } catch (KeeperException ke) {
1703 switch (ke.code()) {
1704 case NODEEXISTS:
1705 case NONODE:
1706 case BADVERSION:
1707 case NOAUTH:
1708
1709
1710 if (runSequentialOnMultiFailure) {
1711 LOG.info("On call to ZK.multi, received exception: " + ke.toString() + "."
1712 + " Attempting to run operations sequentially because"
1713 + " runSequentialOnMultiFailure is: " + runSequentialOnMultiFailure + ".");
1714 processSequentially(zkw, ops);
1715 break;
1716 }
1717 default:
1718 throw ke;
1719 }
1720 } catch (InterruptedException ie) {
1721 zkw.interruptedException(ie);
1722 }
1723 } else {
1724
1725 processSequentially(zkw, ops);
1726 }
1727
1728 }
1729
1730 private static void processSequentially(ZooKeeperWatcher zkw, List<ZKUtilOp> ops)
1731 throws KeeperException, NoNodeException {
1732 for (ZKUtilOp op : ops) {
1733 if (op instanceof CreateAndFailSilent) {
1734 createAndFailSilent(zkw, (CreateAndFailSilent) op);
1735 } else if (op instanceof DeleteNodeFailSilent) {
1736 deleteNodeFailSilent(zkw, (DeleteNodeFailSilent) op);
1737 } else if (op instanceof SetData) {
1738 setData(zkw, (SetData) op);
1739 } else {
1740 throw new UnsupportedOperationException("Unexpected ZKUtilOp type: "
1741 + op.getClass().getName());
1742 }
1743 }
1744 }
1745
1746
1747
1748
1749
1750
1751 public static String dump(ZooKeeperWatcher zkw) {
1752 StringBuilder sb = new StringBuilder();
1753 try {
1754 sb.append("HBase is rooted at ").append(zkw.baseZNode);
1755 sb.append("\nActive master address: ");
1756 try {
1757 sb.append(MasterAddressTracker.getMasterAddress(zkw));
1758 } catch (IOException e) {
1759 sb.append("<<FAILED LOOKUP: " + e.getMessage() + ">>");
1760 }
1761 sb.append("\nBackup master addresses:");
1762 for (String child : listChildrenNoWatch(zkw,
1763 zkw.backupMasterAddressesZNode)) {
1764 sb.append("\n ").append(child);
1765 }
1766 sb.append("\nRegion server holding hbase:meta: "
1767 + new MetaTableLocator().getMetaRegionLocation(zkw));
1768 Configuration conf = HBaseConfiguration.create();
1769 int numMetaReplicas = conf.getInt(HConstants.META_REPLICAS_NUM,
1770 HConstants.DEFAULT_META_REPLICA_NUM);
1771 for (int i = 1; i < numMetaReplicas; i++) {
1772 sb.append("\nRegion server holding hbase:meta, replicaId " + i + " "
1773 + new MetaTableLocator().getMetaRegionLocation(zkw, i));
1774 }
1775 sb.append("\nRegion servers:");
1776 for (String child : listChildrenNoWatch(zkw, zkw.rsZNode)) {
1777 sb.append("\n ").append(child);
1778 }
1779 try {
1780 getReplicationZnodesDump(zkw, sb);
1781 } catch (KeeperException ke) {
1782 LOG.warn("Couldn't get the replication znode dump", ke);
1783 }
1784 sb.append("\nQuorum Server Statistics:");
1785 String[] servers = zkw.getQuorum().split(",");
1786 for (String server : servers) {
1787 sb.append("\n ").append(server);
1788 try {
1789 String[] stat = getServerStats(server, ZKUtil.zkDumpConnectionTimeOut);
1790
1791 if (stat == null) {
1792 sb.append("[Error] invalid quorum server: " + server);
1793 break;
1794 }
1795
1796 for (String s : stat) {
1797 sb.append("\n ").append(s);
1798 }
1799 } catch (Exception e) {
1800 sb.append("\n ERROR: ").append(e.getMessage());
1801 }
1802 }
1803 } catch (KeeperException ke) {
1804 sb.append("\nFATAL ZooKeeper Exception!\n");
1805 sb.append("\n" + ke.getMessage());
1806 }
1807 return sb.toString();
1808 }
1809
1810
1811
1812
1813
1814
1815
1816 private static void getReplicationZnodesDump(ZooKeeperWatcher zkw, StringBuilder sb)
1817 throws KeeperException {
1818 String replicationZNodeName = zkw.getConfiguration().get("zookeeper.znode.replication",
1819 "replication");
1820 String replicationZnode = joinZNode(zkw.baseZNode, replicationZNodeName);
1821 if (ZKUtil.checkExists(zkw, replicationZnode) == -1) return;
1822
1823 sb.append("\n").append(replicationZnode).append(": ");
1824 List<String> children = ZKUtil.listChildrenNoWatch(zkw, replicationZnode);
1825 for (String child : children) {
1826 String znode = joinZNode(replicationZnode, child);
1827 if (child.equals(zkw.getConfiguration().get("zookeeper.znode.replication.peers", "peers"))) {
1828 appendPeersZnodes(zkw, znode, sb);
1829 } else if (child.equals(zkw.getConfiguration().
1830 get("zookeeper.znode.replication.rs", "rs"))) {
1831 appendRSZnodes(zkw, znode, sb);
1832 }
1833 }
1834 }
1835
1836 private static void appendRSZnodes(ZooKeeperWatcher zkw, String znode, StringBuilder sb)
1837 throws KeeperException {
1838 List<String> stack = new LinkedList<String>();
1839 stack.add(znode);
1840 do {
1841 String znodeToProcess = stack.remove(stack.size() - 1);
1842 sb.append("\n").append(znodeToProcess).append(": ");
1843 byte[] data;
1844 try {
1845 data = ZKUtil.getData(zkw, znodeToProcess);
1846 } catch (InterruptedException e) {
1847 zkw.interruptedException(e);
1848 return;
1849 }
1850 if (data != null && data.length > 0) {
1851 long position = 0;
1852 try {
1853 position = ZKUtil.parseWALPositionFrom(ZKUtil.getData(zkw, znodeToProcess));
1854 sb.append(position);
1855 } catch (DeserializationException ignored) {
1856 } catch (InterruptedException e) {
1857 zkw.interruptedException(e);
1858 return;
1859 }
1860 }
1861 for (String zNodeChild : ZKUtil.listChildrenNoWatch(zkw, znodeToProcess)) {
1862 stack.add(ZKUtil.joinZNode(znodeToProcess, zNodeChild));
1863 }
1864 } while (stack.size() > 0);
1865 }
1866
1867 private static void appendPeersZnodes(ZooKeeperWatcher zkw, String peersZnode,
1868 StringBuilder sb) throws KeeperException {
1869 int pblen = ProtobufUtil.lengthOfPBMagic();
1870 sb.append("\n").append(peersZnode).append(": ");
1871 for (String peerIdZnode : ZKUtil.listChildrenNoWatch(zkw, peersZnode)) {
1872 String znodeToProcess = ZKUtil.joinZNode(peersZnode, peerIdZnode);
1873 byte[] data;
1874 try {
1875 data = ZKUtil.getData(zkw, znodeToProcess);
1876 } catch (InterruptedException e) {
1877 zkw.interruptedException(e);
1878 return;
1879 }
1880
1881 try {
1882 String clusterKey = ZooKeeperProtos.ReplicationPeer.newBuilder().
1883 mergeFrom(data, pblen, data.length - pblen).getClusterkey();
1884 sb.append("\n").append(znodeToProcess).append(": ").append(clusterKey);
1885
1886 appendPeerState(zkw, znodeToProcess, sb);
1887 } catch (InvalidProtocolBufferException ipbe) {
1888 LOG.warn("Got Exception while parsing peer: " + znodeToProcess, ipbe);
1889 }
1890 }
1891 }
1892
1893 private static void appendPeerState(ZooKeeperWatcher zkw, String znodeToProcess,
1894 StringBuilder sb) throws KeeperException, InvalidProtocolBufferException {
1895 String peerState = zkw.getConfiguration().get("zookeeper.znode.replication.peers.state",
1896 "peer-state");
1897 int pblen = ProtobufUtil.lengthOfPBMagic();
1898 for (String child : ZKUtil.listChildrenNoWatch(zkw, znodeToProcess)) {
1899 if (!child.equals(peerState)) continue;
1900 String peerStateZnode = ZKUtil.joinZNode(znodeToProcess, child);
1901 sb.append("\n").append(peerStateZnode).append(": ");
1902 byte[] peerStateData;
1903 try {
1904 peerStateData = ZKUtil.getData(zkw, peerStateZnode);
1905 sb.append(ZooKeeperProtos.ReplicationState.newBuilder()
1906 .mergeFrom(peerStateData, pblen, peerStateData.length - pblen).getState().name());
1907 } catch (InterruptedException e) {
1908 zkw.interruptedException(e);
1909 return;
1910 }
1911 }
1912 }
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922 public static String[] getServerStats(String server, int timeout)
1923 throws IOException {
1924 String[] sp = server.split(":");
1925 if (sp == null || sp.length == 0) {
1926 return null;
1927 }
1928
1929 String host = sp[0];
1930 int port = sp.length > 1 ? Integer.parseInt(sp[1])
1931 : HConstants.DEFAULT_ZOOKEPER_CLIENT_PORT;
1932
1933 Socket socket = new Socket();
1934 InetSocketAddress sockAddr = new InetSocketAddress(host, port);
1935 socket.connect(sockAddr, timeout);
1936
1937 socket.setSoTimeout(timeout);
1938 PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
1939 BufferedReader in = new BufferedReader(new InputStreamReader(
1940 socket.getInputStream()));
1941 out.println("stat");
1942 out.flush();
1943 ArrayList<String> res = new ArrayList<String>();
1944 while (true) {
1945 String line = in.readLine();
1946 if (line != null) {
1947 res.add(line);
1948 } else {
1949 break;
1950 }
1951 }
1952 socket.close();
1953 return res.toArray(new String[res.size()]);
1954 }
1955
1956 private static void logRetrievedMsg(final ZooKeeperWatcher zkw,
1957 final String znode, final byte [] data, final boolean watcherSet) {
1958 if (!LOG.isTraceEnabled()) return;
1959 LOG.trace(zkw.prefix("Retrieved " + ((data == null)? 0: data.length) +
1960 " byte(s) of data from znode " + znode +
1961 (watcherSet? " and set watcher; ": "; data=") +
1962 (data == null? "null": data.length == 0? "empty": (
1963 znode.startsWith(zkw.assignmentZNode)?
1964 ZKAssign.toString(data):
1965 znode.startsWith(ZooKeeperWatcher.META_ZNODE_PREFIX)?
1966 getServerNameOrEmptyString(data):
1967 znode.startsWith(zkw.backupMasterAddressesZNode)?
1968 getServerNameOrEmptyString(data):
1969 StringUtils.abbreviate(Bytes.toStringBinary(data), 32)))));
1970 }
1971
1972 private static String getServerNameOrEmptyString(final byte [] data) {
1973 try {
1974 return ServerName.parseFrom(data).toString();
1975 } catch (DeserializationException e) {
1976 return "";
1977 }
1978 }
1979
1980
1981
1982
1983
1984 public static void waitForBaseZNode(Configuration conf) throws IOException {
1985 LOG.info("Waiting until the base znode is available");
1986 String parentZNode = conf.get(HConstants.ZOOKEEPER_ZNODE_PARENT,
1987 HConstants.DEFAULT_ZOOKEEPER_ZNODE_PARENT);
1988 ZooKeeper zk = new ZooKeeper(ZKConfig.getZKQuorumServersString(conf),
1989 conf.getInt(HConstants.ZK_SESSION_TIMEOUT,
1990 HConstants.DEFAULT_ZK_SESSION_TIMEOUT), EmptyWatcher.instance);
1991
1992 final int maxTimeMs = 10000;
1993 final int maxNumAttempts = maxTimeMs / HConstants.SOCKET_RETRY_WAIT_MS;
1994
1995 KeeperException keeperEx = null;
1996 try {
1997 try {
1998 for (int attempt = 0; attempt < maxNumAttempts; ++attempt) {
1999 try {
2000 if (zk.exists(parentZNode, false) != null) {
2001 LOG.info("Parent znode exists: " + parentZNode);
2002 keeperEx = null;
2003 break;
2004 }
2005 } catch (KeeperException e) {
2006 keeperEx = e;
2007 }
2008 Threads.sleepWithoutInterrupt(HConstants.SOCKET_RETRY_WAIT_MS);
2009 }
2010 } finally {
2011 zk.close();
2012 }
2013 } catch (InterruptedException ex) {
2014 Thread.currentThread().interrupt();
2015 }
2016
2017 if (keeperEx != null) {
2018 throw new IOException(keeperEx);
2019 }
2020 }
2021
2022
2023 public static byte[] blockUntilAvailable(
2024 final ZooKeeperWatcher zkw, final String znode, final long timeout)
2025 throws InterruptedException {
2026 if (timeout < 0) throw new IllegalArgumentException();
2027 if (zkw == null) throw new IllegalArgumentException();
2028 if (znode == null) throw new IllegalArgumentException();
2029
2030 byte[] data = null;
2031 boolean finished = false;
2032 final long endTime = System.currentTimeMillis() + timeout;
2033 while (!finished) {
2034 try {
2035 data = ZKUtil.getData(zkw, znode);
2036 } catch(KeeperException e) {
2037 if (e instanceof KeeperException.SessionExpiredException
2038 || e instanceof KeeperException.AuthFailedException) {
2039
2040 throw new InterruptedException("interrupted due to " + e);
2041 }
2042 LOG.warn("Unexpected exception handling blockUntilAvailable", e);
2043 }
2044
2045 if (data == null && (System.currentTimeMillis() +
2046 HConstants.SOCKET_RETRY_WAIT_MS < endTime)) {
2047 Thread.sleep(HConstants.SOCKET_RETRY_WAIT_MS);
2048 } else {
2049 finished = true;
2050 }
2051 }
2052
2053 return data;
2054 }
2055
2056
2057
2058
2059
2060
2061
2062
2063 public static KeeperException convert(final DeserializationException e) {
2064 KeeperException ke = new KeeperException.DataInconsistencyException();
2065 ke.initCause(e);
2066 return ke;
2067 }
2068
2069
2070
2071
2072
2073
2074 public static void logZKTree(ZooKeeperWatcher zkw, String root) {
2075 if (!LOG.isDebugEnabled()) return;
2076 LOG.debug("Current zk system:");
2077 String prefix = "|-";
2078 LOG.debug(prefix + root);
2079 try {
2080 logZKTree(zkw, root, prefix);
2081 } catch (KeeperException e) {
2082 throw new RuntimeException(e);
2083 }
2084 }
2085
2086
2087
2088
2089
2090
2091 protected static void logZKTree(ZooKeeperWatcher zkw, String root, String prefix)
2092 throws KeeperException {
2093 List<String> children = ZKUtil.listChildrenNoWatch(zkw, root);
2094 if (children == null) return;
2095 for (String child : children) {
2096 LOG.debug(prefix + child);
2097 String node = ZKUtil.joinZNode(root.equals("/") ? "" : root, child);
2098 logZKTree(zkw, node, prefix + "---");
2099 }
2100 }
2101
2102
2103
2104
2105
2106
2107 public static byte[] positionToByteArray(final long position) {
2108 byte[] bytes = ZooKeeperProtos.ReplicationHLogPosition.newBuilder().setPosition(position)
2109 .build().toByteArray();
2110 return ProtobufUtil.prependPBMagic(bytes);
2111 }
2112
2113
2114
2115
2116
2117
2118 public static long parseWALPositionFrom(final byte[] bytes) throws DeserializationException {
2119 if (bytes == null) {
2120 throw new DeserializationException("Unable to parse null WAL position.");
2121 }
2122 if (ProtobufUtil.isPBMagicPrefix(bytes)) {
2123 int pblen = ProtobufUtil.lengthOfPBMagic();
2124 ZooKeeperProtos.ReplicationHLogPosition.Builder builder =
2125 ZooKeeperProtos.ReplicationHLogPosition.newBuilder();
2126 ZooKeeperProtos.ReplicationHLogPosition position;
2127 try {
2128 position = builder.mergeFrom(bytes, pblen, bytes.length - pblen).build();
2129 } catch (InvalidProtocolBufferException e) {
2130 throw new DeserializationException(e);
2131 }
2132 return position.getPosition();
2133 } else {
2134 if (bytes.length > 0) {
2135 return Bytes.toLong(bytes);
2136 }
2137 return 0;
2138 }
2139 }
2140
2141
2142
2143
2144
2145
2146
2147
2148 public static byte[] regionSequenceIdsToByteArray(final Long regionLastFlushedSequenceId,
2149 final Map<byte[], Long> storeSequenceIds) {
2150 ClusterStatusProtos.RegionStoreSequenceIds.Builder regionSequenceIdsBuilder =
2151 ClusterStatusProtos.RegionStoreSequenceIds.newBuilder();
2152 ClusterStatusProtos.StoreSequenceId.Builder storeSequenceIdBuilder =
2153 ClusterStatusProtos.StoreSequenceId.newBuilder();
2154 if (storeSequenceIds != null) {
2155 for (Map.Entry<byte[], Long> e : storeSequenceIds.entrySet()){
2156 byte[] columnFamilyName = e.getKey();
2157 Long curSeqId = e.getValue();
2158 storeSequenceIdBuilder.setFamilyName(ByteStringer.wrap(columnFamilyName));
2159 storeSequenceIdBuilder.setSequenceId(curSeqId);
2160 regionSequenceIdsBuilder.addStoreSequenceId(storeSequenceIdBuilder.build());
2161 storeSequenceIdBuilder.clear();
2162 }
2163 }
2164 regionSequenceIdsBuilder.setLastFlushedSequenceId(regionLastFlushedSequenceId);
2165 byte[] result = regionSequenceIdsBuilder.build().toByteArray();
2166 return ProtobufUtil.prependPBMagic(result);
2167 }
2168
2169
2170
2171
2172
2173
2174 public static RegionStoreSequenceIds parseRegionStoreSequenceIds(final byte[] bytes)
2175 throws DeserializationException {
2176 if (bytes == null || !ProtobufUtil.isPBMagicPrefix(bytes)) {
2177 throw new DeserializationException("Unable to parse RegionStoreSequenceIds.");
2178 }
2179 RegionStoreSequenceIds.Builder regionSequenceIdsBuilder =
2180 ClusterStatusProtos.RegionStoreSequenceIds.newBuilder();
2181 int pblen = ProtobufUtil.lengthOfPBMagic();
2182 RegionStoreSequenceIds storeIds = null;
2183 try {
2184 storeIds = regionSequenceIdsBuilder.mergeFrom(bytes, pblen, bytes.length - pblen).build();
2185 } catch (InvalidProtocolBufferException e) {
2186 throw new DeserializationException(e);
2187 }
2188 return storeIds;
2189 }
2190 }