1 /*
2 * Copyright 2011 The Apache Software Foundation
3 *
4 * Licensed to the Apache Software Foundation (ASF) under one
5 * or more contributor license agreements. See the NOTICE file
6 * distributed with this work for additional information
7 * regarding copyright ownership. The ASF licenses this file
8 * to you under the Apache License, Version 2.0 (the
9 * "License"); you may not use this file except in compliance
10 * with the License. You may obtain a copy of the License at
11 *
12 * http://www.apache.org/licenses/LICENSE-2.0
13 *
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
19 */
20
21 package org.apache.hadoop.hbase.zookeeper;
22
23 import org.apache.hadoop.hbase.Abortable;
24 import org.apache.hadoop.hbase.util.Bytes;
25 import org.apache.zookeeper.KeeperException;
26
27 /**
28 * Publishes and synchronizes a unique identifier specific to a given HBase
29 * cluster. The stored identifier is read from the file system by the active
30 * master on startup, and is subsequently available to all watchers (including
31 * clients).
32 */
33 public class ClusterId {
34 private ZooKeeperWatcher watcher;
35 private Abortable abortable;
36 private String id;
37
38 public ClusterId(ZooKeeperWatcher watcher, Abortable abortable) {
39 this.watcher = watcher;
40 this.abortable = abortable;
41 }
42
43 public boolean hasId() {
44 return getId() != null;
45 }
46
47 public String getId() {
48 try {
49 if (id == null) {
50 id = readClusterIdZNode(watcher);
51 }
52 } catch (KeeperException ke) {
53 abortable.abort("Unexpected exception from ZooKeeper reading cluster ID",
54 ke);
55 }
56 return id;
57 }
58
59 public static String readClusterIdZNode(ZooKeeperWatcher watcher)
60 throws KeeperException {
61 if (ZKUtil.checkExists(watcher, watcher.clusterIdZNode) != -1) {
62 byte[] data = ZKUtil.getData(watcher, watcher.clusterIdZNode);
63 if (data != null) {
64 return Bytes.toString(data);
65 }
66 }
67 return null;
68 }
69
70 public static void setClusterId(ZooKeeperWatcher watcher, String id)
71 throws KeeperException {
72 ZKUtil.createSetData(watcher, watcher.clusterIdZNode, Bytes.toBytes(id));
73 }
74 }