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.Closeable;
22  import java.io.IOException;
23  import java.util.ArrayList;
24  import java.util.HashMap;
25  import java.util.List;
26  import java.util.Map;
27  import java.util.concurrent.CopyOnWriteArrayList;
28  import java.util.concurrent.CountDownLatch;
29  import java.util.regex.Matcher;
30  import java.util.regex.Pattern;
31  
32  import org.apache.commons.logging.Log;
33  import org.apache.commons.logging.LogFactory;
34  import org.apache.hadoop.conf.Configuration;
35  import org.apache.hadoop.hbase.Abortable;
36  import org.apache.hadoop.hbase.AuthUtil;
37  import org.apache.hadoop.hbase.HConstants;
38  import org.apache.hadoop.hbase.HRegionInfo;
39  import org.apache.hadoop.hbase.ZooKeeperConnectionException;
40  import org.apache.hadoop.hbase.classification.InterfaceAudience;
41  import org.apache.hadoop.hbase.security.Superusers;
42  import org.apache.hadoop.security.UserGroupInformation;
43  import org.apache.zookeeper.KeeperException;
44  import org.apache.zookeeper.WatchedEvent;
45  import org.apache.zookeeper.Watcher;
46  import org.apache.zookeeper.ZooDefs.Ids;
47  import org.apache.zookeeper.ZooDefs.Perms;
48  import org.apache.zookeeper.data.ACL;
49  import org.apache.zookeeper.data.Id;
50  import org.apache.zookeeper.data.Stat;
51  
52  /**
53   * Acts as the single ZooKeeper Watcher.  One instance of this is instantiated
54   * for each Master, RegionServer, and client process.
55   *
56   * <p>This is the only class that implements {@link Watcher}.  Other internal
57   * classes which need to be notified of ZooKeeper events must register with
58   * the local instance of this watcher via {@link #registerListener}.
59   *
60   * <p>This class also holds and manages the connection to ZooKeeper.  Code to
61   * deal with connection related events and exceptions are handled here.
62   */
63  @InterfaceAudience.Private
64  public class ZooKeeperWatcher implements Watcher, Abortable, Closeable {
65    private static final Log LOG = LogFactory.getLog(ZooKeeperWatcher.class);
66  
67    // Identifier for this watcher (for logging only).  It is made of the prefix
68    // passed on construction and the zookeeper sessionid.
69    private String prefix;
70    private String identifier;
71  
72    // zookeeper quorum
73    private String quorum;
74  
75    // zookeeper connection
76    private final RecoverableZooKeeper recoverableZooKeeper;
77  
78    // abortable in case of zk failure
79    protected Abortable abortable;
80    // Used if abortable is null
81    private boolean aborted = false;
82  
83    // listeners to be notified
84    private final List<ZooKeeperListener> listeners =
85      new CopyOnWriteArrayList<ZooKeeperListener>();
86  
87    // Used by ZKUtil:waitForZKConnectionIfAuthenticating to wait for SASL
88    // negotiation to complete
89    public CountDownLatch saslLatch = new CountDownLatch(1);
90  
91    // node names
92  
93    // base znode for this cluster
94    public String baseZNode;
95    //znodes containing the locations of the servers hosting the meta replicas
96    private Map<Integer,String> metaReplicaZnodes = new HashMap<Integer, String>();
97    // znode containing ephemeral nodes of the regionservers
98    public String rsZNode;
99    // znode containing ephemeral nodes of the draining regionservers
100   public String drainingZNode;
101   // znode of currently active master
102   private String masterAddressZNode;
103   // znode of this master in backup master directory, if not the active master
104   public String backupMasterAddressesZNode;
105   // znode containing the current cluster state
106   public String clusterStateZNode;
107   // znode used for table disabling/enabling
108   @Deprecated
109   public String tableZNode;
110   // znode containing the unique cluster ID
111   public String clusterIdZNode;
112   // znode used for log splitting work assignment
113   public String splitLogZNode;
114   // znode containing the state of the load balancer
115   public String balancerZNode;
116   // znode containing the state of region normalizer
117   private String regionNormalizerZNode;
118   // znode containing the state of all switches, currently there are split and merge child node.
119   private String switchZNode;
120   // znode containing the lock for the switches
121   private String switchLockZNode;
122   // znode containing the lock for the tables
123   public String tableLockZNode;
124   // znode containing the state of recovering regions
125   public String recoveringRegionsZNode;
126   // znode containing namespace descriptors
127   public static String namespaceZNode = "namespace";
128 
129   public final static String META_ZNODE_PREFIX = "meta-region-server";
130 
131   private final Configuration conf;
132 
133   /* A pattern that matches a Kerberos name, borrowed from Hadoop's KerberosName */
134   private static final Pattern NAME_PATTERN = Pattern.compile("([^/@]*)(/([^/@]*))?@([^/@]*)");
135
136   /**
137    * Instantiate a ZooKeeper connection and watcher.
138    * @param identifier string that is passed to RecoverableZookeeper to be used as
139    * identifier for this instance. Use null for default.
140    * @throws IOException
141    * @throws ZooKeeperConnectionException
142    */
143   public ZooKeeperWatcher(Configuration conf, String identifier,
144       Abortable abortable) throws ZooKeeperConnectionException, IOException {
145     this(conf, identifier, abortable, false);
146   }
147
148   /**
149    * Instantiate a ZooKeeper connection and watcher.
150    * @param conf
151    * @param identifier string that is passed to RecoverableZookeeper to be used as identifier for
152    *          this instance. Use null for default.
153    * @param abortable Can be null if there is on error there is no host to abort: e.g. client
154    *          context.
155    * @param canCreateBaseZNode
156    * @throws IOException
157    * @throws ZooKeeperConnectionException
158    */
159   public ZooKeeperWatcher(Configuration conf, String identifier,
160       Abortable abortable, boolean canCreateBaseZNode)
161   throws IOException, ZooKeeperConnectionException {
162     this.conf = conf;
163     this.quorum = ZKConfig.getZKQuorumServersString(conf);
164     this.prefix = identifier;
165     // Identifier will get the sessionid appended later below down when we
166     // handle the syncconnect event.
167     this.identifier = identifier + "0x0";
168     this.abortable = abortable;
169     setNodeNames(conf);
170     PendingWatcher pendingWatcher = new PendingWatcher();
171     this.recoverableZooKeeper = ZKUtil.connect(conf, quorum, pendingWatcher, identifier);
172     pendingWatcher.prepare(this);
173     if (canCreateBaseZNode) {
174       try {
175         createBaseZNodes();
176       } catch (ZooKeeperConnectionException zce) {
177         try {
178           this.recoverableZooKeeper.close();
179         } catch (InterruptedException ie) {
180           LOG.debug("Encountered InterruptedException when closing " + this.recoverableZooKeeper);
181           Thread.currentThread().interrupt();
182         }
183         throw zce;
184       }
185     }
186   }
187
188   private void createBaseZNodes() throws ZooKeeperConnectionException {
189     try {
190       // Create all the necessary "directories" of znodes
191       ZKUtil.createWithParents(this, baseZNode);
192       ZKUtil.createAndFailSilent(this, rsZNode);
193       ZKUtil.createAndFailSilent(this, drainingZNode);
194       ZKUtil.createAndFailSilent(this, tableZNode);
195       ZKUtil.createAndFailSilent(this, splitLogZNode);
196       ZKUtil.createAndFailSilent(this, backupMasterAddressesZNode);
197       ZKUtil.createAndFailSilent(this, tableLockZNode);
198       ZKUtil.createAndFailSilent(this, recoveringRegionsZNode);
199     } catch (KeeperException e) {
200       throw new ZooKeeperConnectionException(
201           prefix("Unexpected KeeperException creating base node"), e);
202     }
203   }
204
205   /** Returns whether the znode is supposed to be readable by the client
206    * and DOES NOT contain sensitive information (world readable).*/
207   public boolean isClientReadable(String node) {
208     // Developer notice: These znodes are world readable. DO NOT add more znodes here UNLESS
209     // all clients need to access this data to work. Using zk for sharing data to clients (other
210     // than service lookup case is not a recommended design pattern.
211     return
212         node.equals(baseZNode) ||
213         isAnyMetaReplicaZnode(node) ||
214         node.equals(getMasterAddressZNode()) ||
215         node.equals(clusterIdZNode)||
216         node.equals(rsZNode) ||
217         // /hbase/table and /hbase/table/foo is allowed, /hbase/table-lock is not
218         node.equals(tableZNode) ||
219         node.startsWith(tableZNode + "/");
220   }
221
222   /**
223    * On master start, we check the znode ACLs under the root directory and set the ACLs properly
224    * if needed. If the cluster goes from an unsecure setup to a secure setup, this step is needed
225    * so that the existing znodes created with open permissions are now changed with restrictive
226    * perms.
227    */
228   public void checkAndSetZNodeAcls() {
229     if (!ZKUtil.isSecureZooKeeper(getConfiguration())) {
230       LOG.info("not a secure deployment, proceeding");
231       return;
232     }
233
234     // Check the base znodes permission first. Only do the recursion if base znode's perms are not
235     // correct.
236     try {
237       List<ACL> actualAcls = recoverableZooKeeper.getAcl(baseZNode, new Stat());
238
239       if (!isBaseZnodeAclSetup(actualAcls)) {
240         LOG.info("setting znode ACLs");
241         setZnodeAclsRecursive(baseZNode);
242       }
243     } catch(KeeperException.NoNodeException nne) {
244       return;
245     } catch(InterruptedException ie) {
246       interruptedException(ie);
247     } catch (IOException|KeeperException e) {
248       LOG.warn("Received exception while checking and setting zookeeper ACLs", e);
249     }
250   }
251
252   /**
253    * Set the znode perms recursively. This will do post-order recursion, so that baseZnode ACLs
254    * will be set last in case the master fails in between.
255    * @param znode
256    */
257   private void setZnodeAclsRecursive(String znode) throws KeeperException, InterruptedException {
258     List<String> children = recoverableZooKeeper.getChildren(znode, false);
259
260     for (String child : children) {
261       setZnodeAclsRecursive(ZKUtil.joinZNode(znode, child));
262     }
263     List<ACL> acls = ZKUtil.createACL(this, znode, true);
264     LOG.info("Setting ACLs for znode:" + znode + " , acl:" + acls);
265     recoverableZooKeeper.setAcl(znode, acls, -1);
266   }
267
268   /**
269    * Checks whether the ACLs returned from the base znode (/hbase) is set for secure setup.
270    * @param acls acls from zookeeper
271    * @return whether ACLs are set for the base znode
272    * @throws IOException
273    */
274   private boolean isBaseZnodeAclSetup(List<ACL> acls) throws IOException {
275     if (LOG.isDebugEnabled()) {
276       LOG.debug("Checking znode ACLs");
277     }
278     String[] superUsers = conf.getStrings(Superusers.SUPERUSER_CONF_KEY);
279     // Check whether ACL set for all superusers
280     if (superUsers != null && !checkACLForSuperUsers(superUsers, acls)) {
281       return false;
282     }
283
284     // this assumes that current authenticated user is the same as zookeeper client user
285     // configured via JAAS
286     String hbaseUser = UserGroupInformation.getCurrentUser().getShortUserName();
287
288     if (acls.isEmpty()) {
289       if (LOG.isDebugEnabled()) {
290         LOG.debug("ACL is empty");
291       }
292       return false;
293     }
294
295     for (ACL acl : acls) {
296       int perms = acl.getPerms();
297       Id id = acl.getId();
298       // We should only set at most 3 possible ACLs for 3 Ids. One for everyone, one for superuser
299       // and one for the hbase user
300       if (Ids.ANYONE_ID_UNSAFE.equals(id)) {
301         if (perms != Perms.READ) {
302           if (LOG.isDebugEnabled()) {
303             LOG.debug(String.format("permissions for '%s' are not correct: have 0x%x, want 0x%x",
304               id, perms, Perms.READ));
305           }
306           return false;
307         }
308       } else if (superUsers != null && isSuperUserId(superUsers, id)) {
309         if (perms != Perms.ALL) {
310           if (LOG.isDebugEnabled()) {
311             LOG.debug(String.format("permissions for '%s' are not correct: have 0x%x, want 0x%x",
312               id, perms, Perms.ALL));
313           }
314           return false;
315         }
316       } else if ("sasl".equals(id.getScheme())) {
317         String name = id.getId();
318         // If ZooKeeper recorded the Kerberos full name in the ACL, use only the shortname
319         Matcher match = NAME_PATTERN.matcher(name);
320         if (match.matches()) {
321           name = match.group(1);
322         }
323         if (name.equals(hbaseUser)) {
324           if (perms != Perms.ALL) {
325             if (LOG.isDebugEnabled()) {
326               LOG.debug(String.format("permissions for '%s' are not correct: have 0x%x, want 0x%x",
327                 id, perms, Perms.ALL));
328             }
329             return false;
330           }
331         } else {
332           if (LOG.isDebugEnabled()) {
333             LOG.debug("Unexpected shortname in SASL ACL: " + id);
334           }
335           return false;
336         }
337       } else {
338         if (LOG.isDebugEnabled()) {
339           LOG.debug("unexpected ACL id '" + id + "'");
340         }
341         return false;
342       }
343     }
344     return true;
345   }
346
347   /*
348    * Validate whether ACL set for all superusers.
349    */
350   private boolean checkACLForSuperUsers(String[] superUsers, List<ACL> acls) {
351     for (String user : superUsers) {
352       boolean hasAccess = false;
353       // TODO: Validate super group members also when ZK supports setting node ACL for groups.
354       if (!AuthUtil.isGroupPrincipal(user)) {
355         for (ACL acl : acls) {
356           if (user.equals(acl.getId().getId())) {
357             if (acl.getPerms() == Perms.ALL) {
358               hasAccess = true;
359             } else {
360               if (LOG.isDebugEnabled()) {
361                 LOG.debug(String.format(
362                   "superuser '%s' does not have correct permissions: have 0x%x, want 0x%x",
363                   acl.getId().getId(), acl.getPerms(), Perms.ALL));
364               }
365             }
366             break;
367           }
368         }
369         if (!hasAccess) {
370           return false;
371         }
372       }
373     }
374     return true;
375   }
376
377   /*
378    * Validate whether ACL ID is superuser.
379    */
380   public static boolean isSuperUserId(String[] superUsers, Id id) {
381     for (String user : superUsers) {
382       // TODO: Validate super group members also when ZK supports setting node ACL for groups.
383       if (!AuthUtil.isGroupPrincipal(user) && new Id("sasl", user).equals(id)) {
384         return true;
385       }
386     }
387     return false;
388   }
389
390   @Override
391   public String toString() {
392     return this.identifier + ", quorum=" + quorum + ", baseZNode=" + baseZNode;
393   }
394
395   /**
396    * Adds this instance's identifier as a prefix to the passed <code>str</code>
397    * @param str String to amend.
398    * @return A new string with this instance's identifier as prefix: e.g.
399    * if passed 'hello world', the returned string could be
400    */
401   public String prefix(final String str) {
402     return this.toString() + " " + str;
403   }
404
405   /**
406    * Set the local variable node names using the specified configuration.
407    */
408   private void setNodeNames(Configuration conf) {
409     baseZNode = conf.get(HConstants.ZOOKEEPER_ZNODE_PARENT,
410         HConstants.DEFAULT_ZOOKEEPER_ZNODE_PARENT);
411     metaReplicaZnodes.put(0, ZKUtil.joinZNode(baseZNode,
412            conf.get("zookeeper.znode.metaserver", "meta-region-server")));
413     int numMetaReplicas = conf.getInt(HConstants.META_REPLICAS_NUM,
414             HConstants.DEFAULT_META_REPLICA_NUM);
415     for (int i = 1; i < numMetaReplicas; i++) {
416       String str = ZKUtil.joinZNode(baseZNode,
417         conf.get("zookeeper.znode.metaserver", "meta-region-server") + "-" + i);
418       metaReplicaZnodes.put(i, str);
419     }
420     rsZNode = ZKUtil.joinZNode(baseZNode,
421         conf.get("zookeeper.znode.rs", "rs"));
422     drainingZNode = ZKUtil.joinZNode(baseZNode,
423         conf.get("zookeeper.znode.draining.rs", "draining"));
424     masterAddressZNode = ZKUtil.joinZNode(baseZNode,
425         conf.get("zookeeper.znode.master", "master"));
426     backupMasterAddressesZNode = ZKUtil.joinZNode(baseZNode,
427         conf.get("zookeeper.znode.backup.masters", "backup-masters"));
428     clusterStateZNode = ZKUtil.joinZNode(baseZNode,
429         conf.get("zookeeper.znode.state", "running"));
430     tableZNode = ZKUtil.joinZNode(baseZNode,
431         conf.get("zookeeper.znode.tableEnableDisable", "table"));
432     clusterIdZNode = ZKUtil.joinZNode(baseZNode,
433         conf.get("zookeeper.znode.clusterId", "hbaseid"));
434     splitLogZNode = ZKUtil.joinZNode(baseZNode,
435         conf.get("zookeeper.znode.splitlog", HConstants.SPLIT_LOGDIR_NAME));
436     balancerZNode = ZKUtil.joinZNode(baseZNode,
437         conf.get("zookeeper.znode.balancer", "balancer"));
438     regionNormalizerZNode = ZKUtil.joinZNode(baseZNode,
439       conf.get("zookeeper.znode.regionNormalizer", "normalizer"));
440     switchZNode = ZKUtil.joinZNode(baseZNode, conf.get("zookeeper.znode.switch", "switch"));
441     switchLockZNode = ZKUtil.joinZNode(switchZNode, "locks");
442     tableLockZNode = ZKUtil.joinZNode(baseZNode,
443         conf.get("zookeeper.znode.tableLock", "table-lock"));
444     recoveringRegionsZNode = ZKUtil.joinZNode(baseZNode,
445         conf.get("zookeeper.znode.recovering.regions", "recovering-regions"));
446     namespaceZNode = ZKUtil.joinZNode(baseZNode,
447         conf.get("zookeeper.znode.namespace", "namespace"));
448   }
449
450   /**
451    * Is the znode of any meta replica
452    * @param node
453    * @return true or false
454    */
455   public boolean isAnyMetaReplicaZnode(String node) {
456     if (metaReplicaZnodes.values().contains(node)) {
457       return true;
458     }
459     return false;
460   }
461
462   /**
463    * Is it the default meta replica's znode
464    * @param node
465    * @return true or false
466    */
467   public boolean isDefaultMetaReplicaZnode(String node) {
468     if (getZNodeForReplica(HRegionInfo.DEFAULT_REPLICA_ID).equals(node)) {
469       return true;
470     }
471     return false;
472   }
473
474   /**
475    * Get the znodes corresponding to the meta replicas from ZK
476    * @return list of znodes
477    * @throws KeeperException
478    */
479   public List<String> getMetaReplicaNodes() throws KeeperException {
480     List<String> childrenOfBaseNode = ZKUtil.listChildrenNoWatch(this, baseZNode);
481     List<String> metaReplicaNodes = new ArrayList<String>(2);
482     String pattern = conf.get("zookeeper.znode.metaserver","meta-region-server");
483     for (String child : childrenOfBaseNode) {
484       if (child.startsWith(pattern)) metaReplicaNodes.add(child);
485     }
486     return metaReplicaNodes;
487   }
488
489   /**
490    * Get the znode string corresponding to a replicaId
491    * @param replicaId
492    * @return znode
493    */
494   public String getZNodeForReplica(int replicaId) {
495     String str = metaReplicaZnodes.get(replicaId);
496     // return a newly created path but don't update the cache of paths
497     // This is mostly needed for tests that attempt to create meta replicas
498     // from outside the master
499     if (str == null) {
500       str = ZKUtil.joinZNode(baseZNode,
501           conf.get("zookeeper.znode.metaserver", "meta-region-server") + "-" + replicaId);
502     }
503     return str;
504   }
505
506   /**
507    * Parse the meta replicaId from the passed znode
508    * @param znode
509    * @return replicaId
510    */
511   public int getMetaReplicaIdFromZnode(String znode) {
512     String pattern = conf.get("zookeeper.znode.metaserver","meta-region-server");
513     if (znode.equals(pattern)) return HRegionInfo.DEFAULT_REPLICA_ID;
514     // the non-default replicas are of the pattern meta-region-server-<replicaId>
515     String nonDefaultPattern = pattern + "-";
516     return Integer.parseInt(znode.substring(nonDefaultPattern.length()));
517   }
518
519   /**
520    * Register the specified listener to receive ZooKeeper events.
521    * @param listener
522    */
523   public void registerListener(ZooKeeperListener listener) {
524     listeners.add(listener);
525   }
526
527   /**
528    * Register the specified listener to receive ZooKeeper events and add it as
529    * the first in the list of current listeners.
530    * @param listener
531    */
532   public void registerListenerFirst(ZooKeeperListener listener) {
533     listeners.add(0, listener);
534   }
535
536   public void unregisterListener(ZooKeeperListener listener) {
537     listeners.remove(listener);
538   }
539
540   /**
541    * Clean all existing listeners
542    */
543   public void unregisterAllListeners() {
544     listeners.clear();
545   }
546
547   /**
548    * Get a copy of current registered listeners
549    */
550   public List<ZooKeeperListener> getListeners() {
551     return new ArrayList<ZooKeeperListener>(listeners);
552   }
553
554   /**
555    * @return The number of currently registered listeners
556    */
557   public int getNumberOfListeners() {
558     return listeners.size();
559   }
560
561   /**
562    * Get the connection to ZooKeeper.
563    * @return connection reference to zookeeper
564    */
565   public RecoverableZooKeeper getRecoverableZooKeeper() {
566     return recoverableZooKeeper;
567   }
568
569   public void reconnectAfterExpiration() throws IOException, KeeperException, InterruptedException {
570     recoverableZooKeeper.reconnectAfterExpiration();
571   }
572
573   /**
574    * Get the quorum address of this instance.
575    * @return quorum string of this zookeeper connection instance
576    */
577   public String getQuorum() {
578     return quorum;
579   }
580
581   /**
582    * @return the base znode of this zookeeper connection instance.
583    */
584   public String getBaseZNode() {
585     return baseZNode;
586   }
587
588   /**
589    * Method called from ZooKeeper for events and connection status.
590    * <p>
591    * Valid events are passed along to listeners.  Connection status changes
592    * are dealt with locally.
593    */
594   @Override
595   public void process(WatchedEvent event) {
596     LOG.debug(prefix("Received ZooKeeper Event, " +
597         "type=" + event.getType() + ", " +
598         "state=" + event.getState() + ", " +
599         "path=" + event.getPath()));
600
601     switch(event.getType()) {
602
603       // If event type is NONE, this is a connection status change
604       case None: {
605         connectionEvent(event);
606         break;
607       }
608
609       // Otherwise pass along to the listeners
610
611       case NodeCreated: {
612         for(ZooKeeperListener listener : listeners) {
613           listener.nodeCreated(event.getPath());
614         }
615         break;
616       }
617
618       case NodeDeleted: {
619         for(ZooKeeperListener listener : listeners) {
620           listener.nodeDeleted(event.getPath());
621         }
622         break;
623       }
624
625       case NodeDataChanged: {
626         for(ZooKeeperListener listener : listeners) {
627           listener.nodeDataChanged(event.getPath());
628         }
629         break;
630       }
631
632       case NodeChildrenChanged: {
633         for(ZooKeeperListener listener : listeners) {
634           listener.nodeChildrenChanged(event.getPath());
635         }
636         break;
637       }
638     }
639   }
640
641   // Connection management
642
643   /**
644    * Called when there is a connection-related event via the Watcher callback.
645    * <p>
646    * If Disconnected or Expired, this should shutdown the cluster. But, since
647    * we send a KeeperException.SessionExpiredException along with the abort
648    * call, it's possible for the Abortable to catch it and try to create a new
649    * session with ZooKeeper. This is what the client does in HCM.
650    * <p>
651    * @param event
652    */
653   private void connectionEvent(WatchedEvent event) {
654     switch(event.getState()) {
655       case SyncConnected:
656         this.identifier = this.prefix + "-0x" +
657           Long.toHexString(this.recoverableZooKeeper.getSessionId());
658         // Update our identifier.  Otherwise ignore.
659         LOG.debug(this.identifier + " connected");
660         break;
661
662       // Abort the server if Disconnected or Expired
663       case Disconnected:
664         LOG.debug(prefix("Received Disconnected from ZooKeeper, ignoring"));
665         break;
666
667       case Expired:
668         String msg = prefix(this.identifier + " received expired from " +
669           "ZooKeeper, aborting");
670         // TODO: One thought is to add call to ZooKeeperListener so say,
671         // ZooKeeperNodeTracker can zero out its data values.
672         if (this.abortable != null) {
673           this.abortable.abort(msg, new KeeperException.SessionExpiredException());
674         }
675         break;
676
677       case ConnectedReadOnly:
678       case SaslAuthenticated:
679       case AuthFailed:
680         break;
681
682       default:
683         throw new IllegalStateException("Received event is not valid: " + event.getState());
684     }
685   }
686
687   /**
688    * Forces a synchronization of this ZooKeeper client connection.
689    * <p>
690    * Executing this method before running other methods will ensure that the
691    * subsequent operations are up-to-date and consistent as of the time that
692    * the sync is complete.
693    * <p>
694    * This is used for compareAndSwap type operations where we need to read the
695    * data of an existing node and delete or transition that node, utilizing the
696    * previously read version and data.  We want to ensure that the version read
697    * is up-to-date from when we begin the operation.
698    */
699   public void sync(String path) throws KeeperException {
700     this.recoverableZooKeeper.sync(path, null, null);
701   }
702
703   /**
704    * Handles KeeperExceptions in client calls.
705    * <p>
706    * This may be temporary but for now this gives one place to deal with these.
707    * <p>
708    * TODO: Currently this method rethrows the exception to let the caller handle
709    * <p>
710    * @param ke
711    * @throws KeeperException
712    */
713   public void keeperException(KeeperException ke)
714   throws KeeperException {
715     LOG.error(prefix("Received unexpected KeeperException, re-throwing exception"), ke);
716     throw ke;
717   }
718
719   /**
720    * Handles InterruptedExceptions in client calls.
721    * <p>
722    * This may be temporary but for now this gives one place to deal with these.
723    * <p>
724    * TODO: Currently, this method does nothing.
725    *       Is this ever expected to happen?  Do we abort or can we let it run?
726    *       Maybe this should be logged as WARN?  It shouldn't happen?
727    * <p>
728    * @param ie
729    */
730   public void interruptedException(InterruptedException ie) {
731     LOG.debug(prefix("Received InterruptedException, doing nothing here"), ie);
732     // At least preserver interrupt.
733     Thread.currentThread().interrupt();
734     // no-op
735   }
736
737   /**
738    * Close the connection to ZooKeeper.
739    *
740    */
741   @Override
742   public void close() {
743     try {
744       recoverableZooKeeper.close();
745     } catch (InterruptedException e) {
746       Thread.currentThread().interrupt();
747     }
748   }
749
750   public Configuration getConfiguration() {
751     return conf;
752   }
753
754   @Override
755   public void abort(String why, Throwable e) {
756     if (this.abortable != null) this.abortable.abort(why, e);
757     else this.aborted = true;
758   }
759
760   @Override
761   public boolean isAborted() {
762     return this.abortable == null? this.aborted: this.abortable.isAborted();
763   }
764
765   /**
766    * @return Path to the currently active master.
767    */
768   public String getMasterAddressZNode() {
769     return this.masterAddressZNode;
770   }
771
772   /**
773    * @return ZooKeeper znode for region normalizer state
774    */
775   public String getRegionNormalizerZNode() {
776     return regionNormalizerZNode;
777   }
778
779   /**
780    *  @return ZK node for switch
781    * */
782   public String getSwitchZNode() {
783     return switchZNode;
784   }
785
786   /**
787    *  @return ZK node for switchLock node.
788    * */
789   public String getSwitchLockZNode() {
790     return switchLockZNode;
791   }
792 }