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.admin.AdminServer;
046import org.apache.zookeeper.server.quorum.QuorumPeerConfig;
047import org.apache.zookeeper.server.quorum.QuorumPeerMain;
048
049/**
050 * HBase's version of ZooKeeper's QuorumPeer. When HBase is set to manage
051 * ZooKeeper, this class is used to start up QuorumPeer instances. By doing
052 * things in here rather than directly calling to ZooKeeper, we have more
053 * control over the process. This class uses {@link ZKConfig} to get settings
054 * from the hbase-site.xml file.
055 */
056@InterfaceAudience.LimitedPrivate(HBaseInterfaceAudience.TOOLS)
057@InterfaceStability.Evolving
058public final class HQuorumPeer {
059  private HQuorumPeer() {
060  }
061
062  /**
063   * Parse ZooKeeper configuration from HBase XML config and run a QuorumPeer.
064   * @param args String[] of command line arguments. Not used.
065   */
066  public static void main(String[] args) {
067    Configuration conf = HBaseConfiguration.create();
068    try {
069      Properties zkProperties = ZKConfig.makeZKProps(conf);
070      writeMyID(zkProperties);
071      QuorumPeerConfig zkConfig = new QuorumPeerConfig();
072      zkConfig.parseProperties(zkProperties);
073
074      // login the zookeeper server principal (if using security)
075      ZKUtil.loginServer(conf, HConstants.ZK_SERVER_KEYTAB_FILE,
076        HConstants.ZK_SERVER_KERBEROS_PRINCIPAL,
077        zkConfig.getClientPortAddress().getHostName());
078
079      runZKServer(zkConfig);
080    } catch (Exception e) {
081      e.printStackTrace();
082      System.exit(-1);
083    }
084  }
085
086  private static void runZKServer(QuorumPeerConfig zkConfig)
087          throws IOException, AdminServer.AdminServerException {
088    if (zkConfig.isDistributed()) {
089      QuorumPeerMain qp = new QuorumPeerMain();
090      qp.runFromConfig(zkConfig);
091    } else {
092      ZooKeeperServerMain zk = new ZooKeeperServerMain();
093      ServerConfig serverConfig = new ServerConfig();
094      serverConfig.readFrom(zkConfig);
095      zk.runFromConfig(serverConfig);
096    }
097  }
098
099  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<>();
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", conf.get(HConstants.ZK_SESSION_TIMEOUT,
147            Integer.toString(HConstants.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}