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