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 java.io.IOException;
22  import java.io.InputStream;
23  import java.util.ArrayList;
24  import java.util.List;
25  import java.util.Map.Entry;
26  import java.util.Properties;
27  
28  import org.apache.commons.logging.Log;
29  import org.apache.commons.logging.LogFactory;
30  import org.apache.hadoop.conf.Configuration;
31  import org.apache.hadoop.hbase.HConstants;
32  import org.apache.hadoop.hbase.classification.InterfaceAudience;
33  
34  /**
35   * Utility methods for reading, and building the ZooKeeper configuration.
36   */
37  @InterfaceAudience.Private
38  public class ZKConfig {
39    private static final Log LOG = LogFactory.getLog(ZKConfig.class);
40  
41    private static final String VARIABLE_START = "${";
42    private static final int VARIABLE_START_LENGTH = VARIABLE_START.length();
43    private static final String VARIABLE_END = "}";
44    private static final int VARIABLE_END_LENGTH = VARIABLE_END.length();
45  
46    /**
47     * Make a Properties object holding ZooKeeper config.
48     * Parses the corresponding config options from the HBase XML configs
49     * and generates the appropriate ZooKeeper properties.
50     * @param conf Configuration to read from.
51     * @return Properties holding mappings representing ZooKeeper config file.
52     */
53    public static Properties makeZKProps(Configuration conf) {
54      if (conf.getBoolean(HConstants.HBASE_CONFIG_READ_ZOOKEEPER_CONFIG, false)) {
55        LOG.warn(
56            "Parsing ZooKeeper's " + HConstants.ZOOKEEPER_CONFIG_NAME +
57            " file for ZK properties " +
58            "has been deprecated. Please instead place all ZK related HBase " +
59            "configuration under the hbase-site.xml, using prefixes " +
60            "of the form '" + HConstants.ZK_CFG_PROPERTY_PREFIX + "', and " +
61            "set property '" + HConstants.HBASE_CONFIG_READ_ZOOKEEPER_CONFIG +
62            "' to false");
63        // First check if there is a zoo.cfg in the CLASSPATH. If so, simply read
64        // it and grab its configuration properties.
65        ClassLoader cl = HQuorumPeer.class.getClassLoader();
66        final InputStream inputStream =
67          cl.getResourceAsStream(HConstants.ZOOKEEPER_CONFIG_NAME);
68        if (inputStream != null) {
69          try {
70            return parseZooCfg(conf, inputStream);
71          } catch (IOException e) {
72            LOG.warn("Cannot read " + HConstants.ZOOKEEPER_CONFIG_NAME +
73                     ", loading from XML files", e);
74          }
75        }
76      } else {
77        if (LOG.isTraceEnabled()) {
78          LOG.trace("Skipped reading ZK properties file '" + HConstants.ZOOKEEPER_CONFIG_NAME +
79            "' since '" + HConstants.HBASE_CONFIG_READ_ZOOKEEPER_CONFIG + "' was not set to true");
80        }
81      }
82  
83      // Otherwise, use the configuration options from HBase's XML files.
84      Properties zkProperties = new Properties();
85  
86      // Directly map all of the hbase.zookeeper.property.KEY properties.
87      for (Entry<String, String> entry : new Configuration(conf)) { // copy for mt safety
88        String key = entry.getKey();
89        if (key.startsWith(HConstants.ZK_CFG_PROPERTY_PREFIX)) {
90          String zkKey = key.substring(HConstants.ZK_CFG_PROPERTY_PREFIX_LEN);
91          String value = entry.getValue();
92          // If the value has variables substitutions, need to do a get.
93          if (value.contains(VARIABLE_START)) {
94            value = conf.get(key);
95          }
96          zkProperties.put(zkKey, value);
97        }
98      }
99  
100     // If clientPort is not set, assign the default.
101     if (zkProperties.getProperty(HConstants.CLIENT_PORT_STR) == null) {
102       zkProperties.put(HConstants.CLIENT_PORT_STR,
103           HConstants.DEFAULT_ZOOKEPER_CLIENT_PORT);
104     }
105 
106     // Create the server.X properties.
107     int peerPort = conf.getInt("hbase.zookeeper.peerport", 2888);
108     int leaderPort = conf.getInt("hbase.zookeeper.leaderport", 3888);
109 
110     final String[] serverHosts = conf.getStrings(HConstants.ZOOKEEPER_QUORUM,
111                                                  HConstants.LOCALHOST);
112     for (int i = 0; i < serverHosts.length; ++i) {
113       String serverHost = serverHosts[i];
114       String address = serverHost + ":" + peerPort + ":" + leaderPort;
115       String key = "server." + i;
116       zkProperties.put(key, address);
117     }
118 
119     return zkProperties;
120   }
121 
122   /**
123    * Parse ZooKeeper's zoo.cfg, injecting HBase Configuration variables in.
124    * This method is used for testing so we can pass our own InputStream.
125    * @param conf HBaseConfiguration to use for injecting variables.
126    * @param inputStream InputStream to read from.
127    * @return Properties parsed from config stream with variables substituted.
128    * @throws IOException if anything goes wrong parsing config
129    * @deprecated in 0.96 onwards. HBase will no longer rely on zoo.cfg
130    * availability.
131    */
132   @Deprecated
133   public static Properties parseZooCfg(Configuration conf,
134       InputStream inputStream) throws IOException {
135     Properties properties = new Properties();
136     try {
137       properties.load(inputStream);
138     } catch (IOException e) {
139       final String msg = "fail to read properties from "
140         + HConstants.ZOOKEEPER_CONFIG_NAME;
141       LOG.fatal(msg);
142       throw new IOException(msg, e);
143     }
144     for (Entry<Object, Object> entry : properties.entrySet()) {
145       String value = entry.getValue().toString().trim();
146       String key = entry.getKey().toString().trim();
147       StringBuilder newValue = new StringBuilder();
148       int varStart = value.indexOf(VARIABLE_START);
149       int varEnd = 0;
150       while (varStart != -1) {
151         varEnd = value.indexOf(VARIABLE_END, varStart);
152         if (varEnd == -1) {
153           String msg = "variable at " + varStart + " has no end marker";
154           LOG.fatal(msg);
155           throw new IOException(msg);
156         }
157         String variable = value.substring(varStart + VARIABLE_START_LENGTH, varEnd);
158 
159         String substituteValue = System.getProperty(variable);
160         if (substituteValue == null) {
161           substituteValue = conf.get(variable);
162         }
163         if (substituteValue == null) {
164           String msg = "variable " + variable + " not set in system property "
165                      + "or hbase configs";
166           LOG.fatal(msg);
167           throw new IOException(msg);
168         }
169 
170         newValue.append(substituteValue);
171 
172         varEnd += VARIABLE_END_LENGTH;
173         varStart = value.indexOf(VARIABLE_START, varEnd);
174       }
175       // Special case for 'hbase.cluster.distributed' property being 'true'
176       if (key.startsWith("server.")) {
177         boolean mode = conf.getBoolean(HConstants.CLUSTER_DISTRIBUTED, HConstants.DEFAULT_CLUSTER_DISTRIBUTED);
178         if (mode == HConstants.CLUSTER_IS_DISTRIBUTED && value.startsWith(HConstants.LOCALHOST)) {
179           String msg = "The server in zoo.cfg cannot be set to localhost " +
180               "in a fully-distributed setup because it won't be reachable. " +
181               "See \"Getting Started\" for more information.";
182           LOG.fatal(msg);
183           throw new IOException(msg);
184         }
185       }
186       newValue.append(value.substring(varEnd));
187       properties.setProperty(key, newValue.toString());
188     }
189     return properties;
190   }
191 
192   /**
193    * Return the ZK Quorum servers string given zk properties returned by
194    * makeZKProps
195    * @param properties
196    * @return Quorum servers String
197    */
198   public static String getZKQuorumServersString(Properties properties) {
199     String clientPort = null;
200     List<String> servers = new ArrayList<String>();
201 
202     // The clientPort option may come after the server.X hosts, so we need to
203     // grab everything and then create the final host:port comma separated list.
204     boolean anyValid = false;
205     for (Entry<Object,Object> property : properties.entrySet()) {
206       String key = property.getKey().toString().trim();
207       String value = property.getValue().toString().trim();
208       if (key.equals("clientPort")) {
209         clientPort = value;
210       }
211       else if (key.startsWith("server.")) {
212         String host = value.substring(0, value.indexOf(':'));
213         servers.add(host);
214         anyValid = true;
215       }
216     }
217 
218     if (!anyValid) {
219       LOG.error("no valid quorum servers found in " + HConstants.ZOOKEEPER_CONFIG_NAME);
220       return null;
221     }
222 
223     if (clientPort == null) {
224       LOG.error("no clientPort found in " + HConstants.ZOOKEEPER_CONFIG_NAME);
225       return null;
226     }
227 
228     if (servers.isEmpty()) {
229       LOG.fatal("No servers were found in provided ZooKeeper configuration. " +
230           "HBase must have a ZooKeeper cluster configured for its " +
231           "operation. Ensure that you've configured '" +
232           HConstants.ZOOKEEPER_QUORUM + "' properly.");
233       return null;
234     }
235 
236     StringBuilder hostPortBuilder = new StringBuilder();
237     for (int i = 0; i < servers.size(); ++i) {
238       String host = servers.get(i);
239       if (i > 0) {
240         hostPortBuilder.append(',');
241       }
242       hostPortBuilder.append(host);
243       hostPortBuilder.append(':');
244       hostPortBuilder.append(clientPort);
245     }
246 
247     return hostPortBuilder.toString();
248   }
249 
250   /**
251    * Return the ZK Quorum servers string given the specified configuration.
252    * @param conf
253    * @return Quorum servers
254    */
255   public static String getZKQuorumServersString(Configuration conf) {
256     return getZKQuorumServersString(makeZKProps(conf));
257   }
258 }