001/*
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *     http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018package org.apache.hadoop.hbase.zookeeper;
019
020import java.util.LinkedList;
021import java.util.List;
022import org.apache.hadoop.conf.Configuration;
023import org.apache.hadoop.hbase.HBaseConfiguration;
024import org.apache.hadoop.hbase.HBaseInterfaceAudience;
025import org.apache.hadoop.hbase.HConstants;
026import org.apache.hadoop.hbase.ServerName;
027import org.apache.yetus.audience.InterfaceAudience;
028
029/**
030 * Tool for reading ZooKeeper servers from HBase XML configuration and producing a line-by-line list
031 * for use by bash scripts.
032 */
033@InterfaceAudience.LimitedPrivate(HBaseInterfaceAudience.TOOLS)
034public final class ZKServerTool {
035  private ZKServerTool() {
036  }
037
038  public static ServerName[] readZKNodes(Configuration conf) {
039    List<ServerName> hosts = new LinkedList<>();
040    String quorum = conf.get(HConstants.ZOOKEEPER_QUORUM, HConstants.LOCALHOST);
041
042    String[] values = quorum.split(",");
043    for (String value : values) {
044      String[] parts = value.split(":");
045      String host = parts[0];
046      int port = HConstants.DEFAULT_ZOOKEEPER_CLIENT_PORT;
047      if (parts.length > 1) {
048        port = Integer.parseInt(parts[1]);
049      }
050      hosts.add(ServerName.valueOf(host, port, -1));
051    }
052    return hosts.toArray(new ServerName[hosts.size()]);
053  }
054
055  /**
056   * Run the tool.
057   * @param args Command line arguments.
058   */
059  public static void main(String[] args) {
060    for (ServerName server : readZKNodes(HBaseConfiguration.create())) {
061      // bin/zookeeper.sh relies on the "ZK host" string for grepping which is case sensitive.
062      System.out.println("ZK host: " + server.getHostname());
063    }
064  }
065}