View Javadoc

1   /**
2    *
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *     http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing, software
14   * distributed under the License is distributed on an "AS IS" BASIS,
15   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16   * See the License for the specific language governing permissions and
17   * limitations under the License.
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   * Internal HBase utility class for ZooKeeper.
82   *
83   * <p>Contains only static methods and constants.
84   *
85   * <p>Methods all throw {@link KeeperException} if there is an unexpected
86   * zookeeper exception, so callers of these methods must handle appropriately.
87   * If ZK is required for the operation, the server will need to be aborted.
88   */
89  @InterfaceAudience.Private
90  public class ZKUtil {
91    private static final Log LOG = LogFactory.getLog(ZKUtil.class);
92  
93    // TODO: Replace this with ZooKeeper constant when ZOOKEEPER-277 is resolved.
94    public static final char ZNODE_PATH_SEPARATOR = '/';
95    private static int zkDumpConnectionTimeOut;
96  
97    // The Quorum for the ZK cluster can have one the following format (see examples below):
98    // (1). s1,s2,s3 (no client port in the list, the client port could be obtained from clientPort)
99    // (2). s1:p1,s2:p2,s3:p3 (with client port, which could be same or different for each server,
100   //      in this case, the clientPort would be ignored)
101   // (3). s1:p1,s2,s3:p3 (mix of (1) and (2) - if port is not specified in a server, it would use
102   //      the clientPort; otherwise, it would use the specified port)
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    * Creates a new connection to ZooKeeper, pulling settings and ensemble config
118    * from the specified configuration object using methods from {@link ZKConfig}.
119    *
120    * Sets the connection status monitoring watcher to the specified watcher.
121    *
122    * @param conf configuration to pull ensemble and other settings from
123    * @param watcher watcher to monitor connection changes
124    * @return connection to zookeeper
125    * @throws IOException if unable to connect to zk or config problem
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    * Log in the current zookeeper server process using the given configuration
161    * keys for the credential file and login principal.
162    *
163    * <p><strong>This is only applicable when running on secure hbase</strong>
164    * On regular HBase (without security features), this will safely be ignored.
165    * </p>
166    *
167    * @param conf The configuration data to use
168    * @param keytabFileKey Property key used to configure the path to the credential file
169    * @param userNameKey Property key used to configure the login principal
170    * @param hostname Current hostname to use in any credentials
171    * @throws IOException underlying exception from SecurityUtil.login() call
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    * Log in the current zookeeper client using the given configuration
182    * keys for the credential file and login principal.
183    *
184    * <p><strong>This is only applicable when running on secure hbase</strong>
185    * On regular HBase (without security features), this will safely be ignored.
186    * </p>
187    *
188    * @param conf The configuration data to use
189    * @param keytabFileKey Property key used to configure the path to the credential file
190    * @param userNameKey Property key used to configure the login principal
191    * @param hostname Current hostname to use in any credentials
192    * @throws IOException underlying exception from SecurityUtil.login() call
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    * Log in the current process using the given configuration keys for the
203    * credential file and login principal.
204    *
205    * <p><strong>This is only applicable when running on secure hbase</strong>
206    * On regular HBase (without security features), this will safely be ignored.
207    * </p>
208    *
209    * @param conf The configuration data to use
210    * @param keytabFileKey Property key used to configure the path to the credential file
211    * @param userNameKey Property key used to configure the login principal
212    * @param hostname Current hostname to use in any credentials
213    * @param loginContextProperty property name to expose the entry name
214    * @param loginContextName jaas entry name
215    * @throws IOException underlying exception from SecurityUtil.login() call
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     // User has specified a jaas.conf, keep this one as the good one.
225     // HBASE_OPTS="-Djava.security.auth.login.config=jaas.conf"
226     if (System.getProperty("java.security.auth.login.config") != null)
227       return;
228 
229     // No keytab specified, no auth
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     // Initialize the "jaas.conf" for keyTab/principal,
240     // If keyTab is not specified use the Ticket Cache.
241     // and set the zookeeper login context name.
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    * A JAAS configuration that defines the login modules that we want to use for login.
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   // Helper methods
331   //
332 
333   /**
334    * Join the prefix znode name with the suffix znode name to generate a proper
335    * full znode name.
336    *
337    * Assumes prefix does not end with slash and suffix does not begin with it.
338    *
339    * @param prefix beginning of znode name
340    * @param suffix ending of znode name
341    * @return result of properly joining prefix with suffix
342    */
343   public static String joinZNode(String prefix, String suffix) {
344     return prefix + ZNODE_PATH_SEPARATOR + suffix;
345   }
346 
347   /**
348    * Returns the full path of the immediate parent of the specified node.
349    * @param node path to get parent of
350    * @return parent of path, null if passed the root node or an invalid node
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    * Get the name of the current node from the specified fully-qualified path.
359    * @param path fully-qualified path
360    * @return name of the current node
361    */
362   public static String getNodeName(String path) {
363     return path.substring(path.lastIndexOf("/")+1);
364   }
365 
366   /**
367    * Get the key to the ZK ensemble for this configuration without
368    * adding a name at the end
369    * @param conf Configuration to use to build the key
370    * @return ensemble key without a name
371    */
372   public static String getZooKeeperClusterKey(Configuration conf) {
373     return getZooKeeperClusterKey(conf, null);
374   }
375 
376   /**
377    * Get the key to the ZK ensemble for this configuration and append
378    * a name at the end
379    * @param conf Configuration to use to build the key
380    * @param name Name that should be appended at the end if not empty or null
381    * @return ensemble key with a name (if any)
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    * Apply the settings in the given key to the given configuration, this is
400    * used to communicate with distant clusters
401    * @param conf configuration object to configure
402    * @param key string that contains the 3 required configuratins
403    * @throws IOException
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    * Separate the given key into the three configurations it should contain:
415    * hbase.zookeeper.quorum, hbase.zookeeper.client.port
416    * and zookeeper.znode.parent
417    * @param key
418    * @return the three configuration in the described order
419    * @throws IOException
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       // The quorum could contain client port in server:clientport format, try to transform more.
430       String zNodeParent = parts [parts.length - 1];
431       String clientPort = parts [parts.length - 2];
432 
433       // The first part length is the total length minus the lengths of other parts and minus 2 ":"
434       int endQuorumIndex = key.length() - zNodeParent.length() - clientPort.length() - 2;
435       String quorumStringInput = key.substring(0, endQuorumIndex);
436       String[] serverHosts = quorumStringInput.split(",");
437 
438       // The common case is that every server has its own client port specified - this means
439       // that (total parts - the ZNodeParent part - the ClientPort part) is equal to
440       // (the number of "," + 1) - "+ 1" because the last server has no ",".
441       if ((parts.length - 2) == (serverHosts.length + 1)) {
442         return new ZKClusterKey(quorumStringInput, Integer.parseInt(clientPort), zNodeParent);
443       }
444 
445       // For the uncommon case that some servers has no port specified, we need to build the
446       // server:clientport list using default client port for servers without specified port.
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    * Standardize the ZK quorum string: make it a "server:clientport" list, separated by ','
460    * @param quorumStringInput a string contains a list of servers for ZK quorum
461    * @param clientPort the default client port
462    * @return the string for a list of "server:port" separated by ","
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   // Existence checks and watches
472   //
473 
474   /**
475    * Watch the specified znode for delete/create/change events.  The watcher is
476    * set whether or not the node exists.  If the node already exists, the method
477    * returns true.  If the node does not exist, the method returns false.
478    *
479    * @param zkw zk reference
480    * @param znode path of node to watch
481    * @return true if znode exists, false if does not exist or error
482    * @throws KeeperException if unexpected zookeeper exception
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    * Watch the specified znode, but only if exists. Useful when watching
508    * for deletions. Uses .getData() (and handles NoNodeException) instead
509    * of .exists() to accomplish this, as .getData() will only set a watch if
510    * the znode exists.
511    * @param zkw zk reference
512    * @param znode path of node to watch
513    * @return true if the watch is set, false if node does not exists
514    * @throws KeeperException if unexpected zookeeper exception
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    * Check if the specified node exists.  Sets no watches.
532    *
533    * @param zkw zk reference
534    * @param znode path of node to watch
535    * @return version of the node if it exists, -1 if does not exist
536    * @throws KeeperException if unexpected zookeeper exception
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   // Znode listings
556   //
557 
558   /**
559    * Lists the children znodes of the specified znode.  Also sets a watch on
560    * the specified znode which will capture a NodeDeleted event on the specified
561    * znode as well as NodeChildrenChanged if any children of the specified znode
562    * are created or deleted.
563    *
564    * Returns null if the specified node does not exist.  Otherwise returns a
565    * list of children of the specified node.  If the node exists but it has no
566    * children, an empty list will be returned.
567    *
568    * @param zkw zk reference
569    * @param znode path of node to list and watch children of
570    * @return list of children of the specified node, an empty list if the node
571    *          exists but has no children, and null if the node does not exist
572    * @throws KeeperException if unexpected zookeeper exception
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    * List all the children of the specified znode, setting a watch for children
597    * changes and also setting a watch on every individual child in order to get
598    * the NodeCreated and NodeDeleted events.
599    * @param zkw zookeeper reference
600    * @param znode node to get children of and watch
601    * @return list of znode names, null if the node doesn't exist
602    * @throws KeeperException
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    * Lists the children of the specified znode without setting any watches.
618    *
619    * Sets no watches at all, this method is best effort.
620    *
621    * Returns an empty list if the node has no children.  Returns null if the
622    * parent node itself does not exist.
623    *
624    * @param zkw zookeeper reference
625    * @param znode node to get children
626    * @return list of data of children of specified znode, empty if no children,
627    *         null if parent does not exist
628    * @throws KeeperException if unexpected zookeeper exception
629    */
630   public static List<String> listChildrenNoWatch(ZooKeeperWatcher zkw, String znode)
631   throws KeeperException {
632     List<String> children = null;
633     try {
634       // List the children without watching
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    * Simple class to hold a node path and node data.
646    * @deprecated Unused
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    * Checks if the specified znode has any children.  Sets no watches.
673    *
674    * Returns true if the node exists and has children.  Returns false if the
675    * node does not exist or if the node does not have any children.
676    *
677    * Used during master initialization to determine if the master is a
678    * failed-over-to master or the first master during initial cluster startup.
679    * If the directory for regionserver ephemeral nodes is empty then this is
680    * a cluster startup, if not then it is not cluster startup.
681    *
682    * @param zkw zk reference
683    * @param znode path of node to check for children of
684    * @return true if node has children, false if not or node does not exist
685    * @throws KeeperException if unexpected zookeeper exception
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    * Get the number of children of the specified node.
708    *
709    * If the node does not exist or has no children, returns 0.
710    *
711    * Sets no watches at all.
712    *
713    * @param zkw zk reference
714    * @param znode path of node to count children of
715    * @return number of children of specified node, 0 if none or parent does not
716    *         exist
717    * @throws KeeperException if unexpected zookeeper exception
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   // Data retrieval
735   //
736 
737   /**
738    * Get znode data. Does not set a watcher.
739    * @return ZNode data, null if the node does not exist or if there is an
740    *  error.
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    * Get the data at the specified znode and set a watch.
761    *
762    * Returns the data and sets a watch if the node exists.  Returns null and no
763    * watch is set if the node does not exist or there is an exception.
764    *
765    * @param zkw zk reference
766    * @param znode path of node
767    * @return data of the specified znode, or null
768    * @throws KeeperException if unexpected zookeeper exception
769    */
770   public static byte [] getDataAndWatch(ZooKeeperWatcher zkw, String znode)
771   throws KeeperException {
772     return getDataInternal(zkw, znode, null, true);
773   }
774 
775   /**
776    * Get the data at the specified znode and set a watch.
777    *
778    * Returns the data and sets a watch if the node exists.  Returns null and no
779    * watch is set if the node does not exist or there is an exception.
780    *
781    * @param zkw zk reference
782    * @param znode path of node
783    * @param stat object to populate the version of the znode
784    * @return data of the specified znode, or null
785    * @throws KeeperException if unexpected zookeeper exception
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       // This log can get pretty annoying when we cycle on 100ms waits.
801       // Enable trace if you really want to see it.
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    * Get the data at the specified znode without setting a watch.
818    *
819    * Returns the data if the node exists.  Returns null if the node does not
820    * exist.
821    *
822    * Sets the stats of the node in the passed Stat object.  Pass a null stat if
823    * not interested.
824    *
825    * @param zkw zk reference
826    * @param znode path of node
827    * @param stat node status to get if node exists
828    * @return data of the specified znode, or null if node does not exist
829    * @throws KeeperException if unexpected zookeeper exception
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    * Returns the date of child znodes of the specified znode.  Also sets a watch on
855    * the specified znode which will capture a NodeDeleted event on the specified
856    * znode as well as NodeChildrenChanged if any children of the specified znode
857    * are created or deleted.
858    *
859    * Returns null if the specified node does not exist.  Otherwise returns a
860    * list of children of the specified node.  If the node exists but it has no
861    * children, an empty list will be returned.
862    *
863    * @param zkw zk reference
864    * @param baseNode path of node to list and watch children of
865    * @return list of data of children of the specified node, an empty list if the node
866    *          exists but has no children, and null if the node does not exist
867    * @throws KeeperException if unexpected zookeeper exception
868    * @deprecated Unused
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    * Update the data of an existing node with the expected version to have the
888    * specified data.
889    *
890    * Throws an exception if there is a version mismatch or some other problem.
891    *
892    * Sets no watches under any conditions.
893    *
894    * @param zkw zk reference
895    * @param znode
896    * @param data
897    * @param expectedVersion
898    * @throws KeeperException if unexpected zookeeper exception
899    * @throws KeeperException.BadVersionException if version mismatch
900    * @deprecated Unused
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   // Data setting
914   //
915 
916   /**
917    * Sets the data of the existing znode to be the specified data.  Ensures that
918    * the current data has the specified expected version.
919    *
920    * <p>If the node does not exist, a {@link NoNodeException} will be thrown.
921    *
922    * <p>If their is a version mismatch, method returns null.
923    *
924    * <p>No watches are set but setting data will trigger other watchers of this
925    * node.
926    *
927    * <p>If there is another problem, a KeeperException will be thrown.
928    *
929    * @param zkw zk reference
930    * @param znode path of node
931    * @param data data to set for node
932    * @param expectedVersion version expected when setting data
933    * @return true if data set, false if version mismatch
934    * @throws KeeperException if unexpected zookeeper exception
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    * Set data into node creating node if it doesn't yet exist.
949    * Does not set watch.
950    *
951    * @param zkw zk reference
952    * @param znode path of node
953    * @param data data to set for node
954    * @throws KeeperException
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    * Sets the data of the existing znode to be the specified data.  The node
968    * must exist but no checks are done on the existing data or version.
969    *
970    * <p>If the node does not exist, a {@link NoNodeException} will be thrown.
971    *
972    * <p>No watches are set but setting data will trigger other watchers of this
973    * node.
974    *
975    * <p>If there is another problem, a KeeperException will be thrown.
976    *
977    * @param zkw zk reference
978    * @param znode path of node
979    * @param data data to set for node
980    * @throws KeeperException if unexpected zookeeper exception
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    * Returns whether or not secure authentication is enabled
995    * (whether <code>hbase.security.authentication</code> is set to
996    * <code>kerberos</code>.
997    */
998   public static boolean isSecureZooKeeper(Configuration conf) {
999     // Detection for embedded HBase client with jaas configuration
1000     // defined for third party programs.
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       // No Jaas configuration defined.
1013       return false;
1014     }
1015 
1016     // Master & RSs uses hbase.zookeeper.client.*
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       // add permission to hbase supper user
1028       if (superUser != null) {
1029         acls.add(new ACL(Perms.ALL, new Id("auth", superUser)));
1030       }
1031       // Certain znodes are accessed directly by the client,
1032       // so they must be readable by non-authenticated clients
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   // Node creation
1054   //
1055 
1056   /**
1057    *
1058    * Set the specified znode to be an ephemeral node carrying the specified
1059    * data.
1060    *
1061    * If the node is created successfully, a watcher is also set on the node.
1062    *
1063    * If the node is not created successfully because it already exists, this
1064    * method will also set a watcher on the node.
1065    *
1066    * If there is another problem, a KeeperException will be thrown.
1067    *
1068    * @param zkw zk reference
1069    * @param znode path of node
1070    * @param data data of node
1071    * @return true if node created, false if not, watch set in both cases
1072    * @throws KeeperException if unexpected zookeeper exception
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       // It did exist but now it doesn't, try again
1089       return createEphemeralNodeAndWatch(zkw, znode, data);
1090     }
1091     return ret;
1092   }
1093 
1094   /**
1095    * Creates the specified znode to be a persistent node carrying the specified
1096    * data.
1097    *
1098    * Returns true if the node was successfully created, false if the node
1099    * already existed.
1100    *
1101    * If the node is created successfully, a watcher is also set on the node.
1102    *
1103    * If the node is not created successfully because it already exists, this
1104    * method will also set a watcher on the node but return false.
1105    *
1106    * If there is another problem, a KeeperException will be thrown.
1107    *
1108    * @param zkw zk reference
1109    * @param znode path of node
1110    * @param data data of node
1111    * @return true if node created, false if not, watch set in both cases
1112    * @throws KeeperException if unexpected zookeeper exception
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    * Creates the specified znode with the specified data but does not watch it.
1138    *
1139    * Returns the znode of the newly created node
1140    *
1141    * If there is another problem, a KeeperException will be thrown.
1142    *
1143    * @param zkw zk reference
1144    * @param znode path of node
1145    * @param data data of node
1146    * @param createMode specifying whether the node to be created is ephemeral and/or sequential
1147    * @return true name of the newly created znode or null
1148    * @throws KeeperException if unexpected zookeeper exception
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    * Creates the specified node with the specified data and watches it.
1168    *
1169    * <p>Throws an exception if the node already exists.
1170    *
1171    * <p>The node created is persistent and open access.
1172    *
1173    * <p>Returns the version number of the created node if successful.
1174    *
1175    * @param zkw zk reference
1176    * @param znode path of node to create
1177    * @param data data of node to create
1178    * @return version of node created
1179    * @throws KeeperException if unexpected zookeeper exception
1180    * @throws KeeperException.NodeExistsException if node already exists
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         // Likely a race condition. Someone deleted the znode.
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    * Async creates the specified node with the specified data.
1203    *
1204    * <p>Throws an exception if the node already exists.
1205    *
1206    * <p>The node created is persistent and open access.
1207    *
1208    * @param zkw zk reference
1209    * @param znode path of node to create
1210    * @param data data of node to create
1211    * @param cb
1212    * @param ctx
1213    * @throws KeeperException if unexpected zookeeper exception
1214    * @throws KeeperException.NodeExistsException if node already exists
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    * Creates the specified node, iff the node does not exist.  Does not set a
1225    * watch and fails silently if the node already exists.
1226    *
1227    * The node created is persistent and open access.
1228    *
1229    * @param zkw zk reference
1230    * @param znode path of node
1231    * @throws KeeperException if unexpected zookeeper exception
1232    */
1233   public static void createAndFailSilent(ZooKeeperWatcher zkw,
1234       String znode) throws KeeperException {
1235     createAndFailSilent(zkw, znode, new byte[0]);
1236   }
1237 
1238   /**
1239    * Creates the specified node containing specified data, iff the node does not exist.  Does
1240    * not set a watch and fails silently if the node already exists.
1241    *
1242    * The node created is persistent and open access.
1243    *
1244    * @param zkw zk reference
1245    * @param znode path of node
1246    * @param data a byte array data to store in the znode
1247    * @throws KeeperException if unexpected zookeeper exception
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           // If we failed to create the file and it does not already exist.
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    * Creates the specified node and all parent nodes required for it to exist.
1282    *
1283    * No watches are set and no errors are thrown if the node already exists.
1284    *
1285    * The nodes created are persistent and open access.
1286    *
1287    * @param zkw zk reference
1288    * @param znode path of node
1289    * @throws KeeperException if unexpected zookeeper exception
1290    */
1291   public static void createWithParents(ZooKeeperWatcher zkw, String znode)
1292   throws KeeperException {
1293     createWithParents(zkw, znode, new byte[0]);
1294   }
1295 
1296   /**
1297    * Creates the specified node and all parent nodes required for it to exist.  The creation of
1298    * parent znodes is not atomic with the leafe znode creation but the data is written atomically
1299    * when the leaf node is created.
1300    *
1301    * No watches are set and no errors are thrown if the node already exists.
1302    *
1303    * The nodes created are persistent and open access.
1304    *
1305    * @param zkw zk reference
1306    * @param znode path of node
1307    * @throws KeeperException if unexpected zookeeper exception
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   // Deletes
1329   //
1330 
1331   /**
1332    * Delete the specified node.  Sets no watches.  Throws all exceptions.
1333    */
1334   public static void deleteNode(ZooKeeperWatcher zkw, String node)
1335   throws KeeperException {
1336     deleteNode(zkw, node, -1);
1337   }
1338 
1339   /**
1340    * Delete the specified node with the specified version.  Sets no watches.
1341    * Throws all exceptions.
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    * Deletes the specified node.  Fails silent if the node does not exist.
1359    * @param zkw
1360    * @param node
1361    * @throws KeeperException
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    * Delete the specified node and all of it's children.
1383    * <p>
1384    * If the node does not exist, just returns.
1385    * <p>
1386    * Sets no watches. Throws all exceptions besides dealing with deletion of
1387    * children.
1388    */
1389   public static void deleteNodeRecursively(ZooKeeperWatcher zkw, String node)
1390   throws KeeperException {
1391     try {
1392       List<String> children = ZKUtil.listChildrenNoWatch(zkw, node);
1393       // the node is already deleted, so we just finish
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       //Zookeeper Watches are one time triggers; When children of parent nodes are deleted
1403       //recursively, must set another watch, get notified of delete node
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    * Delete all the children of the specified node but not the node itself.
1414    *
1415    * Sets no watches.  Throws all exceptions besides dealing with deletion of
1416    * children.
1417    *
1418    * If hbase.zookeeper.useMulti is true, use ZooKeeper's multi-update functionality.
1419    * Otherwise, run the list of operations sequentially.
1420    *
1421    * @throws KeeperException
1422    */
1423   public static void deleteChildrenRecursively(ZooKeeperWatcher zkw, String node)
1424       throws KeeperException {
1425     deleteChildrenRecursivelyMultiOrSequential(zkw, true, node);
1426   }
1427 
1428   /**
1429    * Delete all the children of the specified node but not the node itself. This
1430    * will first traverse the znode tree for listing the children and then delete
1431    * these znodes using multi-update api or sequential based on the specified
1432    * configurations.
1433    * <p>
1434    * Sets no watches. Throws all exceptions besides dealing with deletion of
1435    * children.
1436    * <p>
1437    * If hbase.zookeeper.useMulti is true, use ZooKeeper's multi-update
1438    * functionality. Otherwise, run the list of operations sequentially.
1439    * <p>
1440    * If all of the following are true:
1441    * <ul>
1442    * <li>runSequentialOnMultiFailure is true
1443    * <li>hbase.zookeeper.useMulti is true
1444    * </ul>
1445    * on calling multi, we get a ZooKeeper exception that can be handled by a
1446    * sequential call(*), we retry the operations one-by-one (sequentially).
1447    *
1448    * @param zkw
1449    *          - zk reference
1450    * @param runSequentialOnMultiFailure
1451    *          - if true when we get a ZooKeeper exception that could retry the
1452    *          operations one-by-one (sequentially)
1453    * @param pathRoots
1454    *          - path of the parent node(s)
1455    * @throws KeeperException.NotEmptyException
1456    *           if node has children while deleting
1457    * @throws KeeperException
1458    *           if unexpected ZooKeeper exception
1459    * @throws IllegalArgumentException
1460    *           if an invalid path is specified
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       // Delete the leaves first and eventually get rid of the root
1473       for (int i = children.size() - 1; i >= 0; --i) {
1474         ops.add(ZKUtilOp.deleteNodeFailSilent(children.get(i)));
1475       }
1476     }
1477     // atleast one element should exist
1478     if (ops.size() > 0) {
1479       multiOrSequential(zkw, ops, runSequentialOnMultiFailure);
1480     }
1481   }
1482 
1483   /**
1484    * BFS Traversal of all the children under path, with the entries in the list,
1485    * in the same order as that of the traversal. Lists all the children without
1486    * setting any watches.
1487    *
1488    * @param zkw
1489    *          - zk reference
1490    * @param znode
1491    *          - path of node
1492    * @return list of children znodes under the path
1493    * @throws KeeperException
1494    *           if unexpected ZooKeeper exception
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    * Represents an action taken by ZKUtil, e.g. createAndFailSilent.
1521    * These actions are higher-level than ZKOp actions, which represent
1522    * individual actions in the ZooKeeper API, like create.
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      * @return a createAndFailSilent ZKUtilOp
1533      */
1534     public static ZKUtilOp createAndFailSilent(String path, byte[] data) {
1535       return new CreateAndFailSilent(path, data);
1536     }
1537 
1538     /**
1539      * @return a deleteNodeFailSilent ZKUtilOP
1540      */
1541     public static ZKUtilOp deleteNodeFailSilent(String path) {
1542       return new DeleteNodeFailSilent(path);
1543     }
1544 
1545     /**
1546      * @return a setData ZKUtilOp
1547      */
1548     public static ZKUtilOp setData(String path, byte [] data) {
1549       return new SetData(path, data);
1550     }
1551 
1552     /**
1553      * @return path to znode where the ZKOp will occur
1554      */
1555     public String getPath() {
1556       return path;
1557     }
1558 
1559     /**
1560      * ZKUtilOp representing createAndFailSilent in ZooKeeper
1561      * (attempt to create node, ignore error if already exists)
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      * ZKUtilOp representing deleteNodeFailSilent in ZooKeeper
1593      * (attempt to delete node, ignore error if node doesn't exist)
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      * ZKUtilOp representing setData in ZooKeeper
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    * Convert from ZKUtilOp to ZKOp
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    * If hbase.zookeeper.useMulti is true, use ZooKeeper's multi-update functionality.
1671    * Otherwise, run the list of operations sequentially.
1672    *
1673    * If all of the following are true:
1674    * - runSequentialOnMultiFailure is true
1675    * - hbase.zookeeper.useMulti is true
1676    * - on calling multi, we get a ZooKeeper exception that can be handled by a sequential call(*)
1677    * Then:
1678    * - we retry the operations one-by-one (sequentially)
1679    *
1680    * Note *: an example is receiving a NodeExistsException from a "create" call.  Without multi,
1681    * a user could call "createAndFailSilent" to ensure that a node exists if they don't care who
1682    * actually created the node (i.e. the NodeExistsException from ZooKeeper is caught).
1683    * This will cause all operations in the multi to fail, however, because
1684    * the NodeExistsException that zk.create throws will fail the multi transaction.
1685    * In this case, if the previous conditions hold, the commands are run sequentially, which should
1686    * result in the correct final state, but means that the operations will not run atomically.
1687    *
1688    * @throws KeeperException
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            // if we get an exception that could be solved by running sequentially
1709            // (and the client asked us to), then break out and run sequentially
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       // run sequentially
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   // ZooKeeper cluster information
1748   //
1749 
1750   /** @return String dump of everything in ZooKeeper. */
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    * Appends replication znodes to the passed StringBuilder.
1812    * @param zkw
1813    * @param sb
1814    * @throws KeeperException
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     // do a ls -r on this znode
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) { // log position
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       // parse the data of the above peer znode.
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       // add the peer-state.
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    * Gets the statistics from the given server.
1916    *
1917    * @param server  The server to get the statistics from.
1918    * @param timeout  The socket timeout to use.
1919    * @return The array of response strings.
1920    * @throws IOException When the socket communication fails.
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): // We should not be doing this reaching into another class
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    * Waits for HBase installation's base (parent) znode to become available.
1982    * @throws IOException on ZK errors
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           // non-recoverable errors so stop here
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    * Convert a {@link DeserializationException} to a more palatable {@link KeeperException}.
2059    * Used when can't let a {@link DeserializationException} out w/o changing public API.
2060    * @param e Exception to convert
2061    * @return Converted exception
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    * Recursively print the current state of ZK (non-transactional)
2071    * @param root name of the root directory in zk to print
2072    * @throws KeeperException
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    * Helper method to print the current state of the ZK tree.
2088    * @see #logZKTree(ZooKeeperWatcher, String)
2089    * @throws KeeperException if an unexpected exception occurs
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    * @param position
2104    * @return Serialized protobuf of <code>position</code> with pb magic prefix prepended suitable
2105    *         for use as content of an wal position in a replication queue.
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    * @param bytes - Content of a WAL position znode.
2115    * @return long - The current WAL position.
2116    * @throws DeserializationException
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    * @param regionLastFlushedSequenceId the flushed sequence id of a region which is the min of its
2143    *          store max seq ids
2144    * @param storeSequenceIds column family to sequence Id map
2145    * @return Serialized protobuf of <code>RegionSequenceIds</code> with pb magic prefix prepended
2146    *         suitable for use to filter wal edits in distributedLogReplay mode
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    * @param bytes Content of serialized data of RegionStoreSequenceIds
2171    * @return a RegionStoreSequenceIds object
2172    * @throws DeserializationException
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 }