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.client;
019
020import static org.apache.hadoop.hbase.HConstants.MASTER_ADDRS_KEY;
021import static org.apache.hadoop.hbase.util.DNS.getHostname;
022
023import com.google.errorprone.annotations.RestrictedApi;
024import java.io.IOException;
025import java.net.UnknownHostException;
026import java.util.HashSet;
027import java.util.Set;
028import java.util.concurrent.CompletableFuture;
029import java.util.stream.Collectors;
030import org.apache.hadoop.conf.Configuration;
031import org.apache.hadoop.hbase.HConstants;
032import org.apache.hadoop.hbase.ServerName;
033import org.apache.hadoop.hbase.security.User;
034import org.apache.hadoop.hbase.util.DNS.ServerType;
035import org.apache.yetus.audience.InterfaceAudience;
036
037import org.apache.hbase.thirdparty.com.google.common.base.Preconditions;
038import org.apache.hbase.thirdparty.com.google.common.base.Splitter;
039import org.apache.hbase.thirdparty.com.google.common.base.Strings;
040import org.apache.hbase.thirdparty.com.google.common.net.HostAndPort;
041
042import org.apache.hadoop.hbase.shaded.protobuf.ProtobufUtil;
043import org.apache.hadoop.hbase.shaded.protobuf.generated.RegistryProtos.GetMastersRequest;
044import org.apache.hadoop.hbase.shaded.protobuf.generated.RegistryProtos.GetMastersResponse;
045
046/**
047 * Master based registry implementation. Makes RPCs to the configured master addresses from config
048 * {@value org.apache.hadoop.hbase.HConstants#MASTER_ADDRS_KEY}.
049 * <p/>
050 * It supports hedged reads, set the fan out of the requests batch by
051 * {@link #MASTER_REGISTRY_HEDGED_REQS_FANOUT_KEY} to a value greater than {@code 1} will enable
052 * it(the default value is {@link AbstractRpcBasedConnectionRegistry#HEDGED_REQS_FANOUT_DEFAULT}).
053 * <p/>
054 * @deprecated Since 2.5.0, will be removed in 4.0.0. Use {@link RpcConnectionRegistry} instead.
055 */
056@Deprecated
057@InterfaceAudience.Private
058public class MasterRegistry extends AbstractRpcBasedConnectionRegistry {
059
060  /** Configuration key that controls the fan out of requests **/
061  public static final String MASTER_REGISTRY_HEDGED_REQS_FANOUT_KEY =
062    "hbase.client.master_registry.hedged.fanout";
063
064  public static final String MASTER_REGISTRY_INITIAL_REFRESH_DELAY_SECS =
065    "hbase.client.master_registry.initial_refresh_delay_secs";
066
067  public static final String MASTER_REGISTRY_PERIODIC_REFRESH_INTERVAL_SECS =
068    "hbase.client.master_registry.refresh_interval_secs";
069
070  public static final String MASTER_REGISTRY_MIN_SECS_BETWEEN_REFRESHES =
071    "hbase.client.master_registry.min_secs_between_refreshes";
072
073  private static final String MASTER_ADDRS_CONF_SEPARATOR = ",";
074
075  /**
076   * Supplies the default master port we should use given the provided configuration.
077   * @param conf Configuration to parse from.
078   */
079  private static int getDefaultMasterPort(Configuration conf) {
080    final int port = conf.getInt(HConstants.MASTER_PORT, HConstants.DEFAULT_MASTER_PORT);
081    if (port == 0) {
082      // Master port may be set to 0. We should substitute the default port in that case.
083      return HConstants.DEFAULT_MASTER_PORT;
084    }
085    return port;
086  }
087
088  /**
089   * Parses the list of master addresses from the provided configuration. Supported format is comma
090   * separated host[:port] values. If no port number if specified, default master port is assumed.
091   * @param conf Configuration to parse from.
092   */
093  public static Set<ServerName> parseMasterAddrs(Configuration conf) throws UnknownHostException {
094    final int defaultPort = getDefaultMasterPort(conf);
095    final Set<ServerName> masterAddrs = new HashSet<>();
096    final String configuredMasters = getMasterAddr(conf);
097    for (String masterAddr : Splitter.onPattern(MASTER_ADDRS_CONF_SEPARATOR)
098      .split(configuredMasters)) {
099      final HostAndPort masterHostPort =
100        HostAndPort.fromString(masterAddr.trim()).withDefaultPort(defaultPort);
101      masterAddrs.add(ServerName.valueOf(masterHostPort.toString(), ServerName.NON_STARTCODE));
102    }
103    Preconditions.checkArgument(!masterAddrs.isEmpty(), "At least one master address is needed");
104    return masterAddrs;
105  }
106
107  private final String connectionString;
108
109  MasterRegistry(Configuration conf, User user) throws IOException {
110    super(conf, user, MASTER_REGISTRY_HEDGED_REQS_FANOUT_KEY,
111      MASTER_REGISTRY_INITIAL_REFRESH_DELAY_SECS, MASTER_REGISTRY_PERIODIC_REFRESH_INTERVAL_SECS,
112      MASTER_REGISTRY_MIN_SECS_BETWEEN_REFRESHES);
113    connectionString = getConnectionString(conf);
114  }
115
116  @Override
117  protected Set<ServerName> getBootstrapNodes(Configuration conf) throws IOException {
118    return parseMasterAddrs(conf);
119  }
120
121  @Override
122  protected CompletableFuture<Set<ServerName>> fetchEndpoints() {
123    return getMasters();
124  }
125
126  @Override
127  public String getConnectionString() {
128    return connectionString;
129  }
130
131  static String getConnectionString(Configuration conf) throws UnknownHostException {
132    return getMasterAddr(conf);
133  }
134
135  /**
136   * Builds the default master address end point if it is not specified in the configuration.
137   * <p/>
138   * Will be called in {@code HBaseTestingUtility}.
139   */
140  public static String getMasterAddr(Configuration conf) throws UnknownHostException {
141    String masterAddrFromConf = conf.get(MASTER_ADDRS_KEY);
142    if (!Strings.isNullOrEmpty(masterAddrFromConf)) {
143      return masterAddrFromConf;
144    }
145    String hostname = getHostname(conf, ServerType.MASTER);
146    int port = conf.getInt(HConstants.MASTER_PORT, HConstants.DEFAULT_MASTER_PORT);
147    return String.format("%s:%d", hostname, port);
148  }
149
150  private static Set<ServerName> transformServerNames(GetMastersResponse resp) {
151    return resp.getMasterServersList().stream()
152      .map(s -> ProtobufUtil.toServerName(s.getServerName())).collect(Collectors.toSet());
153  }
154
155  @RestrictedApi(explanation = "Should only be called in tests", link = "",
156      allowedOnPath = ".*/(.*/MasterRegistry.java|src/test/.*)")
157  CompletableFuture<Set<ServerName>> getMasters() {
158    return this
159      .<GetMastersResponse> call(
160        (c, s, d) -> s.getMasters(c, GetMastersRequest.getDefaultInstance(), d),
161        r -> r.getMasterServersCount() != 0, "getMasters()")
162      .thenApply(MasterRegistry::transformServerNames);
163  }
164}