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 tables
121   public String tableLockZNode;
122   // znode containing the state of recovering regions
123   public String recoveringRegionsZNode;
124   // znode containing namespace descriptors
125   public static String namespaceZNode = "namespace";
126   // znode of indicating master maintenance mode
127   public static String masterMaintZNode = "masterMaintenance";
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       ZKUtil.createAndFailSilent(this, masterMaintZNode);
200     } catch (KeeperException e) {
201       throw new ZooKeeperConnectionException(
202           prefix("Unexpected KeeperException creating base node"), e);
203     }
204   }
205
206   /** Returns whether the znode is supposed to be readable by the client
207    * and DOES NOT contain sensitive information (world readable).*/
208   public boolean isClientReadable(String node) {
209     // Developer notice: These znodes are world readable. DO NOT add more znodes here UNLESS
210     // all clients need to access this data to work. Using zk for sharing data to clients (other
211     // than service lookup case is not a recommended design pattern.
212     return
213         node.equals(baseZNode) ||
214         isAnyMetaReplicaZnode(node) ||
215         node.equals(getMasterAddressZNode()) ||
216         node.equals(clusterIdZNode)||
217         node.equals(rsZNode) ||
218         // /hbase/table and /hbase/table/foo is allowed, /hbase/table-lock is not
219         node.equals(tableZNode) ||
220         node.startsWith(tableZNode + "/");
221   }
222
223   /**
224    * On master start, we check the znode ACLs under the root directory and set the ACLs properly
225    * if needed. If the cluster goes from an unsecure setup to a secure setup, this step is needed
226    * so that the existing znodes created with open permissions are now changed with restrictive
227    * perms.
228    */
229   public void checkAndSetZNodeAcls() {
230     if (!ZKUtil.isSecureZooKeeper(getConfiguration())) {
231       LOG.info("not a secure deployment, proceeding");
232       return;
233     }
234
235     // Check the base znodes permission first. Only do the recursion if base znode's perms are not
236     // correct.
237     try {
238       List<ACL> actualAcls = recoverableZooKeeper.getAcl(baseZNode, new Stat());
239
240       if (!isBaseZnodeAclSetup(actualAcls)) {
241         LOG.info("setting znode ACLs");
242         setZnodeAclsRecursive(baseZNode);
243       }
244     } catch(KeeperException.NoNodeException nne) {
245       return;
246     } catch(InterruptedException ie) {
247       interruptedException(ie);
248     } catch (IOException|KeeperException e) {
249       LOG.warn("Received exception while checking and setting zookeeper ACLs", e);
250     }
251   }
252
253   /**
254    * Set the znode perms recursively. This will do post-order recursion, so that baseZnode ACLs
255    * will be set last in case the master fails in between.
256    * @param znode
257    */
258   private void setZnodeAclsRecursive(String znode) throws KeeperException, InterruptedException {
259     List<String> children = recoverableZooKeeper.getChildren(znode, false);
260
261     for (String child : children) {
262       setZnodeAclsRecursive(ZKUtil.joinZNode(znode, child));
263     }
264     List<ACL> acls = ZKUtil.createACL(this, znode, true);
265     LOG.info("Setting ACLs for znode:" + znode + " , acl:" + acls);
266     recoverableZooKeeper.setAcl(znode, acls, -1);
267   }
268
269   /**
270    * Checks whether the ACLs returned from the base znode (/hbase) is set for secure setup.
271    * @param acls acls from zookeeper
272    * @return whether ACLs are set for the base znode
273    * @throws IOException
274    */
275   private boolean isBaseZnodeAclSetup(List<ACL> acls) throws IOException {
276     if (LOG.isDebugEnabled()) {
277       LOG.debug("Checking znode ACLs");
278     }
279     String[] superUsers = conf.getStrings(Superusers.SUPERUSER_CONF_KEY);
280     // Check whether ACL set for all superusers
281     if (superUsers != null && !checkACLForSuperUsers(superUsers, acls)) {
282       return false;
283     }
284
285     // this assumes that current authenticated user is the same as zookeeper client user
286     // configured via JAAS
287     String hbaseUser = UserGroupInformation.getCurrentUser().getShortUserName();
288
289     if (acls.isEmpty()) {
290       if (LOG.isDebugEnabled()) {
291         LOG.debug("ACL is empty");
292       }
293       return false;
294     }
295
296     for (ACL acl : acls) {
297       int perms = acl.getPerms();
298       Id id = acl.getId();
299       // We should only set at most 3 possible ACLs for 3 Ids. One for everyone, one for superuser
300       // and one for the hbase user
301       if (Ids.ANYONE_ID_UNSAFE.equals(id)) {
302         if (perms != Perms.READ) {
303           if (LOG.isDebugEnabled()) {
304             LOG.debug(String.format("permissions for '%s' are not correct: have 0x%x, want 0x%x",
305               id, perms, Perms.READ));
306           }
307           return false;
308         }
309       } else if (superUsers != null && isSuperUserId(superUsers, id)) {
310         if (perms != Perms.ALL) {
311           if (LOG.isDebugEnabled()) {
312             LOG.debug(String.format("permissions for '%s' are not correct: have 0x%x, want 0x%x",
313               id, perms, Perms.ALL));
314           }
315           return false;
316         }
317       } else if ("sasl".equals(id.getScheme())) {
318         String name = id.getId();
319         // If ZooKeeper recorded the Kerberos full name in the ACL, use only the shortname
320         Matcher match = NAME_PATTERN.matcher(name);
321         if (match.matches()) {
322           name = match.group(1);
323         }
324         if (name.equals(hbaseUser)) {
325           if (perms != Perms.ALL) {
326             if (LOG.isDebugEnabled()) {
327               LOG.debug(String.format("permissions for '%s' are not correct: have 0x%x, want 0x%x",
328                 id, perms, Perms.ALL));
329             }
330             return false;
331           }
332         } else {
333           if (LOG.isDebugEnabled()) {
334             LOG.debug("Unexpected shortname in SASL ACL: " + id);
335           }
336           return false;
337         }
338       } else {
339         if (LOG.isDebugEnabled()) {
340           LOG.debug("unexpected ACL id '" + id + "'");
341         }
342         return false;
343       }
344     }
345     return true;
346   }
347
348   /*
349    * Validate whether ACL set for all superusers.
350    */
351   private boolean checkACLForSuperUsers(String[] superUsers, List<ACL> acls) {
352     for (String user : superUsers) {
353       boolean hasAccess = false;
354       // TODO: Validate super group members also when ZK supports setting node ACL for groups.
355       if (!AuthUtil.isGroupPrincipal(user)) {
356         for (ACL acl : acls) {
357           if (user.equals(acl.getId().getId())) {
358             if (acl.getPerms() == Perms.ALL) {
359               hasAccess = true;
360             } else {
361               if (LOG.isDebugEnabled()) {
362                 LOG.debug(String.format(
363                   "superuser '%s' does not have correct permissions: have 0x%x, want 0x%x",
364                   acl.getId().getId(), acl.getPerms(), Perms.ALL));
365               }
366             }
367             break;
368           }
369         }
370         if (!hasAccess) {
371           return false;
372         }
373       }
374     }
375     return true;
376   }
377
378   /*
379    * Validate whether ACL ID is superuser.
380    */
381   public static boolean isSuperUserId(String[] superUsers, Id id) {
382     for (String user : superUsers) {
383       // TODO: Validate super group members also when ZK supports setting node ACL for groups.
384       if (!AuthUtil.isGroupPrincipal(user) && new Id("sasl", user).equals(id)) {
385         return true;
386       }
387     }
388     return false;
389   }
390
391   @Override
392   public String toString() {
393     return this.identifier + ", quorum=" + quorum + ", baseZNode=" + baseZNode;
394   }
395
396   /**
397    * Adds this instance's identifier as a prefix to the passed <code>str</code>
398    * @param str String to amend.
399    * @return A new string with this instance's identifier as prefix: e.g.
400    * if passed 'hello world', the returned string could be
401    */
402   public String prefix(final String str) {
403     return this.toString() + " " + str;
404   }
405
406   /**
407    * Set the local variable node names using the specified configuration.
408    */
409   private void setNodeNames(Configuration conf) {
410     baseZNode = conf.get(HConstants.ZOOKEEPER_ZNODE_PARENT,
411         HConstants.DEFAULT_ZOOKEEPER_ZNODE_PARENT);
412     metaReplicaZnodes.put(0, ZKUtil.joinZNode(baseZNode,
413            conf.get("zookeeper.znode.metaserver", "meta-region-server")));
414     int numMetaReplicas = conf.getInt(HConstants.META_REPLICAS_NUM,
415             HConstants.DEFAULT_META_REPLICA_NUM);
416     for (int i = 1; i < numMetaReplicas; i++) {
417       String str = ZKUtil.joinZNode(baseZNode,
418         conf.get("zookeeper.znode.metaserver", "meta-region-server") + "-" + i);
419       metaReplicaZnodes.put(i, str);
420     }
421     rsZNode = ZKUtil.joinZNode(baseZNode,
422         conf.get("zookeeper.znode.rs", "rs"));
423     drainingZNode = ZKUtil.joinZNode(baseZNode,
424         conf.get("zookeeper.znode.draining.rs", "draining"));
425     masterAddressZNode = ZKUtil.joinZNode(baseZNode,
426         conf.get("zookeeper.znode.master", "master"));
427     backupMasterAddressesZNode = ZKUtil.joinZNode(baseZNode,
428         conf.get("zookeeper.znode.backup.masters", "backup-masters"));
429     clusterStateZNode = ZKUtil.joinZNode(baseZNode,
430         conf.get("zookeeper.znode.state", "running"));
431     tableZNode = ZKUtil.joinZNode(baseZNode,
432         conf.get("zookeeper.znode.tableEnableDisable", "table"));
433     clusterIdZNode = ZKUtil.joinZNode(baseZNode,
434         conf.get("zookeeper.znode.clusterId", "hbaseid"));
435     splitLogZNode = ZKUtil.joinZNode(baseZNode,
436         conf.get("zookeeper.znode.splitlog", HConstants.SPLIT_LOGDIR_NAME));
437     balancerZNode = ZKUtil.joinZNode(baseZNode,
438         conf.get("zookeeper.znode.balancer", "balancer"));
439     regionNormalizerZNode = ZKUtil.joinZNode(baseZNode,
440       conf.get("zookeeper.znode.regionNormalizer", "normalizer"));
441     switchZNode = ZKUtil.joinZNode(baseZNode, conf.get("zookeeper.znode.switch", "switch"));
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     masterMaintZNode = ZKUtil.joinZNode(baseZNode,
449       conf.get("zookeeper.znode.masterMaintenance", "master-maintenance"));
450   }
451
452   /**
453    * Is the znode of any meta replica
454    * @param node
455    * @return true or false
456    */
457   public boolean isAnyMetaReplicaZnode(String node) {
458     if (metaReplicaZnodes.values().contains(node)) {
459       return true;
460     }
461     return false;
462   }
463
464   /**
465    * Is it the default meta replica's znode
466    * @param node
467    * @return true or false
468    */
469   public boolean isDefaultMetaReplicaZnode(String node) {
470     if (getZNodeForReplica(HRegionInfo.DEFAULT_REPLICA_ID).equals(node)) {
471       return true;
472     }
473     return false;
474   }
475
476   /**
477    * Get the znodes corresponding to the meta replicas from ZK
478    * @return list of znodes
479    * @throws KeeperException
480    */
481   public List<String> getMetaReplicaNodes() throws KeeperException {
482     List<String> childrenOfBaseNode = ZKUtil.listChildrenNoWatch(this, baseZNode);
483     List<String> metaReplicaNodes = new ArrayList<String>(2);
484     String pattern = conf.get("zookeeper.znode.metaserver","meta-region-server");
485     for (String child : childrenOfBaseNode) {
486       if (child.startsWith(pattern)) metaReplicaNodes.add(child);
487     }
488     return metaReplicaNodes;
489   }
490
491   /**
492    * Get the znode string corresponding to a replicaId
493    * @param replicaId
494    * @return znode
495    */
496   public String getZNodeForReplica(int replicaId) {
497     String str = metaReplicaZnodes.get(replicaId);
498     // return a newly created path but don't update the cache of paths
499     // This is mostly needed for tests that attempt to create meta replicas
500     // from outside the master
501     if (str == null) {
502       str = ZKUtil.joinZNode(baseZNode,
503           conf.get("zookeeper.znode.metaserver", "meta-region-server") + "-" + replicaId);
504     }
505     return str;
506   }
507
508   /**
509    * Parse the meta replicaId from the passed znode
510    * @param znode
511    * @return replicaId
512    */
513   public int getMetaReplicaIdFromZnode(String znode) {
514     String pattern = conf.get("zookeeper.znode.metaserver","meta-region-server");
515     if (znode.equals(pattern)) return HRegionInfo.DEFAULT_REPLICA_ID;
516     // the non-default replicas are of the pattern meta-region-server-<replicaId>
517     String nonDefaultPattern = pattern + "-";
518     return Integer.parseInt(znode.substring(nonDefaultPattern.length()));
519   }
520
521   /**
522    * Register the specified listener to receive ZooKeeper events.
523    * @param listener
524    */
525   public void registerListener(ZooKeeperListener listener) {
526     listeners.add(listener);
527   }
528
529   /**
530    * Register the specified listener to receive ZooKeeper events and add it as
531    * the first in the list of current listeners.
532    * @param listener
533    */
534   public void registerListenerFirst(ZooKeeperListener listener) {
535     listeners.add(0, listener);
536   }
537
538   public void unregisterListener(ZooKeeperListener listener) {
539     listeners.remove(listener);
540   }
541
542   /**
543    * Clean all existing listeners
544    */
545   public void unregisterAllListeners() {
546     listeners.clear();
547   }
548
549   /**
550    * Get a copy of current registered listeners
551    */
552   public List<ZooKeeperListener> getListeners() {
553     return new ArrayList<ZooKeeperListener>(listeners);
554   }
555
556   /**
557    * @return The number of currently registered listeners
558    */
559   public int getNumberOfListeners() {
560     return listeners.size();
561   }
562
563   /**
564    * Get the connection to ZooKeeper.
565    * @return connection reference to zookeeper
566    */
567   public RecoverableZooKeeper getRecoverableZooKeeper() {
568     return recoverableZooKeeper;
569   }
570
571   public void reconnectAfterExpiration() throws IOException, KeeperException, InterruptedException {
572     recoverableZooKeeper.reconnectAfterExpiration();
573   }
574
575   /**
576    * Get the quorum address of this instance.
577    * @return quorum string of this zookeeper connection instance
578    */
579   public String getQuorum() {
580     return quorum;
581   }
582
583   /**
584    * @return the base znode of this zookeeper connection instance.
585    */
586   public String getBaseZNode() {
587     return baseZNode;
588   }
589
590   /**
591    * Method called from ZooKeeper for events and connection status.
592    * <p>
593    * Valid events are passed along to listeners.  Connection status changes
594    * are dealt with locally.
595    */
596   @Override
597   public void process(WatchedEvent event) {
598     LOG.debug(prefix("Received ZooKeeper Event, " +
599         "type=" + event.getType() + ", " +
600         "state=" + event.getState() + ", " +
601         "path=" + event.getPath()));
602
603     switch(event.getType()) {
604
605       // If event type is NONE, this is a connection status change
606       case None: {
607         connectionEvent(event);
608         break;
609       }
610
611       // Otherwise pass along to the listeners
612
613       case NodeCreated: {
614         for(ZooKeeperListener listener : listeners) {
615           listener.nodeCreated(event.getPath());
616         }
617         break;
618       }
619
620       case NodeDeleted: {
621         for(ZooKeeperListener listener : listeners) {
622           listener.nodeDeleted(event.getPath());
623         }
624         break;
625       }
626
627       case NodeDataChanged: {
628         for(ZooKeeperListener listener : listeners) {
629           listener.nodeDataChanged(event.getPath());
630         }
631         break;
632       }
633
634       case NodeChildrenChanged: {
635         for(ZooKeeperListener listener : listeners) {
636           listener.nodeChildrenChanged(event.getPath());
637         }
638         break;
639       }
640     }
641   }
642
643   // Connection management
644
645   /**
646    * Called when there is a connection-related event via the Watcher callback.
647    * <p>
648    * If Disconnected or Expired, this should shutdown the cluster. But, since
649    * we send a KeeperException.SessionExpiredException along with the abort
650    * call, it's possible for the Abortable to catch it and try to create a new
651    * session with ZooKeeper. This is what the client does in HCM.
652    * <p>
653    * @param event
654    */
655   private void connectionEvent(WatchedEvent event) {
656     switch(event.getState()) {
657       case SyncConnected:
658         this.identifier = this.prefix + "-0x" +
659           Long.toHexString(this.recoverableZooKeeper.getSessionId());
660         // Update our identifier.  Otherwise ignore.
661         LOG.debug(this.identifier + " connected");
662         break;
663
664       // Abort the server if Disconnected or Expired
665       case Disconnected:
666         LOG.debug(prefix("Received Disconnected from ZooKeeper, ignoring"));
667         break;
668
669       case Expired:
670         String msg = prefix(this.identifier + " received expired from " +
671           "ZooKeeper, aborting");
672         // TODO: One thought is to add call to ZooKeeperListener so say,
673         // ZooKeeperNodeTracker can zero out its data values.
674         if (this.abortable != null) {
675           this.abortable.abort(msg, new KeeperException.SessionExpiredException());
676         }
677         break;
678
679       case ConnectedReadOnly:
680       case SaslAuthenticated:
681       case AuthFailed:
682         break;
683
684       default:
685         throw new IllegalStateException("Received event is not valid: " + event.getState());
686     }
687   }
688
689   /**
690    * Forces a synchronization of this ZooKeeper client connection.
691    * <p>
692    * Executing this method before running other methods will ensure that the
693    * subsequent operations are up-to-date and consistent as of the time that
694    * the sync is complete.
695    * <p>
696    * This is used for compareAndSwap type operations where we need to read the
697    * data of an existing node and delete or transition that node, utilizing the
698    * previously read version and data.  We want to ensure that the version read
699    * is up-to-date from when we begin the operation.
700    */
701   public void sync(String path) throws KeeperException {
702     this.recoverableZooKeeper.sync(path, null, null);
703   }
704
705   /**
706    * Handles KeeperExceptions in client calls.
707    * <p>
708    * This may be temporary but for now this gives one place to deal with these.
709    * <p>
710    * TODO: Currently this method rethrows the exception to let the caller handle
711    * <p>
712    * @param ke
713    * @throws KeeperException
714    */
715   public void keeperException(KeeperException ke)
716   throws KeeperException {
717     LOG.error(prefix("Received unexpected KeeperException, re-throwing exception"), ke);
718     throw ke;
719   }
720
721   /**
722    * Handles InterruptedExceptions in client calls.
723    * <p>
724    * This may be temporary but for now this gives one place to deal with these.
725    * <p>
726    * TODO: Currently, this method does nothing.
727    *       Is this ever expected to happen?  Do we abort or can we let it run?
728    *       Maybe this should be logged as WARN?  It shouldn't happen?
729    * <p>
730    * @param ie
731    */
732   public void interruptedException(InterruptedException ie) {
733     LOG.debug(prefix("Received InterruptedException, doing nothing here"), ie);
734     // At least preserver interrupt.
735     Thread.currentThread().interrupt();
736     // no-op
737   }
738
739   /**
740    * Close the connection to ZooKeeper.
741    *
742    */
743   @Override
744   public void close() {
745     try {
746       recoverableZooKeeper.close();
747     } catch (InterruptedException e) {
748       Thread.currentThread().interrupt();
749     }
750   }
751
752   public Configuration getConfiguration() {
753     return conf;
754   }
755
756   @Override
757   public void abort(String why, Throwable e) {
758     if (this.abortable != null) this.abortable.abort(why, e);
759     else this.aborted = true;
760   }
761
762   @Override
763   public boolean isAborted() {
764     return this.abortable == null? this.aborted: this.abortable.isAborted();
765   }
766
767   /**
768    * @return Path to the currently active master.
769    */
770   public String getMasterAddressZNode() {
771     return this.masterAddressZNode;
772   }
773
774   /**
775    * @return ZooKeeper znode for region normalizer state
776    */
777   public String getRegionNormalizerZNode() {
778     return regionNormalizerZNode;
779   }
780
781   /**
782    *  @return ZK node for switch
783    * */
784   public String getSwitchZNode() {
785     return switchZNode;
786   }
787 }