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