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.Arrays;
25  import java.util.HashMap;
26  import java.util.List;
27  import java.util.Map;
28  import java.util.concurrent.CopyOnWriteArrayList;
29  import java.util.concurrent.CountDownLatch;
30  
31  import org.apache.commons.logging.Log;
32  import org.apache.commons.logging.LogFactory;
33  import org.apache.hadoop.hbase.classification.InterfaceAudience;
34  import org.apache.hadoop.conf.Configuration;
35  import org.apache.hadoop.hbase.Abortable;
36  import org.apache.hadoop.hbase.HConstants;
37  import org.apache.hadoop.hbase.HRegionInfo;
38  import org.apache.hadoop.hbase.ZooKeeperConnectionException;
39  import org.apache.zookeeper.KeeperException;
40  import org.apache.zookeeper.WatchedEvent;
41  import org.apache.zookeeper.Watcher;
42  import org.apache.zookeeper.ZooDefs;
43  import org.apache.zookeeper.data.ACL;
44  
45  /**
46   * Acts as the single ZooKeeper Watcher.  One instance of this is instantiated
47   * for each Master, RegionServer, and client process.
48   *
49   * <p>This is the only class that implements {@link Watcher}.  Other internal
50   * classes which need to be notified of ZooKeeper events must register with
51   * the local instance of this watcher via {@link #registerListener}.
52   *
53   * <p>This class also holds and manages the connection to ZooKeeper.  Code to
54   * deal with connection related events and exceptions are handled here.
55   */
56  @InterfaceAudience.Private
57  public class ZooKeeperWatcher implements Watcher, Abortable, Closeable {
58    private static final Log LOG = LogFactory.getLog(ZooKeeperWatcher.class);
59  
60    // Identifier for this watcher (for logging only).  It is made of the prefix
61    // passed on construction and the zookeeper sessionid.
62    private String prefix;
63    private String identifier;
64  
65    // zookeeper quorum
66    private String quorum;
67  
68    // zookeeper connection
69    private RecoverableZooKeeper recoverableZooKeeper;
70  
71    // abortable in case of zk failure
72    protected Abortable abortable;
73    // Used if abortable is null
74    private boolean aborted = false;
75  
76    // listeners to be notified
77    private final List<ZooKeeperListener> listeners =
78      new CopyOnWriteArrayList<ZooKeeperListener>();
79  
80    // Used by ZKUtil:waitForZKConnectionIfAuthenticating to wait for SASL
81    // negotiation to complete
82    public CountDownLatch saslLatch = new CountDownLatch(1);
83  
84    // node names
85  
86    // base znode for this cluster
87    public String baseZNode;
88    //znodes containing the locations of the servers hosting the meta replicas
89    private Map<Integer,String> metaReplicaZnodes = new HashMap<Integer, String>();
90    // znode containing ephemeral nodes of the regionservers
91    public String rsZNode;
92    // znode containing ephemeral nodes of the draining regionservers
93    public String drainingZNode;
94    // znode of currently active master
95    private String masterAddressZNode;
96    // znode of this master in backup master directory, if not the active master
97    public String backupMasterAddressesZNode;
98    // znode containing the current cluster state
99    public String clusterStateZNode;
100   // znode used for region transitioning and assignment
101   public String assignmentZNode;
102   // znode used for table disabling/enabling
103   public String tableZNode;
104   // znode containing the unique cluster ID
105   public String clusterIdZNode;
106   // znode used for log splitting work assignment
107   public String splitLogZNode;
108   // znode containing the state of the load balancer
109   public String balancerZNode;
110   // znode containing the lock for the tables
111   public String tableLockZNode;
112   // znode containing the state of recovering regions
113   public String recoveringRegionsZNode;
114   // znode containing namespace descriptors
115   public static String namespaceZNode = "namespace";
116 
117   // Certain ZooKeeper nodes need to be world-readable
118   public static final ArrayList<ACL> CREATOR_ALL_AND_WORLD_READABLE =
119     new ArrayList<ACL>() { {
120       add(new ACL(ZooDefs.Perms.READ,ZooDefs.Ids.ANYONE_ID_UNSAFE));
121       add(new ACL(ZooDefs.Perms.ALL,ZooDefs.Ids.AUTH_IDS));
122     }};
123 
124   public final static String META_ZNODE_PREFIX = "meta-region-server";
125 
126   private final Configuration conf;
127 
128   private final Exception constructorCaller;
129 
130   /**
131    * Instantiate a ZooKeeper connection and watcher.
132    * @param identifier string that is passed to RecoverableZookeeper to be used as
133    * identifier for this instance. Use null for default.
134    * @throws IOException
135    * @throws ZooKeeperConnectionException
136    */
137   public ZooKeeperWatcher(Configuration conf, String identifier,
138       Abortable abortable) throws ZooKeeperConnectionException, IOException {
139     this(conf, identifier, abortable, false);
140   }
141 
142   /**
143    * Instantiate a ZooKeeper connection and watcher.
144    * @param conf
145    * @param identifier string that is passed to RecoverableZookeeper to be used as identifier for
146    *          this instance. Use null for default.
147    * @param abortable Can be null if there is on error there is no host to abort: e.g. client
148    *          context.
149    * @param canCreateBaseZNode
150    * @throws IOException
151    * @throws ZooKeeperConnectionException
152    */
153   public ZooKeeperWatcher(Configuration conf, String identifier,
154       Abortable abortable, boolean canCreateBaseZNode)
155   throws IOException, ZooKeeperConnectionException {
156     this.conf = conf;
157     // Capture a stack trace now.  Will print it out later if problem so we can
158     // distingush amongst the myriad ZKWs.
159     try {
160       throw new Exception("ZKW CONSTRUCTOR STACK TRACE FOR DEBUGGING");
161     } catch (Exception e) {
162       this.constructorCaller = e;
163     }
164     this.quorum = ZKConfig.getZKQuorumServersString(conf);
165     this.prefix = identifier;
166     // Identifier will get the sessionid appended later below down when we
167     // handle the syncconnect event.
168     this.identifier = identifier + "0x0";
169     this.abortable = abortable;
170     setNodeNames(conf);
171     this.recoverableZooKeeper = ZKUtil.connect(conf, quorum, this, identifier);
172     if (canCreateBaseZNode) {
173       createBaseZNodes();
174     }
175   }
176 
177   private void createBaseZNodes() throws ZooKeeperConnectionException {
178     try {
179       // Create all the necessary "directories" of znodes
180       ZKUtil.createWithParents(this, baseZNode);
181       if (conf.getBoolean("hbase.assignment.usezk", true)) {
182         ZKUtil.createAndFailSilent(this, assignmentZNode);
183       }
184       ZKUtil.createAndFailSilent(this, rsZNode);
185       ZKUtil.createAndFailSilent(this, drainingZNode);
186       ZKUtil.createAndFailSilent(this, tableZNode);
187       ZKUtil.createAndFailSilent(this, splitLogZNode);
188       ZKUtil.createAndFailSilent(this, backupMasterAddressesZNode);
189       ZKUtil.createAndFailSilent(this, tableLockZNode);
190       ZKUtil.createAndFailSilent(this, recoveringRegionsZNode);
191     } catch (KeeperException e) {
192       throw new ZooKeeperConnectionException(
193           prefix("Unexpected KeeperException creating base node"), e);
194     }
195   }
196 
197   @Override
198   public String toString() {
199     return this.identifier + ", quorum=" + quorum + ", baseZNode=" + baseZNode;
200   }
201 
202   /**
203    * Adds this instance's identifier as a prefix to the passed <code>str</code>
204    * @param str String to amend.
205    * @return A new string with this instance's identifier as prefix: e.g.
206    * if passed 'hello world', the returned string could be
207    */
208   public String prefix(final String str) {
209     return this.toString() + " " + str;
210   }
211 
212   /**
213    * Set the local variable node names using the specified configuration.
214    */
215   private void setNodeNames(Configuration conf) {
216     baseZNode = conf.get(HConstants.ZOOKEEPER_ZNODE_PARENT,
217         HConstants.DEFAULT_ZOOKEEPER_ZNODE_PARENT);
218     metaReplicaZnodes.put(0, ZKUtil.joinZNode(baseZNode,
219            conf.get("zookeeper.znode.metaserver", "meta-region-server")));
220     int numMetaReplicas = conf.getInt(HConstants.META_REPLICAS_NUM,
221             HConstants.DEFAULT_META_REPLICA_NUM);
222     for (int i = 1; i < numMetaReplicas; i++) {
223       String str = ZKUtil.joinZNode(baseZNode,
224         conf.get("zookeeper.znode.metaserver", "meta-region-server") + "-" + i);
225       metaReplicaZnodes.put(i, str);
226     }
227     rsZNode = ZKUtil.joinZNode(baseZNode,
228         conf.get("zookeeper.znode.rs", "rs"));
229     drainingZNode = ZKUtil.joinZNode(baseZNode,
230         conf.get("zookeeper.znode.draining.rs", "draining"));
231     masterAddressZNode = ZKUtil.joinZNode(baseZNode,
232         conf.get("zookeeper.znode.master", "master"));
233     backupMasterAddressesZNode = ZKUtil.joinZNode(baseZNode,
234         conf.get("zookeeper.znode.backup.masters", "backup-masters"));
235     clusterStateZNode = ZKUtil.joinZNode(baseZNode,
236         conf.get("zookeeper.znode.state", "running"));
237     assignmentZNode = ZKUtil.joinZNode(baseZNode,
238         conf.get("zookeeper.znode.unassigned", "region-in-transition"));
239     tableZNode = ZKUtil.joinZNode(baseZNode,
240         conf.get("zookeeper.znode.tableEnableDisable", "table"));
241     clusterIdZNode = ZKUtil.joinZNode(baseZNode,
242         conf.get("zookeeper.znode.clusterId", "hbaseid"));
243     splitLogZNode = ZKUtil.joinZNode(baseZNode,
244         conf.get("zookeeper.znode.splitlog", HConstants.SPLIT_LOGDIR_NAME));
245     balancerZNode = ZKUtil.joinZNode(baseZNode,
246         conf.get("zookeeper.znode.balancer", "balancer"));
247     tableLockZNode = ZKUtil.joinZNode(baseZNode,
248         conf.get("zookeeper.znode.tableLock", "table-lock"));
249     recoveringRegionsZNode = ZKUtil.joinZNode(baseZNode,
250         conf.get("zookeeper.znode.recovering.regions", "recovering-regions"));
251     namespaceZNode = ZKUtil.joinZNode(baseZNode,
252         conf.get("zookeeper.znode.namespace", "namespace"));
253   }
254 
255   /**
256    * Is the znode of any meta replica
257    * @param node
258    * @return true or false
259    */
260   public boolean isAnyMetaReplicaZnode(String node) {
261     if (metaReplicaZnodes.values().contains(node)) {
262       return true;
263     }
264     return false;
265   }
266 
267   /**
268    * Is it the default meta replica's znode
269    * @param node
270    * @return true or false
271    */
272   public boolean isDefaultMetaReplicaZnode(String node) {
273     if (getZNodeForReplica(HRegionInfo.DEFAULT_REPLICA_ID).equals(node)) {
274       return true;
275     }
276     return false;
277   }
278 
279   /**
280    * Get the znodes corresponding to the meta replicas from ZK
281    * @return list of znodes
282    * @throws KeeperException
283    */
284   public List<String> getMetaReplicaNodes() throws KeeperException {
285     List<String> childrenOfBaseNode = ZKUtil.listChildrenNoWatch(this, baseZNode);
286     List<String> metaReplicaNodes = new ArrayList<String>(2);
287     String pattern = conf.get("zookeeper.znode.metaserver","meta-region-server");
288     for (String child : childrenOfBaseNode) {
289       if (child.startsWith(pattern)) metaReplicaNodes.add(child);
290     }
291     return metaReplicaNodes;
292   }
293 
294   /**
295    * Get the znode string corresponding to a replicaId
296    * @param replicaId
297    * @return znode
298    */
299   public String getZNodeForReplica(int replicaId) {
300     String str = metaReplicaZnodes.get(replicaId);
301     // return a newly created path but don't update the cache of paths
302     // This is mostly needed for tests that attempt to create meta replicas
303     // from outside the master
304     if (str == null) {
305       str = ZKUtil.joinZNode(baseZNode,
306           conf.get("zookeeper.znode.metaserver", "meta-region-server") + "-" + replicaId);
307     }
308     return str;
309   }
310 
311   /**
312    * Parse the meta replicaId from the passed znode
313    * @param znode
314    * @return replicaId
315    */
316   public int getMetaReplicaIdFromZnode(String znode) {
317     String pattern = conf.get("zookeeper.znode.metaserver","meta-region-server");
318     if (znode.equals(pattern)) return HRegionInfo.DEFAULT_REPLICA_ID;
319     // the non-default replicas are of the pattern meta-region-server-<replicaId>
320     String nonDefaultPattern = pattern + "-"; 
321     return Integer.parseInt(znode.substring(nonDefaultPattern.length()));
322   }
323 
324   /**
325    * Register the specified listener to receive ZooKeeper events.
326    * @param listener
327    */
328   public void registerListener(ZooKeeperListener listener) {
329     listeners.add(listener);
330   }
331 
332   /**
333    * Register the specified listener to receive ZooKeeper events and add it as
334    * the first in the list of current listeners.
335    * @param listener
336    */
337   public void registerListenerFirst(ZooKeeperListener listener) {
338     listeners.add(0, listener);
339   }
340 
341   public void unregisterListener(ZooKeeperListener listener) {
342     listeners.remove(listener);
343   }
344 
345   /**
346    * Clean all existing listeners
347    */
348   public void unregisterAllListeners() {
349     listeners.clear();
350   }
351 
352   /**
353    * Get a copy of current registered listeners
354    */
355   public List<ZooKeeperListener> getListeners() {
356     return new ArrayList<ZooKeeperListener>(listeners);
357   }
358 
359   /**
360    * @return The number of currently registered listeners
361    */
362   public int getNumberOfListeners() {
363     return listeners.size();
364   }
365 
366   /**
367    * Get the connection to ZooKeeper.
368    * @return connection reference to zookeeper
369    */
370   public RecoverableZooKeeper getRecoverableZooKeeper() {
371     return recoverableZooKeeper;
372   }
373 
374   public void reconnectAfterExpiration() throws IOException, KeeperException, InterruptedException {
375     recoverableZooKeeper.reconnectAfterExpiration();
376   }
377 
378   /**
379    * Get the quorum address of this instance.
380    * @return quorum string of this zookeeper connection instance
381    */
382   public String getQuorum() {
383     return quorum;
384   }
385 
386   /**
387    * @return the base znode of this zookeeper connection instance.
388    */
389   public String getBaseZNode() {
390     return baseZNode;
391   }
392 
393   /**
394    * Method called from ZooKeeper for events and connection status.
395    * <p>
396    * Valid events are passed along to listeners.  Connection status changes
397    * are dealt with locally.
398    */
399   @Override
400   public void process(WatchedEvent event) {
401     LOG.debug(prefix("Received ZooKeeper Event, " +
402         "type=" + event.getType() + ", " +
403         "state=" + event.getState() + ", " +
404         "path=" + event.getPath()));
405 
406     switch(event.getType()) {
407 
408       // If event type is NONE, this is a connection status change
409       case None: {
410         connectionEvent(event);
411         break;
412       }
413 
414       // Otherwise pass along to the listeners
415 
416       case NodeCreated: {
417         for(ZooKeeperListener listener : listeners) {
418           listener.nodeCreated(event.getPath());
419         }
420         break;
421       }
422 
423       case NodeDeleted: {
424         for(ZooKeeperListener listener : listeners) {
425           listener.nodeDeleted(event.getPath());
426         }
427         break;
428       }
429 
430       case NodeDataChanged: {
431         for(ZooKeeperListener listener : listeners) {
432           listener.nodeDataChanged(event.getPath());
433         }
434         break;
435       }
436 
437       case NodeChildrenChanged: {
438         for(ZooKeeperListener listener : listeners) {
439           listener.nodeChildrenChanged(event.getPath());
440         }
441         break;
442       }
443     }
444   }
445 
446   // Connection management
447 
448   /**
449    * Called when there is a connection-related event via the Watcher callback.
450    * <p>
451    * If Disconnected or Expired, this should shutdown the cluster. But, since
452    * we send a KeeperException.SessionExpiredException along with the abort
453    * call, it's possible for the Abortable to catch it and try to create a new
454    * session with ZooKeeper. This is what the client does in HCM.
455    * <p>
456    * @param event
457    */
458   private void connectionEvent(WatchedEvent event) {
459     switch(event.getState()) {
460       case SyncConnected:
461         // Now, this callback can be invoked before the this.zookeeper is set.
462         // Wait a little while.
463         long finished = System.currentTimeMillis() +
464           this.conf.getLong("hbase.zookeeper.watcher.sync.connected.wait", 2000);
465         while (System.currentTimeMillis() < finished) {
466           try {
467             Thread.sleep(1);
468           } catch (InterruptedException e) {
469             LOG.warn("Interrupted while sleeping");
470             throw new RuntimeException("Interrupted while waiting for" +
471                 " recoverableZooKeeper is set");
472           }
473           if (this.recoverableZooKeeper != null) break;
474         }
475 
476         if (this.recoverableZooKeeper == null) {
477           LOG.error("ZK is null on connection event -- see stack trace " +
478             "for the stack trace when constructor was called on this zkw",
479             this.constructorCaller);
480           throw new NullPointerException("ZK is null");
481         }
482         this.identifier = this.prefix + "-0x" +
483           Long.toHexString(this.recoverableZooKeeper.getSessionId());
484         // Update our identifier.  Otherwise ignore.
485         LOG.debug(this.identifier + " connected");
486         break;
487 
488       // Abort the server if Disconnected or Expired
489       case Disconnected:
490         LOG.debug(prefix("Received Disconnected from ZooKeeper, ignoring"));
491         break;
492 
493       case Expired:
494         String msg = prefix(this.identifier + " received expired from " +
495           "ZooKeeper, aborting");
496         // TODO: One thought is to add call to ZooKeeperListener so say,
497         // ZooKeeperNodeTracker can zero out its data values.
498         if (this.abortable != null) {
499           this.abortable.abort(msg, new KeeperException.SessionExpiredException());
500         }
501         break;
502 
503       case ConnectedReadOnly:
504       case SaslAuthenticated:
505       case AuthFailed:
506         break;
507 
508       default:
509         throw new IllegalStateException("Received event is not valid: " + event.getState());
510     }
511   }
512 
513   /**
514    * Forces a synchronization of this ZooKeeper client connection.
515    * <p>
516    * Executing this method before running other methods will ensure that the
517    * subsequent operations are up-to-date and consistent as of the time that
518    * the sync is complete.
519    * <p>
520    * This is used for compareAndSwap type operations where we need to read the
521    * data of an existing node and delete or transition that node, utilizing the
522    * previously read version and data.  We want to ensure that the version read
523    * is up-to-date from when we begin the operation.
524    */
525   public void sync(String path) throws KeeperException {
526     this.recoverableZooKeeper.sync(path, null, null);
527   }
528 
529   /**
530    * Handles KeeperExceptions in client calls.
531    * <p>
532    * This may be temporary but for now this gives one place to deal with these.
533    * <p>
534    * TODO: Currently this method rethrows the exception to let the caller handle
535    * <p>
536    * @param ke
537    * @throws KeeperException
538    */
539   public void keeperException(KeeperException ke)
540   throws KeeperException {
541     LOG.error(prefix("Received unexpected KeeperException, re-throwing exception"), ke);
542     throw ke;
543   }
544 
545   /**
546    * Handles InterruptedExceptions in client calls.
547    * <p>
548    * This may be temporary but for now this gives one place to deal with these.
549    * <p>
550    * TODO: Currently, this method does nothing.
551    *       Is this ever expected to happen?  Do we abort or can we let it run?
552    *       Maybe this should be logged as WARN?  It shouldn't happen?
553    * <p>
554    * @param ie
555    */
556   public void interruptedException(InterruptedException ie) {
557     LOG.debug(prefix("Received InterruptedException, doing nothing here"), ie);
558     // At least preserver interrupt.
559     Thread.currentThread().interrupt();
560     // no-op
561   }
562 
563   /**
564    * Close the connection to ZooKeeper.
565    *
566    * @throws InterruptedException
567    */
568   public void close() {
569     try {
570       if (recoverableZooKeeper != null) {
571         recoverableZooKeeper.close();
572       }
573     } catch (InterruptedException e) {
574       Thread.currentThread().interrupt();
575     }
576   }
577 
578   public Configuration getConfiguration() {
579     return conf;
580   }
581 
582   @Override
583   public void abort(String why, Throwable e) {
584     if (this.abortable != null) this.abortable.abort(why, e);
585     else this.aborted = true;
586   }
587 
588   @Override
589   public boolean isAborted() {
590     return this.abortable == null? this.aborted: this.abortable.isAborted();
591   }
592 
593   /**
594    * @return Path to the currently active master.
595    */
596   public String getMasterAddressZNode() {
597     return this.masterAddressZNode;
598   }
599 
600 }