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 static org.apache.hadoop.hbase.HConstants.DEFAULT_ZK_SESSION_TIMEOUT;
22  import static org.apache.hadoop.hbase.HConstants.ZK_SESSION_TIMEOUT;
23  
24  import java.io.File;
25  import java.io.IOException;
26  import java.io.PrintWriter;
27  import java.net.InetAddress;
28  import java.net.NetworkInterface;
29  import java.net.UnknownHostException;
30  import java.util.ArrayList;
31  import java.util.Enumeration;
32  import java.util.List;
33  import java.util.Map.Entry;
34  import java.util.Properties;
35  
36  import org.apache.hadoop.conf.Configuration;
37  import org.apache.hadoop.hbase.HBaseConfiguration;
38  import org.apache.hadoop.hbase.HBaseInterfaceAudience;
39  import org.apache.hadoop.hbase.classification.InterfaceAudience;
40  import org.apache.hadoop.hbase.classification.InterfaceStability;
41  import org.apache.hadoop.hbase.util.Strings;
42  import org.apache.hadoop.net.DNS;
43  import org.apache.hadoop.util.StringUtils;
44  import org.apache.zookeeper.server.ServerConfig;
45  import org.apache.zookeeper.server.ZooKeeperServerMain;
46  import org.apache.zookeeper.server.quorum.QuorumPeerConfig;
47  import org.apache.zookeeper.server.quorum.QuorumPeerMain;
48  
49  /**
50   * HBase's version of ZooKeeper's QuorumPeer. When HBase is set to manage
51   * ZooKeeper, this class is used to start up QuorumPeer instances. By doing
52   * things in here rather than directly calling to ZooKeeper, we have more
53   * control over the process. This class uses {@link ZKConfig} to parse the
54   * zoo.cfg and inject variables from HBase's site.xml configuration in.
55   */
56  @InterfaceAudience.LimitedPrivate(HBaseInterfaceAudience.TOOLS)
57  @InterfaceStability.Evolving
58  public class HQuorumPeer {
59  
60    /**
61     * Parse ZooKeeper configuration from HBase XML config and run a QuorumPeer.
62     * @param args String[] of command line arguments. Not used.
63     */
64    public static void main(String[] args) {
65      Configuration conf = HBaseConfiguration.create();
66      try {
67        Properties zkProperties = ZKConfig.makeZKProps(conf);
68        writeMyID(zkProperties);
69        QuorumPeerConfig zkConfig = new QuorumPeerConfig();
70        zkConfig.parseProperties(zkProperties);
71  
72        // login the zookeeper server principal (if using security)
73        ZKUtil.loginServer(conf, "hbase.zookeeper.server.keytab.file",
74          "hbase.zookeeper.server.kerberos.principal",
75          zkConfig.getClientPortAddress().getHostName());
76  
77        runZKServer(zkConfig);
78      } catch (Exception e) {
79        e.printStackTrace();
80        System.exit(-1);
81      }
82    }
83  
84    private static void runZKServer(QuorumPeerConfig zkConfig) throws UnknownHostException, IOException {
85      if (zkConfig.isDistributed()) {
86        QuorumPeerMain qp = new QuorumPeerMain();
87        qp.runFromConfig(zkConfig);
88      } else {
89        ZooKeeperServerMain zk = new ZooKeeperServerMain();
90        ServerConfig serverConfig = new ServerConfig();
91        serverConfig.readFrom(zkConfig);
92        zk.runFromConfig(serverConfig);
93      }
94    }
95  
96    private static boolean addressIsLocalHost(String address) {
97      return address.equals("localhost") || address.equals("127.0.0.1");
98    }
99  
100   static void writeMyID(Properties properties) throws IOException {
101     long myId = -1;
102 
103     Configuration conf = HBaseConfiguration.create();
104     String myAddress = Strings.domainNamePointerToHostName(DNS.getDefaultHost(
105         conf.get("hbase.zookeeper.dns.interface","default"),
106         conf.get("hbase.zookeeper.dns.nameserver","default")));
107 
108     List<String> ips = new ArrayList<String>();
109 
110     // Add what could be the best (configured) match
111     ips.add(myAddress.contains(".") ?
112         myAddress :
113         StringUtils.simpleHostname(myAddress));
114 
115     // For all nics get all hostnames and IPs
116     Enumeration<?> nics = NetworkInterface.getNetworkInterfaces();
117     while(nics.hasMoreElements()) {
118       Enumeration<?> rawAdrs =
119           ((NetworkInterface)nics.nextElement()).getInetAddresses();
120       while(rawAdrs.hasMoreElements()) {
121         InetAddress inet = (InetAddress) rawAdrs.nextElement();
122         ips.add(StringUtils.simpleHostname(inet.getHostName()));
123         ips.add(inet.getHostAddress());
124       }
125     }
126 
127     for (Entry<Object, Object> entry : properties.entrySet()) {
128       String key = entry.getKey().toString().trim();
129       String value = entry.getValue().toString().trim();
130       if (key.startsWith("server.")) {
131         int dot = key.indexOf('.');
132         long id = Long.parseLong(key.substring(dot + 1));
133         String[] parts = value.split(":");
134         String address = parts[0];
135         if (addressIsLocalHost(address) || ips.contains(address)) {
136           myId = id;
137           break;
138         }
139       }
140     }
141 
142     // Set the max session timeout from the provided client-side timeout
143     properties.setProperty("maxSessionTimeout",
144       conf.get(ZK_SESSION_TIMEOUT, Integer.toString(DEFAULT_ZK_SESSION_TIMEOUT)));
145 
146     if (myId == -1) {
147       throw new IOException("Could not find my address: " + myAddress +
148                             " in list of ZooKeeper quorum servers");
149     }
150 
151     String dataDirStr = properties.get("dataDir").toString().trim();
152     File dataDir = new File(dataDirStr);
153     if (!dataDir.isDirectory()) {
154       if (!dataDir.mkdirs()) {
155         throw new IOException("Unable to create data dir " + dataDir);
156       }
157     }
158 
159     File myIdFile = new File(dataDir, "myid");
160     PrintWriter w = new PrintWriter(myIdFile);
161     w.println(myId);
162     w.close();
163   }
164 }