001/*
002 *
003 * Licensed to the Apache Software Foundation (ASF) under one
004 * or more contributor license agreements.  See the NOTICE file
005 * distributed with this work for additional information
006 * regarding copyright ownership.  The ASF licenses this file
007 * to you under the Apache License, Version 2.0 (the
008 * "License"); you may not use this file except in compliance
009 * with the License.  You may obtain a copy of the License at
010 *
011 *     http://www.apache.org/licenses/LICENSE-2.0
012 *
013 * Unless required by applicable law or agreed to in writing, software
014 * distributed under the License is distributed on an "AS IS" BASIS,
015 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
016 * See the License for the specific language governing permissions and
017 * limitations under the License.
018 */
019package org.apache.hadoop.hbase.zookeeper;
020
021import java.io.File;
022import java.io.IOException;
023import java.io.PrintWriter;
024import java.net.InetAddress;
025import java.net.NetworkInterface;
026import java.net.UnknownHostException;
027import java.nio.charset.StandardCharsets;
028import java.util.ArrayList;
029import java.util.Enumeration;
030import java.util.List;
031import java.util.Map.Entry;
032import java.util.Properties;
033
034import org.apache.hadoop.conf.Configuration;
035import org.apache.hadoop.hbase.HBaseConfiguration;
036import org.apache.hadoop.hbase.HBaseInterfaceAudience;
037import org.apache.hadoop.hbase.HConstants;
038import org.apache.hadoop.hbase.util.DNS;
039import org.apache.hadoop.hbase.util.Strings;
040import org.apache.hadoop.util.StringUtils;
041import org.apache.yetus.audience.InterfaceAudience;
042import org.apache.yetus.audience.InterfaceStability;
043import org.apache.zookeeper.server.ServerConfig;
044import org.apache.zookeeper.server.ZooKeeperServerMain;
045import org.apache.zookeeper.server.quorum.QuorumPeerConfig;
046import org.apache.zookeeper.server.quorum.QuorumPeerMain;
047
048/**
049 * HBase's version of ZooKeeper's QuorumPeer. When HBase is set to manage
050 * ZooKeeper, this class is used to start up QuorumPeer instances. By doing
051 * things in here rather than directly calling to ZooKeeper, we have more
052 * control over the process. This class uses {@link ZKConfig} to get settings
053 * from the hbase-site.xml file.
054 */
055@InterfaceAudience.LimitedPrivate(HBaseInterfaceAudience.TOOLS)
056@InterfaceStability.Evolving
057public final class HQuorumPeer {
058  private HQuorumPeer() {
059  }
060
061  /**
062   * Parse ZooKeeper configuration from HBase XML config and run a QuorumPeer.
063   * @param args String[] of command line arguments. Not used.
064   */
065  public static void main(String[] args) {
066    Configuration conf = HBaseConfiguration.create();
067    try {
068      Properties zkProperties = ZKConfig.makeZKProps(conf);
069      writeMyID(zkProperties);
070      QuorumPeerConfig zkConfig = new QuorumPeerConfig();
071      zkConfig.parseProperties(zkProperties);
072
073      // login the zookeeper server principal (if using security)
074      ZKUtil.loginServer(conf, HConstants.ZK_SERVER_KEYTAB_FILE,
075        HConstants.ZK_SERVER_KERBEROS_PRINCIPAL,
076        zkConfig.getClientPortAddress().getHostName());
077
078      runZKServer(zkConfig);
079    } catch (Exception e) {
080      e.printStackTrace();
081      System.exit(-1);
082    }
083  }
084
085  private static void runZKServer(QuorumPeerConfig zkConfig)
086          throws UnknownHostException, IOException {
087    if (zkConfig.isDistributed()) {
088      QuorumPeerMain qp = new QuorumPeerMain();
089      qp.runFromConfig(zkConfig);
090    } else {
091      ZooKeeperServerMain zk = new ZooKeeperServerMain();
092      ServerConfig serverConfig = new ServerConfig();
093      serverConfig.readFrom(zkConfig);
094      zk.runFromConfig(serverConfig);
095    }
096  }
097
098  private static boolean addressIsLocalHost(String address) {
099    return address.equals("localhost") || address.equals("127.0.0.1");
100  }
101
102  static void writeMyID(Properties properties) throws IOException {
103    long myId = -1;
104
105    Configuration conf = HBaseConfiguration.create();
106    String myAddress = Strings.domainNamePointerToHostName(DNS.getDefaultHost(
107        conf.get("hbase.zookeeper.dns.interface","default"),
108        conf.get("hbase.zookeeper.dns.nameserver","default")));
109
110    List<String> ips = new ArrayList<>();
111
112    // Add what could be the best (configured) match
113    ips.add(myAddress.contains(".") ?
114        myAddress :
115        StringUtils.simpleHostname(myAddress));
116
117    // For all nics get all hostnames and IPs
118    Enumeration<?> nics = NetworkInterface.getNetworkInterfaces();
119    while(nics.hasMoreElements()) {
120      Enumeration<?> rawAdrs =
121          ((NetworkInterface)nics.nextElement()).getInetAddresses();
122      while(rawAdrs.hasMoreElements()) {
123        InetAddress inet = (InetAddress) rawAdrs.nextElement();
124        ips.add(StringUtils.simpleHostname(inet.getHostName()));
125        ips.add(inet.getHostAddress());
126      }
127    }
128
129    for (Entry<Object, Object> entry : properties.entrySet()) {
130      String key = entry.getKey().toString().trim();
131      String value = entry.getValue().toString().trim();
132      if (key.startsWith("server.")) {
133        int dot = key.indexOf('.');
134        long id = Long.parseLong(key.substring(dot + 1));
135        String[] parts = value.split(":");
136        String address = parts[0];
137        if (addressIsLocalHost(address) || ips.contains(address)) {
138          myId = id;
139          break;
140        }
141      }
142    }
143
144    // Set the max session timeout from the provided client-side timeout
145    properties.setProperty("maxSessionTimeout", conf.get(HConstants.ZK_SESSION_TIMEOUT,
146            Integer.toString(HConstants.DEFAULT_ZK_SESSION_TIMEOUT)));
147
148    if (myId == -1) {
149      throw new IOException("Could not find my address: " + myAddress +
150                            " in list of ZooKeeper quorum servers");
151    }
152
153    String dataDirStr = properties.get("dataDir").toString().trim();
154    File dataDir = new File(dataDirStr);
155    if (!dataDir.isDirectory()) {
156      if (!dataDir.mkdirs()) {
157        throw new IOException("Unable to create data dir " + dataDir);
158      }
159    }
160
161    File myIdFile = new File(dataDir, "myid");
162    PrintWriter w = new PrintWriter(myIdFile, StandardCharsets.UTF_8.name());
163    w.println(myId);
164    w.close();
165  }
166}