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