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.HashMap;
30  import java.util.LinkedList;
31  import java.util.List;
32  import java.util.Map;
33  import java.util.Properties;
34  
35  import javax.security.auth.login.AppConfigurationEntry;
36  import javax.security.auth.login.AppConfigurationEntry.LoginModuleControlFlag;
37  
38  import com.google.protobuf.HBaseZeroCopyByteString;
39  import org.apache.commons.lang.StringUtils;
40  import org.apache.commons.logging.Log;
41  import org.apache.commons.logging.LogFactory;
42  import org.apache.hadoop.classification.InterfaceAudience;
43  import org.apache.hadoop.conf.Configuration;
44  import org.apache.hadoop.hbase.HConstants;
45  import org.apache.hadoop.hbase.ServerName;
46  import org.apache.hadoop.hbase.exceptions.DeserializationException;
47  import org.apache.hadoop.hbase.protobuf.ProtobufUtil;
48  import org.apache.hadoop.hbase.protobuf.generated.ZooKeeperProtos;
49  import org.apache.hadoop.hbase.protobuf.generated.ZooKeeperProtos.RegionStoreSequenceIds;
50  import org.apache.hadoop.hbase.util.Bytes;
51  import org.apache.hadoop.hbase.util.ExceptionUtil;
52  import org.apache.hadoop.hbase.util.Threads;
53  import org.apache.hadoop.hbase.zookeeper.ZKUtil.ZKUtilOp.CreateAndFailSilent;
54  import org.apache.hadoop.hbase.zookeeper.ZKUtil.ZKUtilOp.DeleteNodeFailSilent;
55  import org.apache.hadoop.hbase.zookeeper.ZKUtil.ZKUtilOp.SetData;
56  import org.apache.hadoop.security.SecurityUtil;
57  import org.apache.hadoop.security.authentication.util.KerberosUtil;
58  import org.apache.zookeeper.AsyncCallback;
59  import org.apache.zookeeper.CreateMode;
60  import org.apache.zookeeper.KeeperException;
61  import org.apache.zookeeper.KeeperException.NoNodeException;
62  import org.apache.zookeeper.Op;
63  import org.apache.zookeeper.Watcher;
64  import org.apache.zookeeper.ZooDefs.Ids;
65  import org.apache.zookeeper.ZooKeeper;
66  import org.apache.zookeeper.client.ZooKeeperSaslClient;
67  import org.apache.zookeeper.data.ACL;
68  import org.apache.zookeeper.data.Stat;
69  import org.apache.zookeeper.proto.CreateRequest;
70  import org.apache.zookeeper.proto.DeleteRequest;
71  import org.apache.zookeeper.proto.SetDataRequest;
72  import org.apache.zookeeper.server.ZooKeeperSaslServer;
73  
74  import com.google.protobuf.InvalidProtocolBufferException;
75  
76  /**
77   * Internal HBase utility class for ZooKeeper.
78   *
79   * <p>Contains only static methods and constants.
80   *
81   * <p>Methods all throw {@link KeeperException} if there is an unexpected
82   * zookeeper exception, so callers of these methods must handle appropriately.
83   * If ZK is required for the operation, the server will need to be aborted.
84   */
85  @InterfaceAudience.Private
86  public class ZKUtil {
87    private static final Log LOG = LogFactory.getLog(ZKUtil.class);
88  
89    // TODO: Replace this with ZooKeeper constant when ZOOKEEPER-277 is resolved.
90    public static final char ZNODE_PATH_SEPARATOR = '/';
91    private static int zkDumpConnectionTimeOut;
92  
93    /**
94     * Creates a new connection to ZooKeeper, pulling settings and ensemble config
95     * from the specified configuration object using methods from {@link ZKConfig}.
96     *
97     * Sets the connection status monitoring watcher to the specified watcher.
98     *
99     * @param conf configuration to pull ensemble and other settings from
100    * @param watcher watcher to monitor connection changes
101    * @return connection to zookeeper
102    * @throws IOException if unable to connect to zk or config problem
103    */
104   public static RecoverableZooKeeper connect(Configuration conf, Watcher watcher)
105   throws IOException {
106     Properties properties = ZKConfig.makeZKProps(conf);
107     String ensemble = ZKConfig.getZKQuorumServersString(properties);
108     return connect(conf, ensemble, watcher);
109   }
110 
111   public static RecoverableZooKeeper connect(Configuration conf, String ensemble,
112       Watcher watcher)
113   throws IOException {
114     return connect(conf, ensemble, watcher, null);
115   }
116 
117   public static RecoverableZooKeeper connect(Configuration conf, String ensemble,
118       Watcher watcher, final String identifier)
119   throws IOException {
120     if(ensemble == null) {
121       throw new IOException("Unable to determine ZooKeeper ensemble");
122     }
123     int timeout = conf.getInt(HConstants.ZK_SESSION_TIMEOUT,
124         HConstants.DEFAULT_ZK_SESSION_TIMEOUT);
125     if (LOG.isTraceEnabled()) {
126       LOG.trace(identifier + " opening connection to ZooKeeper ensemble=" + ensemble);
127     }
128     int retry = conf.getInt("zookeeper.recovery.retry", 3);
129     int retryIntervalMillis =
130       conf.getInt("zookeeper.recovery.retry.intervalmill", 1000);
131     zkDumpConnectionTimeOut = conf.getInt("zookeeper.dump.connection.timeout",
132         1000);
133     return new RecoverableZooKeeper(ensemble, timeout, watcher,
134         retry, retryIntervalMillis, identifier);
135   }
136 
137   /**
138    * Log in the current zookeeper server process using the given configuration
139    * keys for the credential file and login principal.
140    *
141    * <p><strong>This is only applicable when running on secure hbase</strong>
142    * On regular HBase (without security features), this will safely be ignored.
143    * </p>
144    *
145    * @param conf The configuration data to use
146    * @param keytabFileKey Property key used to configure the path to the credential file
147    * @param userNameKey Property key used to configure the login principal
148    * @param hostname Current hostname to use in any credentials
149    * @throws IOException underlying exception from SecurityUtil.login() call
150    */
151   public static void loginServer(Configuration conf, String keytabFileKey,
152       String userNameKey, String hostname) throws IOException {
153     login(conf, keytabFileKey, userNameKey, hostname,
154           ZooKeeperSaslServer.LOGIN_CONTEXT_NAME_KEY,
155           JaasConfiguration.SERVER_KEYTAB_KERBEROS_CONFIG_NAME);
156   }
157 
158   /**
159    * Log in the current zookeeper client using the given configuration
160    * keys for the credential file and login principal.
161    *
162    * <p><strong>This is only applicable when running on secure hbase</strong>
163    * On regular HBase (without security features), this will safely be ignored.
164    * </p>
165    *
166    * @param conf The configuration data to use
167    * @param keytabFileKey Property key used to configure the path to the credential file
168    * @param userNameKey Property key used to configure the login principal
169    * @param hostname Current hostname to use in any credentials
170    * @throws IOException underlying exception from SecurityUtil.login() call
171    */
172   public static void loginClient(Configuration conf, String keytabFileKey,
173       String userNameKey, String hostname) throws IOException {
174     login(conf, keytabFileKey, userNameKey, hostname,
175           ZooKeeperSaslClient.LOGIN_CONTEXT_NAME_KEY,
176           JaasConfiguration.CLIENT_KEYTAB_KERBEROS_CONFIG_NAME);
177   }
178 
179   /**
180    * Log in the current process using the given configuration keys for the
181    * credential file and login principal.
182    *
183    * <p><strong>This is only applicable when running on secure hbase</strong>
184    * On regular HBase (without security features), this will safely be ignored.
185    * </p>
186    *
187    * @param conf The configuration data to use
188    * @param keytabFileKey Property key used to configure the path to the credential file
189    * @param userNameKey Property key used to configure the login principal
190    * @param hostname Current hostname to use in any credentials
191    * @param loginContextProperty property name to expose the entry name
192    * @param loginContextName jaas entry name
193    * @throws IOException underlying exception from SecurityUtil.login() call
194    */
195   private static void login(Configuration conf, String keytabFileKey,
196       String userNameKey, String hostname,
197       String loginContextProperty, String loginContextName)
198       throws IOException {
199     if (!isSecureZooKeeper(conf))
200       return;
201 
202     // User has specified a jaas.conf, keep this one as the good one.
203     // HBASE_OPTS="-Djava.security.auth.login.config=jaas.conf"
204     if (System.getProperty("java.security.auth.login.config") != null)
205       return;
206 
207     // No keytab specified, no auth
208     String keytabFilename = conf.get(keytabFileKey);
209     if (keytabFilename == null) {
210       LOG.warn("no keytab specified for: " + keytabFileKey);
211       return;
212     }
213 
214     String principalConfig = conf.get(userNameKey, System.getProperty("user.name"));
215     String principalName = SecurityUtil.getServerPrincipal(principalConfig, hostname);
216 
217     // Initialize the "jaas.conf" for keyTab/principal,
218     // If keyTab is not specified use the Ticket Cache.
219     // and set the zookeeper login context name.
220     JaasConfiguration jaasConf = new JaasConfiguration(loginContextName,
221         principalName, keytabFilename);
222     javax.security.auth.login.Configuration.setConfiguration(jaasConf);
223     System.setProperty(loginContextProperty, loginContextName);
224   }
225 
226   /**
227    * A JAAS configuration that defines the login modules that we want to use for login.
228    */
229   private static class JaasConfiguration extends javax.security.auth.login.Configuration {
230     private static final String SERVER_KEYTAB_KERBEROS_CONFIG_NAME =
231       "zookeeper-server-keytab-kerberos";
232     private static final String CLIENT_KEYTAB_KERBEROS_CONFIG_NAME =
233       "zookeeper-client-keytab-kerberos";
234 
235     private static final Map<String, String> BASIC_JAAS_OPTIONS =
236       new HashMap<String,String>();
237     static {
238       String jaasEnvVar = System.getenv("HBASE_JAAS_DEBUG");
239       if (jaasEnvVar != null && "true".equalsIgnoreCase(jaasEnvVar)) {
240         BASIC_JAAS_OPTIONS.put("debug", "true");
241       }
242     }
243 
244     private static final Map<String,String> KEYTAB_KERBEROS_OPTIONS =
245       new HashMap<String,String>();
246     static {
247       KEYTAB_KERBEROS_OPTIONS.put("doNotPrompt", "true");
248       KEYTAB_KERBEROS_OPTIONS.put("storeKey", "true");
249       KEYTAB_KERBEROS_OPTIONS.put("refreshKrb5Config", "true");
250       KEYTAB_KERBEROS_OPTIONS.putAll(BASIC_JAAS_OPTIONS);
251     }
252 
253     private static final AppConfigurationEntry KEYTAB_KERBEROS_LOGIN =
254       new AppConfigurationEntry(KerberosUtil.getKrb5LoginModuleName(),
255                                 LoginModuleControlFlag.REQUIRED,
256                                 KEYTAB_KERBEROS_OPTIONS);
257 
258     private static final AppConfigurationEntry[] KEYTAB_KERBEROS_CONF =
259       new AppConfigurationEntry[]{KEYTAB_KERBEROS_LOGIN};
260 
261     private javax.security.auth.login.Configuration baseConfig;
262     private final String loginContextName;
263     private final boolean useTicketCache;
264     private final String keytabFile;
265     private final String principal;
266 
267     public JaasConfiguration(String loginContextName, String principal) {
268       this(loginContextName, principal, null, true);
269     }
270 
271     public JaasConfiguration(String loginContextName, String principal, String keytabFile) {
272       this(loginContextName, principal, keytabFile, keytabFile == null || keytabFile.length() == 0);
273     }
274 
275     private JaasConfiguration(String loginContextName, String principal,
276                              String keytabFile, boolean useTicketCache) {
277       try {
278         this.baseConfig = javax.security.auth.login.Configuration.getConfiguration();
279       } catch (SecurityException e) {
280         this.baseConfig = null;
281       }
282       this.loginContextName = loginContextName;
283       this.useTicketCache = useTicketCache;
284       this.keytabFile = keytabFile;
285       this.principal = principal;
286       LOG.info("JaasConfiguration loginContextName=" + loginContextName +
287                " principal=" + principal + " useTicketCache=" + useTicketCache +
288                " keytabFile=" + keytabFile);
289     }
290 
291     @Override
292     public AppConfigurationEntry[] getAppConfigurationEntry(String appName) {
293       if (loginContextName.equals(appName)) {
294         if (!useTicketCache) {
295           KEYTAB_KERBEROS_OPTIONS.put("keyTab", keytabFile);
296           KEYTAB_KERBEROS_OPTIONS.put("useKeyTab", "true");
297         }
298         KEYTAB_KERBEROS_OPTIONS.put("principal", principal);
299         KEYTAB_KERBEROS_OPTIONS.put("useTicketCache", useTicketCache ? "true" : "false");
300         return KEYTAB_KERBEROS_CONF;
301       }
302       if (baseConfig != null) return baseConfig.getAppConfigurationEntry(appName);
303       return(null);
304     }
305   }
306 
307   //
308   // Helper methods
309   //
310 
311   /**
312    * Join the prefix znode name with the suffix znode name to generate a proper
313    * full znode name.
314    *
315    * Assumes prefix does not end with slash and suffix does not begin with it.
316    *
317    * @param prefix beginning of znode name
318    * @param suffix ending of znode name
319    * @return result of properly joining prefix with suffix
320    */
321   public static String joinZNode(String prefix, String suffix) {
322     return prefix + ZNODE_PATH_SEPARATOR + suffix;
323   }
324 
325   /**
326    * Returns the full path of the immediate parent of the specified node.
327    * @param node path to get parent of
328    * @return parent of path, null if passed the root node or an invalid node
329    */
330   public static String getParent(String node) {
331     int idx = node.lastIndexOf(ZNODE_PATH_SEPARATOR);
332     return idx <= 0 ? null : node.substring(0, idx);
333   }
334 
335   /**
336    * Get the name of the current node from the specified fully-qualified path.
337    * @param path fully-qualified path
338    * @return name of the current node
339    */
340   public static String getNodeName(String path) {
341     return path.substring(path.lastIndexOf("/")+1);
342   }
343 
344   /**
345    * Get the key to the ZK ensemble for this configuration without
346    * adding a name at the end
347    * @param conf Configuration to use to build the key
348    * @return ensemble key without a name
349    */
350   public static String getZooKeeperClusterKey(Configuration conf) {
351     return getZooKeeperClusterKey(conf, null);
352   }
353 
354   /**
355    * Get the key to the ZK ensemble for this configuration and append
356    * a name at the end
357    * @param conf Configuration to use to build the key
358    * @param name Name that should be appended at the end if not empty or null
359    * @return ensemble key with a name (if any)
360    */
361   public static String getZooKeeperClusterKey(Configuration conf, String name) {
362     String ensemble = conf.get(HConstants.ZOOKEEPER_QUORUM.replaceAll(
363         "[\\t\\n\\x0B\\f\\r]", ""));
364     StringBuilder builder = new StringBuilder(ensemble);
365     builder.append(":");
366     builder.append(conf.get(HConstants.ZOOKEEPER_CLIENT_PORT));
367     builder.append(":");
368     builder.append(conf.get(HConstants.ZOOKEEPER_ZNODE_PARENT));
369     if (name != null && !name.isEmpty()) {
370       builder.append(",");
371       builder.append(name);
372     }
373     return builder.toString();
374   }
375 
376   /**
377    * Apply the settings in the given key to the given configuration, this is
378    * used to communicate with distant clusters
379    * @param conf configuration object to configure
380    * @param key string that contains the 3 required configuratins
381    * @throws IOException
382    */
383   public static void applyClusterKeyToConf(Configuration conf, String key)
384       throws IOException{
385     String[] parts = transformClusterKey(key);
386     conf.set(HConstants.ZOOKEEPER_QUORUM, parts[0]);
387     conf.set(HConstants.ZOOKEEPER_CLIENT_PORT, parts[1]);
388     conf.set(HConstants.ZOOKEEPER_ZNODE_PARENT, parts[2]);
389   }
390 
391   /**
392    * Separate the given key into the three configurations it should contain:
393    * hbase.zookeeper.quorum, hbase.zookeeper.client.port
394    * and zookeeper.znode.parent
395    * @param key
396    * @return the three configuration in the described order
397    * @throws IOException
398    */
399   public static String[] transformClusterKey(String key) throws IOException {
400     String[] parts = key.split(":");
401     if (parts.length != 3) {
402       throw new IOException("Cluster key passed " + key + " is invalid, the format should be:" +
403           HConstants.ZOOKEEPER_QUORUM + ":hbase.zookeeper.client.port:"
404           + HConstants.ZOOKEEPER_ZNODE_PARENT);
405     }
406     return parts;
407   }
408 
409   //
410   // Existence checks and watches
411   //
412 
413   /**
414    * Watch the specified znode for delete/create/change events.  The watcher is
415    * set whether or not the node exists.  If the node already exists, the method
416    * returns true.  If the node does not exist, the method returns false.
417    *
418    * @param zkw zk reference
419    * @param znode path of node to watch
420    * @return true if znode exists, false if does not exist or error
421    * @throws KeeperException if unexpected zookeeper exception
422    */
423   public static boolean watchAndCheckExists(ZooKeeperWatcher zkw, String znode)
424   throws KeeperException {
425     try {
426       Stat s = zkw.getRecoverableZooKeeper().exists(znode, zkw);
427       boolean exists = s != null ? true : false;
428       if (exists) {
429         LOG.debug(zkw.prefix("Set watcher on existing znode=" + znode));
430       } else {
431         LOG.debug(zkw.prefix("Set watcher on znode that does not yet exist, " + znode));
432       }
433       return exists;
434     } catch (KeeperException e) {
435       LOG.warn(zkw.prefix("Unable to set watcher on znode " + znode), e);
436       zkw.keeperException(e);
437       return false;
438     } catch (InterruptedException e) {
439       LOG.warn(zkw.prefix("Unable to set watcher on znode " + znode), e);
440       zkw.interruptedException(e);
441       return false;
442     }
443   }
444 
445   /**
446    * Watch the specified znode, but only if exists. Useful when watching
447    * for deletions. Uses .getData() (and handles NoNodeException) instead
448    * of .exists() to accomplish this, as .getData() will only set a watch if
449    * the znode exists.
450    * @param zkw zk reference
451    * @param znode path of node to watch
452    * @return true if the watch is set, false if node does not exists
453    * @throws KeeperException if unexpected zookeeper exception
454    */
455   public static boolean setWatchIfNodeExists(ZooKeeperWatcher zkw, String znode)
456       throws KeeperException {
457     try {
458       zkw.getRecoverableZooKeeper().getData(znode, true, null);
459       return true;
460     } catch (NoNodeException e) {
461       return false;
462     } catch (InterruptedException e) {
463       LOG.warn(zkw.prefix("Unable to set watcher on znode " + znode), e);
464       zkw.interruptedException(e);
465       return false;
466     }
467   }
468 
469   /**
470    * Check if the specified node exists.  Sets no watches.
471    *
472    * @param zkw zk reference
473    * @param znode path of node to watch
474    * @return version of the node if it exists, -1 if does not exist
475    * @throws KeeperException if unexpected zookeeper exception
476    */
477   public static int checkExists(ZooKeeperWatcher zkw, String znode)
478   throws KeeperException {
479     try {
480       Stat s = zkw.getRecoverableZooKeeper().exists(znode, null);
481       return s != null ? s.getVersion() : -1;
482     } catch (KeeperException e) {
483       LOG.warn(zkw.prefix("Unable to set watcher on znode (" + znode + ")"), e);
484       zkw.keeperException(e);
485       return -1;
486     } catch (InterruptedException e) {
487       LOG.warn(zkw.prefix("Unable to set watcher on znode (" + znode + ")"), e);
488       zkw.interruptedException(e);
489       return -1;
490     }
491   }
492 
493   //
494   // Znode listings
495   //
496 
497   /**
498    * Lists the children znodes of the specified znode.  Also sets a watch on
499    * the specified znode which will capture a NodeDeleted event on the specified
500    * znode as well as NodeChildrenChanged if any children of the specified znode
501    * are created or deleted.
502    *
503    * Returns null if the specified node does not exist.  Otherwise returns a
504    * list of children of the specified node.  If the node exists but it has no
505    * children, an empty list will be returned.
506    *
507    * @param zkw zk reference
508    * @param znode path of node to list and watch children of
509    * @return list of children of the specified node, an empty list if the node
510    *          exists but has no children, and null if the node does not exist
511    * @throws KeeperException if unexpected zookeeper exception
512    */
513   public static List<String> listChildrenAndWatchForNewChildren(
514       ZooKeeperWatcher zkw, String znode)
515   throws KeeperException {
516     try {
517       List<String> children = zkw.getRecoverableZooKeeper().getChildren(znode, zkw);
518       return children;
519     } catch(KeeperException.NoNodeException ke) {
520       LOG.debug(zkw.prefix("Unable to list children of znode " + znode + " " +
521           "because node does not exist (not an error)"));
522       return null;
523     } catch (KeeperException e) {
524       LOG.warn(zkw.prefix("Unable to list children of znode " + znode + " "), e);
525       zkw.keeperException(e);
526       return null;
527     } catch (InterruptedException e) {
528       LOG.warn(zkw.prefix("Unable to list children of znode " + znode + " "), e);
529       zkw.interruptedException(e);
530       return null;
531     }
532   }
533 
534   /**
535    * List all the children of the specified znode, setting a watch for children
536    * changes and also setting a watch on every individual child in order to get
537    * the NodeCreated and NodeDeleted events.
538    * @param zkw zookeeper reference
539    * @param znode node to get children of and watch
540    * @return list of znode names, null if the node doesn't exist
541    * @throws KeeperException
542    */
543   public static List<String> listChildrenAndWatchThem(ZooKeeperWatcher zkw,
544       String znode) throws KeeperException {
545     List<String> children = listChildrenAndWatchForNewChildren(zkw, znode);
546     if (children == null) {
547       return null;
548     }
549     for (String child : children) {
550       watchAndCheckExists(zkw, joinZNode(znode, child));
551     }
552     return children;
553   }
554 
555   /**
556    * Lists the children of the specified znode without setting any watches.
557    *
558    * Sets no watches at all, this method is best effort.
559    *
560    * Returns an empty list if the node has no children.  Returns null if the
561    * parent node itself does not exist.
562    *
563    * @param zkw zookeeper reference
564    * @param znode node to get children
565    * @return list of data of children of specified znode, empty if no children,
566    *         null if parent does not exist
567    * @throws KeeperException if unexpected zookeeper exception
568    */
569   public static List<String> listChildrenNoWatch(ZooKeeperWatcher zkw, String znode)
570   throws KeeperException {
571     List<String> children = null;
572     try {
573       // List the children without watching
574       children = zkw.getRecoverableZooKeeper().getChildren(znode, null);
575     } catch(KeeperException.NoNodeException nne) {
576       return null;
577     } catch(InterruptedException ie) {
578       zkw.interruptedException(ie);
579     }
580     return children;
581   }
582 
583   /**
584    * Simple class to hold a node path and node data.
585    * @deprecated Unused
586    */
587   @Deprecated
588   public static class NodeAndData {
589     private String node;
590     private byte [] data;
591     public NodeAndData(String node, byte [] data) {
592       this.node = node;
593       this.data = data;
594     }
595     public String getNode() {
596       return node;
597     }
598     public byte [] getData() {
599       return data;
600     }
601     @Override
602     public String toString() {
603       return node;
604     }
605     public boolean isEmpty() {
606       return (data.length == 0);
607     }
608   }
609 
610   /**
611    * Checks if the specified znode has any children.  Sets no watches.
612    *
613    * Returns true if the node exists and has children.  Returns false if the
614    * node does not exist or if the node does not have any children.
615    *
616    * Used during master initialization to determine if the master is a
617    * failed-over-to master or the first master during initial cluster startup.
618    * If the directory for regionserver ephemeral nodes is empty then this is
619    * a cluster startup, if not then it is not cluster startup.
620    *
621    * @param zkw zk reference
622    * @param znode path of node to check for children of
623    * @return true if node has children, false if not or node does not exist
624    * @throws KeeperException if unexpected zookeeper exception
625    */
626   public static boolean nodeHasChildren(ZooKeeperWatcher zkw, String znode)
627   throws KeeperException {
628     try {
629       return !zkw.getRecoverableZooKeeper().getChildren(znode, null).isEmpty();
630     } catch(KeeperException.NoNodeException ke) {
631       LOG.debug(zkw.prefix("Unable to list children of znode " + znode + " " +
632       "because node does not exist (not an error)"));
633       return false;
634     } catch (KeeperException e) {
635       LOG.warn(zkw.prefix("Unable to list children of znode " + znode), e);
636       zkw.keeperException(e);
637       return false;
638     } catch (InterruptedException e) {
639       LOG.warn(zkw.prefix("Unable to list children of znode " + znode), e);
640       zkw.interruptedException(e);
641       return false;
642     }
643   }
644 
645   /**
646    * Get the number of children of the specified node.
647    *
648    * If the node does not exist or has no children, returns 0.
649    *
650    * Sets no watches at all.
651    *
652    * @param zkw zk reference
653    * @param znode path of node to count children of
654    * @return number of children of specified node, 0 if none or parent does not
655    *         exist
656    * @throws KeeperException if unexpected zookeeper exception
657    */
658   public static int getNumberOfChildren(ZooKeeperWatcher zkw, String znode)
659   throws KeeperException {
660     try {
661       Stat stat = zkw.getRecoverableZooKeeper().exists(znode, null);
662       return stat == null ? 0 : stat.getNumChildren();
663     } catch(KeeperException e) {
664       LOG.warn(zkw.prefix("Unable to get children of node " + znode));
665       zkw.keeperException(e);
666     } catch(InterruptedException e) {
667       zkw.interruptedException(e);
668     }
669     return 0;
670   }
671 
672   //
673   // Data retrieval
674   //
675 
676   /**
677    * Get znode data. Does not set a watcher.
678    * @return ZNode data, null if the node does not exist or if there is an
679    *  error.
680    */
681   public static byte [] getData(ZooKeeperWatcher zkw, String znode)
682       throws KeeperException, InterruptedException {
683     try {
684       byte [] data = zkw.getRecoverableZooKeeper().getData(znode, null, null);
685       logRetrievedMsg(zkw, znode, data, false);
686       return data;
687     } catch (KeeperException.NoNodeException e) {
688       LOG.debug(zkw.prefix("Unable to get data of znode " + znode + " " +
689           "because node does not exist (not an error)"));
690       return null;
691     } catch (KeeperException e) {
692       LOG.warn(zkw.prefix("Unable to get data of znode " + znode), e);
693       zkw.keeperException(e);
694       return null;
695     }
696   }
697 
698   /**
699    * Get the data at the specified znode and set a watch.
700    *
701    * Returns the data and sets a watch if the node exists.  Returns null and no
702    * watch is set if the node does not exist or there is an exception.
703    *
704    * @param zkw zk reference
705    * @param znode path of node
706    * @return data of the specified znode, or null
707    * @throws KeeperException if unexpected zookeeper exception
708    */
709   public static byte [] getDataAndWatch(ZooKeeperWatcher zkw, String znode)
710   throws KeeperException {
711     return getDataInternal(zkw, znode, null, true);
712   }
713 
714   /**
715    * Get the data at the specified znode and set a watch.
716    *
717    * Returns the data and sets a watch if the node exists.  Returns null and no
718    * watch is set if the node does not exist or there is an exception.
719    *
720    * @param zkw zk reference
721    * @param znode path of node
722    * @param stat object to populate the version of the znode
723    * @return data of the specified znode, or null
724    * @throws KeeperException if unexpected zookeeper exception
725    */
726   public static byte[] getDataAndWatch(ZooKeeperWatcher zkw, String znode,
727       Stat stat) throws KeeperException {
728     return getDataInternal(zkw, znode, stat, true);
729   }
730 
731   private static byte[] getDataInternal(ZooKeeperWatcher zkw, String znode, Stat stat,
732       boolean watcherSet)
733       throws KeeperException {
734     try {
735       byte [] data = zkw.getRecoverableZooKeeper().getData(znode, zkw, stat);
736       logRetrievedMsg(zkw, znode, data, watcherSet);
737       return data;
738     } catch (KeeperException.NoNodeException e) {
739       // This log can get pretty annoying when we cycle on 100ms waits.
740       // Enable trace if you really want to see it.
741       LOG.trace(zkw.prefix("Unable to get data of znode " + znode + " " +
742         "because node does not exist (not an error)"));
743       return null;
744     } catch (KeeperException e) {
745       LOG.warn(zkw.prefix("Unable to get data of znode " + znode), e);
746       zkw.keeperException(e);
747       return null;
748     } catch (InterruptedException e) {
749       LOG.warn(zkw.prefix("Unable to get data of znode " + znode), e);
750       zkw.interruptedException(e);
751       return null;
752     }
753   }
754 
755   /**
756    * Get the data at the specified znode without setting a watch.
757    *
758    * Returns the data if the node exists.  Returns null if the node does not
759    * exist.
760    *
761    * Sets the stats of the node in the passed Stat object.  Pass a null stat if
762    * not interested.
763    *
764    * @param zkw zk reference
765    * @param znode path of node
766    * @param stat node status to get if node exists
767    * @return data of the specified znode, or null if node does not exist
768    * @throws KeeperException if unexpected zookeeper exception
769    */
770   public static byte [] getDataNoWatch(ZooKeeperWatcher zkw, String znode,
771       Stat stat)
772   throws KeeperException {
773     try {
774       byte [] data = zkw.getRecoverableZooKeeper().getData(znode, null, stat);
775       logRetrievedMsg(zkw, znode, data, false);
776       return data;
777     } catch (KeeperException.NoNodeException e) {
778       LOG.debug(zkw.prefix("Unable to get data of znode " + znode + " " +
779           "because node does not exist (not necessarily an error)"));
780       return null;
781     } catch (KeeperException e) {
782       LOG.warn(zkw.prefix("Unable to get data of znode " + znode), e);
783       zkw.keeperException(e);
784       return null;
785     } catch (InterruptedException e) {
786       LOG.warn(zkw.prefix("Unable to get data of znode " + znode), e);
787       zkw.interruptedException(e);
788       return null;
789     }
790   }
791 
792   /**
793    * Returns the date of child znodes of the specified znode.  Also sets a watch on
794    * the specified znode which will capture a NodeDeleted event on the specified
795    * znode as well as NodeChildrenChanged if any children of the specified znode
796    * are created or deleted.
797    *
798    * Returns null if the specified node does not exist.  Otherwise returns a
799    * list of children of the specified node.  If the node exists but it has no
800    * children, an empty list will be returned.
801    *
802    * @param zkw zk reference
803    * @param baseNode path of node to list and watch children of
804    * @return list of data of children of the specified node, an empty list if the node
805    *          exists but has no children, and null if the node does not exist
806    * @throws KeeperException if unexpected zookeeper exception
807    * @deprecated Unused
808    */
809   public static List<NodeAndData> getChildDataAndWatchForNewChildren(
810       ZooKeeperWatcher zkw, String baseNode) throws KeeperException {
811     List<String> nodes =
812       ZKUtil.listChildrenAndWatchForNewChildren(zkw, baseNode);
813     if (nodes != null) {
814       List<NodeAndData> newNodes = new ArrayList<NodeAndData>();
815       for (String node : nodes) {
816         String nodePath = ZKUtil.joinZNode(baseNode, node);
817         byte[] data = ZKUtil.getDataAndWatch(zkw, nodePath);
818         newNodes.add(new NodeAndData(nodePath, data));
819       }
820       return newNodes;
821     }
822     return null;
823   }
824 
825   /**
826    * Update the data of an existing node with the expected version to have the
827    * specified data.
828    *
829    * Throws an exception if there is a version mismatch or some other problem.
830    *
831    * Sets no watches under any conditions.
832    *
833    * @param zkw zk reference
834    * @param znode
835    * @param data
836    * @param expectedVersion
837    * @throws KeeperException if unexpected zookeeper exception
838    * @throws KeeperException.BadVersionException if version mismatch
839    * @deprecated Unused
840    */
841   public static void updateExistingNodeData(ZooKeeperWatcher zkw, String znode,
842       byte [] data, int expectedVersion)
843   throws KeeperException {
844     try {
845       zkw.getRecoverableZooKeeper().setData(znode, data, expectedVersion);
846     } catch(InterruptedException ie) {
847       zkw.interruptedException(ie);
848     }
849   }
850 
851   //
852   // Data setting
853   //
854 
855   /**
856    * Sets the data of the existing znode to be the specified data.  Ensures that
857    * the current data has the specified expected version.
858    *
859    * <p>If the node does not exist, a {@link NoNodeException} will be thrown.
860    *
861    * <p>If their is a version mismatch, method returns null.
862    *
863    * <p>No watches are set but setting data will trigger other watchers of this
864    * node.
865    *
866    * <p>If there is another problem, a KeeperException will be thrown.
867    *
868    * @param zkw zk reference
869    * @param znode path of node
870    * @param data data to set for node
871    * @param expectedVersion version expected when setting data
872    * @return true if data set, false if version mismatch
873    * @throws KeeperException if unexpected zookeeper exception
874    */
875   public static boolean setData(ZooKeeperWatcher zkw, String znode,
876       byte [] data, int expectedVersion)
877   throws KeeperException, KeeperException.NoNodeException {
878     try {
879       return zkw.getRecoverableZooKeeper().setData(znode, data, expectedVersion) != null;
880     } catch (InterruptedException e) {
881       zkw.interruptedException(e);
882       return false;
883     }
884   }
885 
886   /**
887    * Set data into node creating node if it doesn't yet exist.
888    * Does not set watch.
889    *
890    * @param zkw zk reference
891    * @param znode path of node
892    * @param data data to set for node
893    * @throws KeeperException
894    */
895   public static void createSetData(final ZooKeeperWatcher zkw, final String znode,
896       final byte [] data)
897   throws KeeperException {
898     if (checkExists(zkw, znode) == -1) {
899       ZKUtil.createWithParents(zkw, znode, data);
900     } else {
901       ZKUtil.setData(zkw, znode, data);
902     }
903   }
904 
905   /**
906    * Sets the data of the existing znode to be the specified data.  The node
907    * must exist but no checks are done on the existing data or version.
908    *
909    * <p>If the node does not exist, a {@link NoNodeException} will be thrown.
910    *
911    * <p>No watches are set but setting data will trigger other watchers of this
912    * node.
913    *
914    * <p>If there is another problem, a KeeperException will be thrown.
915    *
916    * @param zkw zk reference
917    * @param znode path of node
918    * @param data data to set for node
919    * @throws KeeperException if unexpected zookeeper exception
920    */
921   public static void setData(ZooKeeperWatcher zkw, String znode, byte [] data)
922   throws KeeperException, KeeperException.NoNodeException {
923     setData(zkw, (SetData)ZKUtilOp.setData(znode, data));
924   }
925 
926   private static void setData(ZooKeeperWatcher zkw, SetData setData)
927   throws KeeperException, KeeperException.NoNodeException {
928     SetDataRequest sd = (SetDataRequest)toZooKeeperOp(zkw, setData).toRequestRecord();
929     setData(zkw, sd.getPath(), sd.getData(), sd.getVersion());
930   }
931 
932   /**
933    * Returns whether or not secure authentication is enabled
934    * (whether <code>hbase.security.authentication</code> is set to
935    * <code>kerberos</code>.
936    */
937   public static boolean isSecureZooKeeper(Configuration conf) {
938     // Detection for embedded HBase client with jaas configuration
939     // defined for third party programs.
940     try {
941       javax.security.auth.login.Configuration testConfig = javax.security.auth.login.Configuration.getConfiguration();
942       if(testConfig.getAppConfigurationEntry("Client") == null) {
943         return false;
944       }
945     } catch(Exception e) {
946       // No Jaas configuration defined.
947       return false;
948     }
949 
950     // Master & RSs uses hbase.zookeeper.client.*
951     return("kerberos".equalsIgnoreCase(conf.get("hbase.security.authentication")) &&
952          conf.get("hbase.zookeeper.client.keytab.file") != null);
953   }
954 
955   private static ArrayList<ACL> createACL(ZooKeeperWatcher zkw, String node) {
956     if (isSecureZooKeeper(zkw.getConfiguration())) {
957       // Certain znodes are accessed directly by the client,
958       // so they must be readable by non-authenticated clients
959       if ((node.equals(zkw.baseZNode) == true) ||
960           (node.equals(zkw.metaServerZNode) == true) ||
961           (node.equals(zkw.getMasterAddressZNode()) == true) ||
962           (node.equals(zkw.clusterIdZNode) == true) ||
963           (node.equals(zkw.rsZNode) == true) ||
964           (node.equals(zkw.backupMasterAddressesZNode) == true) ||
965           (node.startsWith(zkw.assignmentZNode) == true) ||
966           (node.startsWith(zkw.tableZNode) == true)) {
967         return ZooKeeperWatcher.CREATOR_ALL_AND_WORLD_READABLE;
968       }
969       return Ids.CREATOR_ALL_ACL;
970     } else {
971       return Ids.OPEN_ACL_UNSAFE;
972     }
973   }
974 
975   //
976   // Node creation
977   //
978 
979   /**
980    *
981    * Set the specified znode to be an ephemeral node carrying the specified
982    * data.
983    *
984    * If the node is created successfully, a watcher is also set on the node.
985    *
986    * If the node is not created successfully because it already exists, this
987    * method will also set a watcher on the node.
988    *
989    * If there is another problem, a KeeperException will be thrown.
990    *
991    * @param zkw zk reference
992    * @param znode path of node
993    * @param data data of node
994    * @return true if node created, false if not, watch set in both cases
995    * @throws KeeperException if unexpected zookeeper exception
996    */
997   public static boolean createEphemeralNodeAndWatch(ZooKeeperWatcher zkw,
998       String znode, byte [] data)
999   throws KeeperException {
1000     boolean ret = true;
1001     try {
1002       zkw.getRecoverableZooKeeper().create(znode, data, createACL(zkw, znode),
1003           CreateMode.EPHEMERAL);
1004     } catch (KeeperException.NodeExistsException nee) {
1005       ret = false;
1006     } catch (InterruptedException e) {
1007       LOG.info("Interrupted", e);
1008       Thread.currentThread().interrupt();
1009     }
1010     if(!watchAndCheckExists(zkw, znode)) {
1011       // It did exist but now it doesn't, try again
1012       return createEphemeralNodeAndWatch(zkw, znode, data);
1013     }
1014     return ret;
1015   }
1016 
1017   /**
1018    * Creates the specified znode to be a persistent node carrying the specified
1019    * data.
1020    *
1021    * Returns true if the node was successfully created, false if the node
1022    * already existed.
1023    *
1024    * If the node is created successfully, a watcher is also set on the node.
1025    *
1026    * If the node is not created successfully because it already exists, this
1027    * method will also set a watcher on the node but return false.
1028    *
1029    * If there is another problem, a KeeperException will be thrown.
1030    *
1031    * @param zkw zk reference
1032    * @param znode path of node
1033    * @param data data of node
1034    * @return true if node created, false if not, watch set in both cases
1035    * @throws KeeperException if unexpected zookeeper exception
1036    */
1037   public static boolean createNodeIfNotExistsAndWatch(
1038       ZooKeeperWatcher zkw, String znode, byte [] data)
1039   throws KeeperException {
1040     boolean ret = true;
1041     try {
1042       zkw.getRecoverableZooKeeper().create(znode, data, createACL(zkw, znode),
1043           CreateMode.PERSISTENT);
1044     } catch (KeeperException.NodeExistsException nee) {
1045       ret = false;
1046     } catch (InterruptedException e) {
1047       zkw.interruptedException(e);
1048       return false;
1049     }
1050     try {
1051       zkw.getRecoverableZooKeeper().exists(znode, zkw);
1052     } catch (InterruptedException e) {
1053       zkw.interruptedException(e);
1054       return false;
1055     }
1056     return ret;
1057   }
1058 
1059   /**
1060    * Creates the specified znode with the specified data but does not watch it.
1061    *
1062    * Returns the znode of the newly created node
1063    *
1064    * If there is another problem, a KeeperException will be thrown.
1065    *
1066    * @param zkw zk reference
1067    * @param znode path of node
1068    * @param data data of node
1069    * @param createMode specifying whether the node to be created is ephemeral and/or sequential
1070    * @return true name of the newly created znode or null
1071    * @throws KeeperException if unexpected zookeeper exception
1072    */
1073   public static String createNodeIfNotExistsNoWatch(ZooKeeperWatcher zkw, String znode,
1074       byte[] data, CreateMode createMode) throws KeeperException {
1075 
1076     String createdZNode = null;
1077     try {
1078       createdZNode = zkw.getRecoverableZooKeeper().create(znode, data,
1079           createACL(zkw, znode), createMode);
1080     } catch (KeeperException.NodeExistsException nee) {
1081       return znode;
1082     } catch (InterruptedException e) {
1083       zkw.interruptedException(e);
1084       return null;
1085     }
1086     return createdZNode;
1087   }
1088 
1089   /**
1090    * Creates the specified node with the specified data and watches it.
1091    *
1092    * <p>Throws an exception if the node already exists.
1093    *
1094    * <p>The node created is persistent and open access.
1095    *
1096    * <p>Returns the version number of the created node if successful.
1097    *
1098    * @param zkw zk reference
1099    * @param znode path of node to create
1100    * @param data data of node to create
1101    * @return version of node created
1102    * @throws KeeperException if unexpected zookeeper exception
1103    * @throws KeeperException.NodeExistsException if node already exists
1104    */
1105   public static int createAndWatch(ZooKeeperWatcher zkw,
1106       String znode, byte [] data)
1107   throws KeeperException, KeeperException.NodeExistsException {
1108     try {
1109       zkw.getRecoverableZooKeeper().create(znode, data, createACL(zkw, znode),
1110           CreateMode.PERSISTENT);
1111       Stat stat = zkw.getRecoverableZooKeeper().exists(znode, zkw);
1112       if (stat == null){
1113         // Likely a race condition. Someone deleted the znode.
1114         throw KeeperException.create(KeeperException.Code.SYSTEMERROR,
1115             "ZK.exists returned null (i.e.: znode does not exist) for znode=" + znode);
1116       }
1117      return stat.getVersion();
1118     } catch (InterruptedException e) {
1119       zkw.interruptedException(e);
1120       return -1;
1121     }
1122   }
1123 
1124   /**
1125    * Async creates the specified node with the specified data.
1126    *
1127    * <p>Throws an exception if the node already exists.
1128    *
1129    * <p>The node created is persistent and open access.
1130    *
1131    * @param zkw zk reference
1132    * @param znode path of node to create
1133    * @param data data of node to create
1134    * @param cb
1135    * @param ctx
1136    * @throws KeeperException if unexpected zookeeper exception
1137    * @throws KeeperException.NodeExistsException if node already exists
1138    */
1139   public static void asyncCreate(ZooKeeperWatcher zkw,
1140       String znode, byte [] data, final AsyncCallback.StringCallback cb,
1141       final Object ctx) {
1142     zkw.getRecoverableZooKeeper().getZooKeeper().create(znode, data,
1143         createACL(zkw, znode), CreateMode.PERSISTENT, cb, ctx);
1144   }
1145 
1146   /**
1147    * Creates the specified node, iff the node does not exist.  Does not set a
1148    * watch and fails silently if the node already exists.
1149    *
1150    * The node created is persistent and open access.
1151    *
1152    * @param zkw zk reference
1153    * @param znode path of node
1154    * @throws KeeperException if unexpected zookeeper exception
1155    */
1156   public static void createAndFailSilent(ZooKeeperWatcher zkw,
1157       String znode) throws KeeperException {
1158     createAndFailSilent(zkw, znode, new byte[0]);
1159   }
1160 
1161   /**
1162    * Creates the specified node containing specified data, iff the node does not exist.  Does
1163    * not set a watch and fails silently if the node already exists.
1164    *
1165    * The node created is persistent and open access.
1166    *
1167    * @param zkw zk reference
1168    * @param znode path of node
1169    * @param data a byte array data to store in the znode
1170    * @throws KeeperException if unexpected zookeeper exception
1171    */
1172   public static void createAndFailSilent(ZooKeeperWatcher zkw,
1173       String znode, byte[] data)
1174   throws KeeperException {
1175     createAndFailSilent(zkw,
1176         (CreateAndFailSilent)ZKUtilOp.createAndFailSilent(znode, data));
1177   }
1178 
1179   private static void createAndFailSilent(ZooKeeperWatcher zkw, CreateAndFailSilent cafs)
1180   throws KeeperException {
1181     CreateRequest create = (CreateRequest)toZooKeeperOp(zkw, cafs).toRequestRecord();
1182     String znode = create.getPath();
1183     try {
1184       RecoverableZooKeeper zk = zkw.getRecoverableZooKeeper();
1185       if (zk.exists(znode, false) == null) {
1186         zk.create(znode, create.getData(), create.getAcl(), CreateMode.fromFlag(create.getFlags()));
1187       }
1188     } catch(KeeperException.NodeExistsException nee) {
1189     } catch(KeeperException.NoAuthException nee){
1190       try {
1191         if (null == zkw.getRecoverableZooKeeper().exists(znode, false)) {
1192           // If we failed to create the file and it does not already exist.
1193           throw(nee);
1194         }
1195       } catch (InterruptedException ie) {
1196         zkw.interruptedException(ie);
1197       }
1198 
1199     } catch(InterruptedException ie) {
1200       zkw.interruptedException(ie);
1201     }
1202   }
1203 
1204   /**
1205    * Creates the specified node and all parent nodes required for it to exist.
1206    *
1207    * No watches are set and no errors are thrown if the node already exists.
1208    *
1209    * The nodes created are persistent and open access.
1210    *
1211    * @param zkw zk reference
1212    * @param znode path of node
1213    * @throws KeeperException if unexpected zookeeper exception
1214    */
1215   public static void createWithParents(ZooKeeperWatcher zkw, String znode)
1216   throws KeeperException {
1217     createWithParents(zkw, znode, new byte[0]);
1218   }
1219 
1220   /**
1221    * Creates the specified node and all parent nodes required for it to exist.  The creation of
1222    * parent znodes is not atomic with the leafe znode creation but the data is written atomically
1223    * when the leaf node is created.
1224    *
1225    * No watches are set and no errors are thrown if the node already exists.
1226    *
1227    * The nodes created are 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 createWithParents(ZooKeeperWatcher zkw, String znode, byte[] data)
1234   throws KeeperException {
1235     try {
1236       if(znode == null) {
1237         return;
1238       }
1239       zkw.getRecoverableZooKeeper().create(znode, data, createACL(zkw, znode),
1240           CreateMode.PERSISTENT);
1241     } catch(KeeperException.NodeExistsException nee) {
1242       return;
1243     } catch(KeeperException.NoNodeException nne) {
1244       createWithParents(zkw, getParent(znode));
1245       createWithParents(zkw, znode, data);
1246     } catch(InterruptedException ie) {
1247       zkw.interruptedException(ie);
1248     }
1249   }
1250 
1251   //
1252   // Deletes
1253   //
1254 
1255   /**
1256    * Delete the specified node.  Sets no watches.  Throws all exceptions.
1257    */
1258   public static void deleteNode(ZooKeeperWatcher zkw, String node)
1259   throws KeeperException {
1260     deleteNode(zkw, node, -1);
1261   }
1262 
1263   /**
1264    * Delete the specified node with the specified version.  Sets no watches.
1265    * Throws all exceptions.
1266    */
1267   public static boolean deleteNode(ZooKeeperWatcher zkw, String node,
1268       int version)
1269   throws KeeperException {
1270     try {
1271       zkw.getRecoverableZooKeeper().delete(node, version);
1272       return true;
1273     } catch(KeeperException.BadVersionException bve) {
1274       return false;
1275     } catch(InterruptedException ie) {
1276       zkw.interruptedException(ie);
1277       return false;
1278     }
1279   }
1280 
1281   /**
1282    * Deletes the specified node.  Fails silent if the node does not exist.
1283    * @param zkw
1284    * @param node
1285    * @throws KeeperException
1286    */
1287   public static void deleteNodeFailSilent(ZooKeeperWatcher zkw, String node)
1288   throws KeeperException {
1289     deleteNodeFailSilent(zkw,
1290       (DeleteNodeFailSilent)ZKUtilOp.deleteNodeFailSilent(node));
1291   }
1292 
1293   private static void deleteNodeFailSilent(ZooKeeperWatcher zkw,
1294       DeleteNodeFailSilent dnfs) throws KeeperException {
1295     DeleteRequest delete = (DeleteRequest)toZooKeeperOp(zkw, dnfs).toRequestRecord();
1296     try {
1297       zkw.getRecoverableZooKeeper().delete(delete.getPath(), delete.getVersion());
1298     } catch(KeeperException.NoNodeException nne) {
1299     } catch(InterruptedException ie) {
1300       zkw.interruptedException(ie);
1301     }
1302   }
1303 
1304 
1305   /**
1306    * Delete the specified node and all of it's children.
1307    * <p>
1308    * If the node does not exist, just returns.
1309    * <p>
1310    * Sets no watches. Throws all exceptions besides dealing with deletion of
1311    * children.
1312    */
1313   public static void deleteNodeRecursively(ZooKeeperWatcher zkw, String node)
1314   throws KeeperException {
1315     try {
1316       List<String> children = ZKUtil.listChildrenNoWatch(zkw, node);
1317       // the node is already deleted, so we just finish
1318       if (children == null) return;
1319 
1320       if(!children.isEmpty()) {
1321         for(String child : children) {
1322           deleteNodeRecursively(zkw, joinZNode(node, child));
1323         }
1324       }
1325       zkw.getRecoverableZooKeeper().delete(node, -1);
1326     } catch(InterruptedException ie) {
1327       zkw.interruptedException(ie);
1328     }
1329   }
1330 
1331   /**
1332    * Delete all the children of the specified node but not the node itself.
1333    *
1334    * Sets no watches.  Throws all exceptions besides dealing with deletion of
1335    * children.
1336    */
1337   public static void deleteChildrenRecursively(ZooKeeperWatcher zkw, String node)
1338   throws KeeperException {
1339     List<String> children = ZKUtil.listChildrenNoWatch(zkw, node);
1340     if (children == null || children.isEmpty()) return;
1341     for(String child : children) {
1342       deleteNodeRecursively(zkw, joinZNode(node, child));
1343     }
1344   }
1345 
1346   /**
1347    * Represents an action taken by ZKUtil, e.g. createAndFailSilent.
1348    * These actions are higher-level than ZKOp actions, which represent
1349    * individual actions in the ZooKeeper API, like create.
1350    */
1351   public abstract static class ZKUtilOp {
1352     private String path;
1353 
1354     private ZKUtilOp(String path) {
1355       this.path = path;
1356     }
1357 
1358     /**
1359      * @return a createAndFailSilent ZKUtilOp
1360      */
1361     public static ZKUtilOp createAndFailSilent(String path, byte[] data) {
1362       return new CreateAndFailSilent(path, data);
1363     }
1364 
1365     /**
1366      * @return a deleteNodeFailSilent ZKUtilOP
1367      */
1368     public static ZKUtilOp deleteNodeFailSilent(String path) {
1369       return new DeleteNodeFailSilent(path);
1370     }
1371 
1372     /**
1373      * @return a setData ZKUtilOp
1374      */
1375     public static ZKUtilOp setData(String path, byte [] data) {
1376       return new SetData(path, data);
1377     }
1378 
1379     /**
1380      * @return path to znode where the ZKOp will occur
1381      */
1382     public String getPath() {
1383       return path;
1384     }
1385 
1386     /**
1387      * ZKUtilOp representing createAndFailSilent in ZooKeeper
1388      * (attempt to create node, ignore error if already exists)
1389      */
1390     public static class CreateAndFailSilent extends ZKUtilOp {
1391       private byte [] data;
1392 
1393       private CreateAndFailSilent(String path, byte [] data) {
1394         super(path);
1395         this.data = data;
1396       }
1397 
1398       public byte[] getData() {
1399         return data;
1400       }
1401 
1402       @Override
1403       public boolean equals(Object o) {
1404         if (this == o) return true;
1405         if (!(o instanceof CreateAndFailSilent)) return false;
1406 
1407         CreateAndFailSilent op = (CreateAndFailSilent) o;
1408         return getPath().equals(op.getPath()) && Arrays.equals(data, op.data);
1409       }
1410 
1411       @Override
1412       public int hashCode() {
1413         int ret = 17 + getPath().hashCode() * 31;
1414         return ret * 31 + Bytes.hashCode(data);
1415       }
1416     }
1417 
1418     /**
1419      * ZKUtilOp representing deleteNodeFailSilent in ZooKeeper
1420      * (attempt to delete node, ignore error if node doesn't exist)
1421      */
1422     public static class DeleteNodeFailSilent extends ZKUtilOp {
1423       private DeleteNodeFailSilent(String path) {
1424         super(path);
1425       }
1426 
1427       @Override
1428       public boolean equals(Object o) {
1429         if (this == o) return true;
1430         if (!(o instanceof DeleteNodeFailSilent)) return false;
1431 
1432         return super.equals(o);
1433       }
1434 
1435       @Override
1436       public int hashCode() {
1437         return getPath().hashCode();
1438       }
1439     }
1440 
1441     /**
1442      * ZKUtilOp representing setData in ZooKeeper
1443      */
1444     public static class SetData extends ZKUtilOp {
1445       private byte [] data;
1446 
1447       private SetData(String path, byte [] data) {
1448         super(path);
1449         this.data = data;
1450       }
1451 
1452       public byte[] getData() {
1453         return data;
1454       }
1455 
1456       @Override
1457       public boolean equals(Object o) {
1458         if (this == o) return true;
1459         if (!(o instanceof SetData)) return false;
1460 
1461         SetData op = (SetData) o;
1462         return getPath().equals(op.getPath()) && Arrays.equals(data, op.data);
1463       }
1464 
1465       @Override
1466       public int hashCode() {
1467         int ret = getPath().hashCode();
1468         return ret * 31 + Bytes.hashCode(data);
1469       }
1470     }
1471   }
1472 
1473   /**
1474    * Convert from ZKUtilOp to ZKOp
1475    */
1476   private static Op toZooKeeperOp(ZooKeeperWatcher zkw, ZKUtilOp op)
1477   throws UnsupportedOperationException {
1478     if(op == null) return null;
1479 
1480     if (op instanceof CreateAndFailSilent) {
1481       CreateAndFailSilent cafs = (CreateAndFailSilent)op;
1482       return Op.create(cafs.getPath(), cafs.getData(), createACL(zkw, cafs.getPath()),
1483         CreateMode.PERSISTENT);
1484     } else if (op instanceof DeleteNodeFailSilent) {
1485       DeleteNodeFailSilent dnfs = (DeleteNodeFailSilent)op;
1486       return Op.delete(dnfs.getPath(), -1);
1487     } else if (op instanceof SetData) {
1488       SetData sd = (SetData)op;
1489       return Op.setData(sd.getPath(), sd.getData(), -1);
1490     } else {
1491       throw new UnsupportedOperationException("Unexpected ZKUtilOp type: "
1492         + op.getClass().getName());
1493     }
1494   }
1495 
1496   /**
1497    * If hbase.zookeeper.useMulti is true, use ZooKeeper's multi-update functionality.
1498    * Otherwise, run the list of operations sequentially.
1499    *
1500    * If all of the following are true:
1501    * - runSequentialOnMultiFailure is true
1502    * - hbase.zookeeper.useMulti is true
1503    * - on calling multi, we get a ZooKeeper exception that can be handled by a sequential call(*)
1504    * Then:
1505    * - we retry the operations one-by-one (sequentially)
1506    *
1507    * Note *: an example is receiving a NodeExistsException from a "create" call.  Without multi,
1508    * a user could call "createAndFailSilent" to ensure that a node exists if they don't care who
1509    * actually created the node (i.e. the NodeExistsException from ZooKeeper is caught).
1510    * This will cause all operations in the multi to fail, however, because
1511    * the NodeExistsException that zk.create throws will fail the multi transaction.
1512    * In this case, if the previous conditions hold, the commands are run sequentially, which should
1513    * result in the correct final state, but means that the operations will not run atomically.
1514    *
1515    * @throws KeeperException
1516    */
1517   public static void multiOrSequential(ZooKeeperWatcher zkw, List<ZKUtilOp> ops,
1518       boolean runSequentialOnMultiFailure) throws KeeperException {
1519     if (ops == null) return;
1520     boolean useMulti = zkw.getConfiguration().getBoolean(HConstants.ZOOKEEPER_USEMULTI, false);
1521 
1522     if (useMulti) {
1523       List<Op> zkOps = new LinkedList<Op>();
1524       for (ZKUtilOp op : ops) {
1525         zkOps.add(toZooKeeperOp(zkw, op));
1526       }
1527       try {
1528         zkw.getRecoverableZooKeeper().multi(zkOps);
1529       } catch (KeeperException ke) {
1530        switch (ke.code()) {
1531          case NODEEXISTS:
1532          case NONODE:
1533          case BADVERSION:
1534          case NOAUTH:
1535            // if we get an exception that could be solved by running sequentially
1536            // (and the client asked us to), then break out and run sequentially
1537            if (runSequentialOnMultiFailure) {
1538              LOG.info("On call to ZK.multi, received exception: " + ke.toString() + "."
1539                + "  Attempting to run operations sequentially because"
1540                + " runSequentialOnMultiFailure is: " + runSequentialOnMultiFailure + ".");
1541              processSequentially(zkw, ops);
1542              break;
1543            }
1544           default:
1545             throw ke;
1546         }
1547       } catch (InterruptedException ie) {
1548         zkw.interruptedException(ie);
1549       }
1550     } else {
1551       // run sequentially
1552       processSequentially(zkw, ops);
1553     }
1554 
1555   }
1556 
1557   private static void processSequentially(ZooKeeperWatcher zkw, List<ZKUtilOp> ops)
1558       throws KeeperException, NoNodeException {
1559     for (ZKUtilOp op : ops) {
1560       if (op instanceof CreateAndFailSilent) {
1561         createAndFailSilent(zkw, (CreateAndFailSilent) op);
1562       } else if (op instanceof DeleteNodeFailSilent) {
1563         deleteNodeFailSilent(zkw, (DeleteNodeFailSilent) op);
1564       } else if (op instanceof SetData) {
1565         setData(zkw, (SetData) op);
1566       } else {
1567         throw new UnsupportedOperationException("Unexpected ZKUtilOp type: "
1568             + op.getClass().getName());
1569       }
1570     }
1571   }
1572 
1573   //
1574   // ZooKeeper cluster information
1575   //
1576 
1577   /** @return String dump of everything in ZooKeeper. */
1578   public static String dump(ZooKeeperWatcher zkw) {
1579     StringBuilder sb = new StringBuilder();
1580     try {
1581       sb.append("HBase is rooted at ").append(zkw.baseZNode);
1582       sb.append("\nActive master address: ");
1583       try {
1584         sb.append(MasterAddressTracker.getMasterAddress(zkw));
1585       } catch (IOException e) {
1586         sb.append("<<FAILED LOOKUP: " + e.getMessage() + ">>");
1587       }
1588       sb.append("\nBackup master addresses:");
1589       for (String child : listChildrenNoWatch(zkw,
1590                                               zkw.backupMasterAddressesZNode)) {
1591         sb.append("\n ").append(child);
1592       }
1593       sb.append("\nRegion server holding hbase:meta: " + MetaRegionTracker.getMetaRegionLocation(zkw));
1594       sb.append("\nRegion servers:");
1595       for (String child : listChildrenNoWatch(zkw, zkw.rsZNode)) {
1596         sb.append("\n ").append(child);
1597       }
1598       try {
1599         getReplicationZnodesDump(zkw, sb);
1600       } catch (KeeperException ke) {
1601         LOG.warn("Couldn't get the replication znode dump", ke);
1602       }
1603       sb.append("\nQuorum Server Statistics:");
1604       String[] servers = zkw.getQuorum().split(",");
1605       for (String server : servers) {
1606         sb.append("\n ").append(server);
1607         try {
1608           String[] stat = getServerStats(server, ZKUtil.zkDumpConnectionTimeOut);
1609 
1610           if (stat == null) {
1611             sb.append("[Error] invalid quorum server: " + server);
1612             break;
1613           }
1614 
1615           for (String s : stat) {
1616             sb.append("\n  ").append(s);
1617           }
1618         } catch (Exception e) {
1619           sb.append("\n  ERROR: ").append(e.getMessage());
1620         }
1621       }
1622     } catch (KeeperException ke) {
1623       sb.append("\nFATAL ZooKeeper Exception!\n");
1624       sb.append("\n" + ke.getMessage());
1625     }
1626     return sb.toString();
1627   }
1628 
1629   /**
1630    * Appends replication znodes to the passed StringBuilder.
1631    * @param zkw
1632    * @param sb
1633    * @throws KeeperException
1634    */
1635   private static void getReplicationZnodesDump(ZooKeeperWatcher zkw, StringBuilder sb)
1636       throws KeeperException {
1637     String replicationZNodeName = zkw.getConfiguration().get("zookeeper.znode.replication",
1638       "replication");
1639     String replicationZnode = joinZNode(zkw.baseZNode, replicationZNodeName);
1640     if (ZKUtil.checkExists(zkw, replicationZnode) == -1) return;
1641     // do a ls -r on this znode
1642     sb.append("\n").append(replicationZnode).append(": ");
1643     List<String> children = ZKUtil.listChildrenNoWatch(zkw, replicationZnode);
1644     for (String child : children) {
1645       String znode = joinZNode(replicationZnode, child);
1646       if (child.equals(zkw.getConfiguration().get("zookeeper.znode.replication.peers", "peers"))) {
1647         appendPeersZnodes(zkw, znode, sb);
1648       } else if (child.equals(zkw.getConfiguration().
1649           get("zookeeper.znode.replication.rs", "rs"))) {
1650         appendRSZnodes(zkw, znode, sb);
1651       }
1652     }
1653   }
1654 
1655   private static void appendRSZnodes(ZooKeeperWatcher zkw, String znode, StringBuilder sb)
1656       throws KeeperException {
1657     List<String> stack = new LinkedList<String>();
1658     stack.add(znode);
1659     do {
1660       String znodeToProcess = stack.remove(stack.size() - 1);
1661       sb.append("\n").append(znodeToProcess).append(": ");
1662       byte[] data;
1663       try {
1664         data = ZKUtil.getData(zkw, znodeToProcess);
1665       } catch (InterruptedException e) {
1666         zkw.interruptedException(e);
1667         return;
1668       }
1669       if (data != null && data.length > 0) { // log position
1670         long position = 0;
1671         try {
1672           position = ZKUtil.parseHLogPositionFrom(ZKUtil.getData(zkw, znodeToProcess));
1673           sb.append(position);
1674         } catch (DeserializationException ignored) {
1675         } catch (InterruptedException e) {
1676           zkw.interruptedException(e);
1677           return;
1678         }
1679       }
1680       for (String zNodeChild : ZKUtil.listChildrenNoWatch(zkw, znodeToProcess)) {
1681         stack.add(ZKUtil.joinZNode(znodeToProcess, zNodeChild));
1682       }
1683     } while (stack.size() > 0);
1684   }
1685 
1686   private static void appendPeersZnodes(ZooKeeperWatcher zkw, String peersZnode,
1687     StringBuilder sb) throws KeeperException {
1688     int pblen = ProtobufUtil.lengthOfPBMagic();
1689     sb.append("\n").append(peersZnode).append(": ");
1690     for (String peerIdZnode : ZKUtil.listChildrenNoWatch(zkw, peersZnode)) {
1691       String znodeToProcess = ZKUtil.joinZNode(peersZnode, peerIdZnode);
1692       byte[] data;
1693       try {
1694         data = ZKUtil.getData(zkw, znodeToProcess);
1695       } catch (InterruptedException e) {
1696         zkw.interruptedException(e);
1697         return;
1698       }
1699       // parse the data of the above peer znode.
1700       try {
1701       String clusterKey = ZooKeeperProtos.ReplicationPeer.newBuilder().
1702         mergeFrom(data, pblen, data.length - pblen).getClusterkey();
1703       sb.append("\n").append(znodeToProcess).append(": ").append(clusterKey);
1704       // add the peer-state.
1705       appendPeerState(zkw, znodeToProcess, sb);
1706       } catch (InvalidProtocolBufferException ipbe) {
1707         LOG.warn("Got Exception while parsing peer: " + znodeToProcess, ipbe);
1708       }
1709     }
1710   }
1711 
1712   private static void appendPeerState(ZooKeeperWatcher zkw, String znodeToProcess,
1713       StringBuilder sb) throws KeeperException, InvalidProtocolBufferException {
1714     String peerState = zkw.getConfiguration().get("zookeeper.znode.replication.peers.state",
1715       "peer-state");
1716     int pblen = ProtobufUtil.lengthOfPBMagic();
1717     for (String child : ZKUtil.listChildrenNoWatch(zkw, znodeToProcess)) {
1718       if (!child.equals(peerState)) continue;
1719       String peerStateZnode = ZKUtil.joinZNode(znodeToProcess, child);
1720       sb.append("\n").append(peerStateZnode).append(": ");
1721       byte[] peerStateData;
1722       try {
1723         peerStateData = ZKUtil.getData(zkw, peerStateZnode);
1724         sb.append(ZooKeeperProtos.ReplicationState.newBuilder()
1725             .mergeFrom(peerStateData, pblen, peerStateData.length - pblen).getState().name());
1726       } catch (InterruptedException e) {
1727         zkw.interruptedException(e);
1728         return;
1729       }
1730     }
1731   }
1732 
1733   /**
1734    * Gets the statistics from the given server.
1735    *
1736    * @param server  The server to get the statistics from.
1737    * @param timeout  The socket timeout to use.
1738    * @return The array of response strings.
1739    * @throws IOException When the socket communication fails.
1740    */
1741   public static String[] getServerStats(String server, int timeout)
1742   throws IOException {
1743     String[] sp = server.split(":");
1744     if (sp == null || sp.length == 0) {
1745       return null;
1746     }
1747 
1748     String host = sp[0];
1749     int port = sp.length > 1 ? Integer.parseInt(sp[1])
1750         : HConstants.DEFAULT_ZOOKEPER_CLIENT_PORT;
1751 
1752     Socket socket = new Socket();
1753     InetSocketAddress sockAddr = new InetSocketAddress(host, port);
1754     socket.connect(sockAddr, timeout);
1755 
1756     socket.setSoTimeout(timeout);
1757     PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
1758     BufferedReader in = new BufferedReader(new InputStreamReader(
1759       socket.getInputStream()));
1760     out.println("stat");
1761     out.flush();
1762     ArrayList<String> res = new ArrayList<String>();
1763     while (true) {
1764       String line = in.readLine();
1765       if (line != null) {
1766         res.add(line);
1767       } else {
1768         break;
1769       }
1770     }
1771     socket.close();
1772     return res.toArray(new String[res.size()]);
1773   }
1774 
1775   private static void logRetrievedMsg(final ZooKeeperWatcher zkw,
1776       final String znode, final byte [] data, final boolean watcherSet) {
1777     if (!LOG.isTraceEnabled()) return;
1778     LOG.trace(zkw.prefix("Retrieved " + ((data == null)? 0: data.length) +
1779       " byte(s) of data from znode " + znode +
1780       (watcherSet? " and set watcher; ": "; data=") +
1781       (data == null? "null": data.length == 0? "empty": (
1782           znode.startsWith(zkw.assignmentZNode)?
1783             ZKAssign.toString(data): // We should not be doing this reaching into another class
1784           znode.startsWith(zkw.metaServerZNode)?
1785             getServerNameOrEmptyString(data):
1786           znode.startsWith(zkw.backupMasterAddressesZNode)?
1787             getServerNameOrEmptyString(data):
1788           StringUtils.abbreviate(Bytes.toStringBinary(data), 32)))));
1789   }
1790 
1791   private static String getServerNameOrEmptyString(final byte [] data) {
1792     try {
1793       return ServerName.parseFrom(data).toString();
1794     } catch (DeserializationException e) {
1795       return "";
1796     }
1797   }
1798 
1799   /**
1800    * Waits for HBase installation's base (parent) znode to become available.
1801    * @throws IOException on ZK errors
1802    */
1803   public static void waitForBaseZNode(Configuration conf) throws IOException {
1804     LOG.info("Waiting until the base znode is available");
1805     String parentZNode = conf.get(HConstants.ZOOKEEPER_ZNODE_PARENT,
1806         HConstants.DEFAULT_ZOOKEEPER_ZNODE_PARENT);
1807     ZooKeeper zk = new ZooKeeper(ZKConfig.getZKQuorumServersString(conf),
1808         conf.getInt(HConstants.ZK_SESSION_TIMEOUT,
1809         HConstants.DEFAULT_ZK_SESSION_TIMEOUT), EmptyWatcher.instance);
1810 
1811     final int maxTimeMs = 10000;
1812     final int maxNumAttempts = maxTimeMs / HConstants.SOCKET_RETRY_WAIT_MS;
1813 
1814     KeeperException keeperEx = null;
1815     try {
1816       try {
1817         for (int attempt = 0; attempt < maxNumAttempts; ++attempt) {
1818           try {
1819             if (zk.exists(parentZNode, false) != null) {
1820               LOG.info("Parent znode exists: " + parentZNode);
1821               keeperEx = null;
1822               break;
1823             }
1824           } catch (KeeperException e) {
1825             keeperEx = e;
1826           }
1827           Threads.sleepWithoutInterrupt(HConstants.SOCKET_RETRY_WAIT_MS);
1828         }
1829       } finally {
1830         zk.close();
1831       }
1832     } catch (InterruptedException ex) {
1833       Thread.currentThread().interrupt();
1834     }
1835 
1836     if (keeperEx != null) {
1837       throw new IOException(keeperEx);
1838     }
1839   }
1840 
1841 
1842   public static byte[] blockUntilAvailable(
1843     final ZooKeeperWatcher zkw, final String znode, final long timeout)
1844     throws InterruptedException {
1845     if (timeout < 0) throw new IllegalArgumentException();
1846     if (zkw == null) throw new IllegalArgumentException();
1847     if (znode == null) throw new IllegalArgumentException();
1848 
1849     byte[] data = null;
1850     boolean finished = false;
1851     final long endTime = System.currentTimeMillis() + timeout;
1852     while (!finished) {
1853       try {
1854         data = ZKUtil.getData(zkw, znode);
1855       } catch(KeeperException e) {
1856         LOG.warn("Unexpected exception handling blockUntilAvailable", e);
1857       }
1858 
1859       if (data == null && (System.currentTimeMillis() +
1860         HConstants.SOCKET_RETRY_WAIT_MS < endTime)) {
1861         Thread.sleep(HConstants.SOCKET_RETRY_WAIT_MS);
1862       } else {
1863         finished = true;
1864       }
1865     }
1866 
1867     return data;
1868   }
1869 
1870 
1871   /**
1872    * Convert a {@link DeserializationException} to a more palatable {@link KeeperException}.
1873    * Used when can't let a {@link DeserializationException} out w/o changing public API.
1874    * @param e Exception to convert
1875    * @return Converted exception
1876    */
1877   public static KeeperException convert(final DeserializationException e) {
1878     KeeperException ke = new KeeperException.DataInconsistencyException();
1879     ke.initCause(e);
1880     return ke;
1881   }
1882 
1883   /**
1884    * Recursively print the current state of ZK (non-transactional)
1885    * @param root name of the root directory in zk to print
1886    * @throws KeeperException
1887    */
1888   public static void logZKTree(ZooKeeperWatcher zkw, String root) {
1889     if (!LOG.isDebugEnabled()) return;
1890     LOG.debug("Current zk system:");
1891     String prefix = "|-";
1892     LOG.debug(prefix + root);
1893     try {
1894       logZKTree(zkw, root, prefix);
1895     } catch (KeeperException e) {
1896       throw new RuntimeException(e);
1897     }
1898   }
1899 
1900   /**
1901    * Helper method to print the current state of the ZK tree.
1902    * @see #logZKTree(ZooKeeperWatcher, String)
1903    * @throws KeeperException if an unexpected exception occurs
1904    */
1905   protected static void logZKTree(ZooKeeperWatcher zkw, String root, String prefix) throws KeeperException {
1906     List<String> children = ZKUtil.listChildrenNoWatch(zkw, root);
1907     if (children == null) return;
1908     for (String child : children) {
1909       LOG.debug(prefix + child);
1910       String node = ZKUtil.joinZNode(root.equals("/") ? "" : root, child);
1911       logZKTree(zkw, node, prefix + "---");
1912     }
1913   }
1914 
1915   /**
1916    * @param position
1917    * @return Serialized protobuf of <code>position</code> with pb magic prefix prepended suitable
1918    *         for use as content of an hlog position in a replication queue.
1919    */
1920   public static byte[] positionToByteArray(final long position) {
1921     byte[] bytes = ZooKeeperProtos.ReplicationHLogPosition.newBuilder().setPosition(position)
1922         .build().toByteArray();
1923     return ProtobufUtil.prependPBMagic(bytes);
1924   }
1925 
1926   /**
1927    * @param bytes - Content of a HLog position znode.
1928    * @return long - The current HLog position.
1929    * @throws DeserializationException
1930    */
1931   public static long parseHLogPositionFrom(final byte[] bytes) throws DeserializationException {
1932     if (bytes == null) {
1933       throw new DeserializationException("Unable to parse null HLog position.");
1934     }
1935     if (ProtobufUtil.isPBMagicPrefix(bytes)) {
1936       int pblen = ProtobufUtil.lengthOfPBMagic();
1937       ZooKeeperProtos.ReplicationHLogPosition.Builder builder =
1938           ZooKeeperProtos.ReplicationHLogPosition.newBuilder();
1939       ZooKeeperProtos.ReplicationHLogPosition position;
1940       try {
1941         position = builder.mergeFrom(bytes, pblen, bytes.length - pblen).build();
1942       } catch (InvalidProtocolBufferException e) {
1943         throw new DeserializationException(e);
1944       }
1945       return position.getPosition();
1946     } else {
1947       if (bytes.length > 0) {
1948         return Bytes.toLong(bytes);
1949       }
1950       return 0;
1951     }
1952   }
1953 
1954   /**
1955    * @param regionLastFlushedSequenceId the flushed sequence id of a region which is the min of its
1956    *          store max seq ids
1957    * @param storeSequenceIds column family to sequence Id map
1958    * @return Serialized protobuf of <code>RegionSequenceIds</code> with pb magic prefix prepended
1959    *         suitable for use to filter wal edits in distributedLogReplay mode
1960    */
1961   public static byte[] regionSequenceIdsToByteArray(final Long regionLastFlushedSequenceId,
1962       final Map<byte[], Long> storeSequenceIds) {
1963     ZooKeeperProtos.RegionStoreSequenceIds.Builder regionSequenceIdsBuilder =
1964         ZooKeeperProtos.RegionStoreSequenceIds.newBuilder();
1965     ZooKeeperProtos.StoreSequenceId.Builder storeSequenceIdBuilder =
1966         ZooKeeperProtos.StoreSequenceId.newBuilder();
1967     if (storeSequenceIds != null) {
1968       for (Map.Entry<byte[], Long> e : storeSequenceIds.entrySet()){
1969         byte[] columnFamilyName = e.getKey();
1970         Long curSeqId = e.getValue();
1971         storeSequenceIdBuilder.setFamilyName(HBaseZeroCopyByteString.wrap(columnFamilyName));
1972         storeSequenceIdBuilder.setSequenceId(curSeqId);
1973         regionSequenceIdsBuilder.addStoreSequenceId(storeSequenceIdBuilder.build());
1974         storeSequenceIdBuilder.clear();
1975       }
1976     }
1977     regionSequenceIdsBuilder.setLastFlushedSequenceId(regionLastFlushedSequenceId);
1978     byte[] result = regionSequenceIdsBuilder.build().toByteArray();
1979     return ProtobufUtil.prependPBMagic(result);
1980   }
1981 
1982   /**
1983    * @param bytes Content of serialized data of RegionStoreSequenceIds
1984    * @return a RegionStoreSequenceIds object
1985    * @throws DeserializationException
1986    */
1987   public static RegionStoreSequenceIds parseRegionStoreSequenceIds(final byte[] bytes)
1988       throws DeserializationException {
1989     if (bytes == null || !ProtobufUtil.isPBMagicPrefix(bytes)) {
1990       throw new DeserializationException("Unable to parse RegionStoreSequenceIds.");
1991     }
1992     RegionStoreSequenceIds.Builder regionSequenceIdsBuilder =
1993         ZooKeeperProtos.RegionStoreSequenceIds.newBuilder();
1994     int pblen = ProtobufUtil.lengthOfPBMagic();
1995     RegionStoreSequenceIds storeIds = null;
1996     try {
1997       storeIds = regionSequenceIdsBuilder.mergeFrom(bytes, pblen, bytes.length - pblen).build();
1998     } catch (InvalidProtocolBufferException e) {
1999       throw new DeserializationException(e);
2000     }
2001     return storeIds;
2002   }
2003 }