View Javadoc

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