1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.apache.hadoop.hbase.master;
21
22 import org.apache.commons.logging.Log;
23 import org.apache.commons.logging.LogFactory;
24 import org.apache.hadoop.hbase.HServerAddress;
25 import org.apache.hadoop.hbase.zookeeper.ZooKeeperWrapper;
26 import org.apache.zookeeper.WatchedEvent;
27 import org.apache.zookeeper.Watcher;
28 import org.apache.zookeeper.Watcher.Event.EventType;
29
30 import java.util.concurrent.atomic.AtomicBoolean;
31
32
33
34
35
36
37
38
39
40
41
42 class ZKMasterAddressWatcher implements Watcher {
43 private static final Log LOG = LogFactory.getLog(ZKMasterAddressWatcher.class);
44
45 private ZooKeeperWrapper zookeeper;
46 private final AtomicBoolean requestShutdown;
47
48
49
50
51
52
53 ZKMasterAddressWatcher(final ZooKeeperWrapper zk, final AtomicBoolean flag) {
54 this.requestShutdown = flag;
55 this.zookeeper = zk;
56 }
57
58
59
60
61 @Override
62 public synchronized void process (WatchedEvent event) {
63 EventType type = event.getType();
64 LOG.debug(("Got event " + type + " with path " + event.getPath()));
65 if (type.equals(EventType.NodeDeleted)) {
66 if (event.getPath().equals(this.zookeeper.clusterStateZNode)) {
67 LOG.info("Cluster shutdown while waiting, shutting down" +
68 " this master.");
69 this.requestShutdown.set(true);
70 } else {
71 LOG.debug("Master address ZNode deleted, notifying waiting masters");
72 notifyAll();
73 }
74 } else if(type.equals(EventType.NodeCreated) &&
75 event.getPath().equals(this.zookeeper.clusterStateZNode)) {
76 LOG.debug("Resetting watch on cluster state node.");
77 this.zookeeper.setClusterStateWatch(this);
78 }
79 }
80
81
82
83
84
85 public synchronized void waitForMasterAddressAvailability() {
86 while (zookeeper.readMasterAddress(this) != null) {
87 try {
88 LOG.debug("Waiting for master address ZNode to be deleted " +
89 "(Also watching cluster state node)");
90 this.zookeeper.setClusterStateWatch(this);
91 wait();
92 } catch (InterruptedException e) {
93 }
94 }
95 }
96
97
98
99
100
101
102 boolean writeAddressToZooKeeper(
103 final HServerAddress address, boolean retry) {
104 do {
105 waitForMasterAddressAvailability();
106
107 if (this.requestShutdown.get()) {
108 LOG.debug("Won't start Master because cluster is shuting down");
109 return false;
110 }
111 if(this.zookeeper.writeMasterAddress(address)) {
112 this.zookeeper.setClusterState(true);
113 this.zookeeper.setClusterStateWatch(this);
114
115 this.zookeeper.readMasterAddress(this);
116 return true;
117 }
118 } while(retry);
119 return false;
120 }
121
122
123
124
125
126 public void setZookeeper(ZooKeeperWrapper zookeeper) {
127 this.zookeeper = zookeeper;
128 }
129 }