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  
20  package org.apache.hadoop.hbase.zookeeper;
21  
22  import org.apache.hadoop.classification.InterfaceAudience;
23  import org.apache.hadoop.hbase.Abortable;
24  import org.apache.hadoop.hbase.ClusterId;
25  import org.apache.hadoop.hbase.exceptions.DeserializationException;
26  import org.apache.zookeeper.KeeperException;
27  
28  /**
29   * Publishes and synchronizes a unique identifier specific to a given HBase
30   * cluster.  The stored identifier is read from the file system by the active
31   * master on startup, and is subsequently available to all watchers (including
32   * clients).
33   */
34  @InterfaceAudience.Private
35  public class ZKClusterId {
36    private ZooKeeperWatcher watcher;
37    private Abortable abortable;
38    private String id;
39  
40    public ZKClusterId(ZooKeeperWatcher watcher, Abortable abortable) {
41      this.watcher = watcher;
42      this.abortable = abortable;
43    }
44  
45    public boolean hasId() {
46      return getId() != null;
47    }
48  
49    public String getId() {
50      try {
51        if (id == null) {
52          id = readClusterIdZNode(watcher);
53        }
54      } catch (KeeperException ke) {
55        abortable.abort("Unexpected exception from ZooKeeper reading cluster ID",
56            ke);
57      }
58      return id;
59    }
60  
61    public static String readClusterIdZNode(ZooKeeperWatcher watcher)
62    throws KeeperException {
63      if (ZKUtil.checkExists(watcher, watcher.clusterIdZNode) != -1) {
64        byte [] data = ZKUtil.getData(watcher, watcher.clusterIdZNode);
65        if (data != null) {
66          try {
67            return ClusterId.parseFrom(data).toString();
68          } catch (DeserializationException e) {
69            throw ZKUtil.convert(e);
70          }
71        }
72      }
73      return null;
74    }
75  
76    public static void setClusterId(ZooKeeperWatcher watcher, ClusterId id)
77        throws KeeperException {
78      ZKUtil.createSetData(watcher, watcher.clusterIdZNode, id.toByteArray());
79    }
80  }