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.master;
020
021import static org.apache.hadoop.hbase.util.CollectionUtils.computeIfAbsent;
022
023import java.io.IOException;
024import java.net.InetAddress;
025import java.util.ArrayList;
026import java.util.Collections;
027import java.util.HashMap;
028import java.util.HashSet;
029import java.util.Iterator;
030import java.util.List;
031import java.util.Map;
032import java.util.Map.Entry;
033import java.util.Set;
034import java.util.concurrent.ConcurrentHashMap;
035import java.util.concurrent.ConcurrentNavigableMap;
036import java.util.concurrent.ConcurrentSkipListMap;
037import java.util.concurrent.CopyOnWriteArrayList;
038import java.util.concurrent.atomic.AtomicBoolean;
039import java.util.function.Predicate;
040import org.apache.hadoop.conf.Configuration;
041import org.apache.hadoop.hbase.ClockOutOfSyncException;
042import org.apache.hadoop.hbase.HConstants;
043import org.apache.hadoop.hbase.NotServingRegionException;
044import org.apache.hadoop.hbase.RegionMetrics;
045import org.apache.hadoop.hbase.ServerMetrics;
046import org.apache.hadoop.hbase.ServerMetricsBuilder;
047import org.apache.hadoop.hbase.ServerName;
048import org.apache.hadoop.hbase.YouAreDeadException;
049import org.apache.hadoop.hbase.ZooKeeperConnectionException;
050import org.apache.hadoop.hbase.client.ClusterConnection;
051import org.apache.hadoop.hbase.client.RegionInfo;
052import org.apache.hadoop.hbase.client.RetriesExhaustedException;
053import org.apache.hadoop.hbase.ipc.HBaseRpcController;
054import org.apache.hadoop.hbase.ipc.RpcControllerFactory;
055import org.apache.hadoop.hbase.monitoring.MonitoredTask;
056import org.apache.hadoop.hbase.regionserver.HRegionServer;
057import org.apache.hadoop.hbase.util.Bytes;
058import org.apache.hadoop.hbase.zookeeper.ZKUtil;
059import org.apache.hadoop.hbase.zookeeper.ZKWatcher;
060import org.apache.yetus.audience.InterfaceAudience;
061import org.apache.zookeeper.KeeperException;
062import org.slf4j.Logger;
063import org.slf4j.LoggerFactory;
064
065import org.apache.hbase.thirdparty.com.google.common.annotations.VisibleForTesting;
066import org.apache.hbase.thirdparty.com.google.protobuf.UnsafeByteOperations;
067
068import org.apache.hadoop.hbase.shaded.protobuf.ProtobufUtil;
069import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.AdminService;
070import org.apache.hadoop.hbase.shaded.protobuf.generated.ClusterStatusProtos.RegionStoreSequenceIds;
071import org.apache.hadoop.hbase.shaded.protobuf.generated.ClusterStatusProtos.StoreSequenceId;
072import org.apache.hadoop.hbase.shaded.protobuf.generated.RegionServerStatusProtos.RegionServerStartupRequest;
073
074/**
075 * The ServerManager class manages info about region servers.
076 * <p>
077 * Maintains lists of online and dead servers.  Processes the startups,
078 * shutdowns, and deaths of region servers.
079 * <p>
080 * Servers are distinguished in two different ways.  A given server has a
081 * location, specified by hostname and port, and of which there can only be one
082 * online at any given time.  A server instance is specified by the location
083 * (hostname and port) as well as the startcode (timestamp from when the server
084 * was started).  This is used to differentiate a restarted instance of a given
085 * server from the original instance.
086 * <p>
087 * If a sever is known not to be running any more, it is called dead. The dead
088 * server needs to be handled by a ServerShutdownHandler.  If the handler is not
089 * enabled yet, the server can't be handled right away so it is queued up.
090 * After the handler is enabled, the server will be submitted to a handler to handle.
091 * However, the handler may be just partially enabled.  If so,
092 * the server cannot be fully processed, and be queued up for further processing.
093 * A server is fully processed only after the handler is fully enabled
094 * and has completed the handling.
095 */
096@InterfaceAudience.Private
097public class ServerManager {
098  public static final String WAIT_ON_REGIONSERVERS_MAXTOSTART =
099      "hbase.master.wait.on.regionservers.maxtostart";
100
101  public static final String WAIT_ON_REGIONSERVERS_MINTOSTART =
102      "hbase.master.wait.on.regionservers.mintostart";
103
104  public static final String WAIT_ON_REGIONSERVERS_TIMEOUT =
105      "hbase.master.wait.on.regionservers.timeout";
106
107  public static final String WAIT_ON_REGIONSERVERS_INTERVAL =
108      "hbase.master.wait.on.regionservers.interval";
109
110  private static final Logger LOG = LoggerFactory.getLogger(ServerManager.class);
111
112  // Set if we are to shutdown the cluster.
113  private AtomicBoolean clusterShutdown = new AtomicBoolean(false);
114
115  /**
116   * The last flushed sequence id for a region.
117   */
118  private final ConcurrentNavigableMap<byte[], Long> flushedSequenceIdByRegion =
119    new ConcurrentSkipListMap<>(Bytes.BYTES_COMPARATOR);
120
121  /**
122   * The last flushed sequence id for a store in a region.
123   */
124  private final ConcurrentNavigableMap<byte[], ConcurrentNavigableMap<byte[], Long>>
125    storeFlushedSequenceIdsByRegion = new ConcurrentSkipListMap<>(Bytes.BYTES_COMPARATOR);
126
127  /** Map of registered servers to their current load */
128  private final ConcurrentNavigableMap<ServerName, ServerMetrics> onlineServers =
129    new ConcurrentSkipListMap<>();
130
131  /**
132   * Map of admin interfaces per registered regionserver; these interfaces we use to control
133   * regionservers out on the cluster
134   */
135  private final Map<ServerName, AdminService.BlockingInterface> rsAdmins = new HashMap<>();
136
137  /** List of region servers that should not get any more new regions. */
138  private final ArrayList<ServerName> drainingServers = new ArrayList<>();
139
140  private final MasterServices master;
141  private final ClusterConnection connection;
142
143  private final DeadServer deadservers = new DeadServer();
144
145  private final long maxSkew;
146  private final long warningSkew;
147
148  private final RpcControllerFactory rpcControllerFactory;
149
150  /**
151   * Set of region servers which are dead but not processed immediately. If one
152   * server died before master enables ServerShutdownHandler, the server will be
153   * added to this set and will be processed through calling
154   * {@link ServerManager#processQueuedDeadServers()} by master.
155   * <p>
156   * A dead server is a server instance known to be dead, not listed in the /hbase/rs
157   * znode any more. It may have not been submitted to ServerShutdownHandler yet
158   * because the handler is not enabled.
159   * <p>
160   * A dead server, which has been submitted to ServerShutdownHandler while the
161   * handler is not enabled, is queued up.
162   * <p>
163   * So this is a set of region servers known to be dead but not submitted to
164   * ServerShutdownHandler for processing yet.
165   */
166  private Set<ServerName> queuedDeadServers = new HashSet<>();
167
168  /**
169   * Set of region servers which are dead and submitted to ServerShutdownHandler to process but not
170   * fully processed immediately.
171   * <p>
172   * If one server died before assignment manager finished the failover cleanup, the server will be
173   * added to this set and will be processed through calling
174   * {@link ServerManager#processQueuedDeadServers()} by assignment manager.
175   * <p>
176   * The Boolean value indicates whether log split is needed inside ServerShutdownHandler
177   * <p>
178   * ServerShutdownHandler processes a dead server submitted to the handler after the handler is
179   * enabled. It may not be able to complete the processing because meta is not yet online or master
180   * is currently in startup mode. In this case, the dead server will be parked in this set
181   * temporarily.
182   */
183  private Map<ServerName, Boolean> requeuedDeadServers = new ConcurrentHashMap<>();
184
185  /** Listeners that are called on server events. */
186  private List<ServerListener> listeners = new CopyOnWriteArrayList<>();
187
188  /**
189   * Constructor.
190   * @param master
191   * @throws ZooKeeperConnectionException
192   */
193  public ServerManager(final MasterServices master) {
194    this(master, true);
195  }
196
197  ServerManager(final MasterServices master, final boolean connect) {
198    this.master = master;
199    Configuration c = master.getConfiguration();
200    maxSkew = c.getLong("hbase.master.maxclockskew", 30000);
201    warningSkew = c.getLong("hbase.master.warningclockskew", 10000);
202    this.connection = connect? master.getClusterConnection(): null;
203    this.rpcControllerFactory = this.connection == null? null: connection.getRpcControllerFactory();
204  }
205
206  /**
207   * Add the listener to the notification list.
208   * @param listener The ServerListener to register
209   */
210  public void registerListener(final ServerListener listener) {
211    this.listeners.add(listener);
212  }
213
214  /**
215   * Remove the listener from the notification list.
216   * @param listener The ServerListener to unregister
217   */
218  public boolean unregisterListener(final ServerListener listener) {
219    return this.listeners.remove(listener);
220  }
221
222  /**
223   * Let the server manager know a new regionserver has come online
224   * @param request the startup request
225   * @param versionNumber the version of the new regionserver
226   * @param ia the InetAddress from which request is received
227   * @return The ServerName we know this server as.
228   * @throws IOException
229   */
230  ServerName regionServerStartup(RegionServerStartupRequest request, int versionNumber,
231      InetAddress ia)
232      throws IOException {
233    // Test for case where we get a region startup message from a regionserver
234    // that has been quickly restarted but whose znode expiration handler has
235    // not yet run, or from a server whose fail we are currently processing.
236    // Test its host+port combo is present in serverAddressToServerInfo.  If it
237    // is, reject the server and trigger its expiration. The next time it comes
238    // in, it should have been removed from serverAddressToServerInfo and queued
239    // for processing by ProcessServerShutdown.
240
241    final String hostname = request.hasUseThisHostnameInstead() ?
242        request.getUseThisHostnameInstead() :ia.getHostName();
243    ServerName sn = ServerName.valueOf(hostname, request.getPort(),
244      request.getServerStartCode());
245    checkClockSkew(sn, request.getServerCurrentTime());
246    checkIsDead(sn, "STARTUP");
247    if (!checkAndRecordNewServer(sn, ServerMetricsBuilder.of(sn, versionNumber))) {
248      LOG.warn("THIS SHOULD NOT HAPPEN, RegionServerStartup"
249        + " could not record the server: " + sn);
250    }
251    return sn;
252  }
253
254  /**
255   * Updates last flushed sequence Ids for the regions on server sn
256   * @param sn
257   * @param hsl
258   */
259  private void updateLastFlushedSequenceIds(ServerName sn, ServerMetrics hsl) {
260    for (Entry<byte[], RegionMetrics> entry : hsl.getRegionMetrics().entrySet()) {
261      byte[] encodedRegionName = Bytes.toBytes(RegionInfo.encodeRegionName(entry.getKey()));
262      Long existingValue = flushedSequenceIdByRegion.get(encodedRegionName);
263      long l = entry.getValue().getCompletedSequenceId();
264      // Don't let smaller sequence ids override greater sequence ids.
265      if (LOG.isTraceEnabled()) {
266        LOG.trace(Bytes.toString(encodedRegionName) + ", existingValue=" + existingValue +
267          ", completeSequenceId=" + l);
268      }
269      if (existingValue == null || (l != HConstants.NO_SEQNUM && l > existingValue)) {
270        flushedSequenceIdByRegion.put(encodedRegionName, l);
271      } else if (l != HConstants.NO_SEQNUM && l < existingValue) {
272        LOG.warn("RegionServer " + sn + " indicates a last flushed sequence id ("
273            + l + ") that is less than the previous last flushed sequence id ("
274            + existingValue + ") for region " + Bytes.toString(entry.getKey()) + " Ignoring.");
275      }
276      ConcurrentNavigableMap<byte[], Long> storeFlushedSequenceId =
277          computeIfAbsent(storeFlushedSequenceIdsByRegion, encodedRegionName,
278            () -> new ConcurrentSkipListMap<>(Bytes.BYTES_COMPARATOR));
279      for (Entry<byte[], Long> storeSeqId : entry.getValue().getStoreSequenceId().entrySet()) {
280        byte[] family = storeSeqId.getKey();
281        existingValue = storeFlushedSequenceId.get(family);
282        l = storeSeqId.getValue();
283        if (LOG.isTraceEnabled()) {
284          LOG.trace(Bytes.toString(encodedRegionName) + ", family=" + Bytes.toString(family) +
285            ", existingValue=" + existingValue + ", completeSequenceId=" + l);
286        }
287        // Don't let smaller sequence ids override greater sequence ids.
288        if (existingValue == null || (l != HConstants.NO_SEQNUM && l > existingValue.longValue())) {
289          storeFlushedSequenceId.put(family, l);
290        }
291      }
292    }
293  }
294
295  @VisibleForTesting
296  public void regionServerReport(ServerName sn,
297    ServerMetrics sl) throws YouAreDeadException {
298    checkIsDead(sn, "REPORT");
299    if (null == this.onlineServers.replace(sn, sl)) {
300      // Already have this host+port combo and its just different start code?
301      // Just let the server in. Presume master joining a running cluster.
302      // recordNewServer is what happens at the end of reportServerStartup.
303      // The only thing we are skipping is passing back to the regionserver
304      // the ServerName to use. Here we presume a master has already done
305      // that so we'll press on with whatever it gave us for ServerName.
306      if (!checkAndRecordNewServer(sn, sl)) {
307        LOG.info("RegionServerReport ignored, could not record the server: " + sn);
308        return; // Not recorded, so no need to move on
309      }
310    }
311    updateLastFlushedSequenceIds(sn, sl);
312  }
313
314  /**
315   * Check is a server of same host and port already exists,
316   * if not, or the existed one got a smaller start code, record it.
317   *
318   * @param serverName the server to check and record
319   * @param sl the server load on the server
320   * @return true if the server is recorded, otherwise, false
321   */
322  boolean checkAndRecordNewServer(final ServerName serverName, final ServerMetrics sl) {
323    ServerName existingServer = null;
324    synchronized (this.onlineServers) {
325      existingServer = findServerWithSameHostnamePortWithLock(serverName);
326      if (existingServer != null && (existingServer.getStartcode() > serverName.getStartcode())) {
327        LOG.info("Server serverName=" + serverName + " rejected; we already have "
328            + existingServer.toString() + " registered with same hostname and port");
329        return false;
330      }
331      recordNewServerWithLock(serverName, sl);
332    }
333
334    // Tell our listeners that a server was added
335    if (!this.listeners.isEmpty()) {
336      for (ServerListener listener : this.listeners) {
337        listener.serverAdded(serverName);
338      }
339    }
340
341    // Note that we assume that same ts means same server, and don't expire in that case.
342    //  TODO: ts can theoretically collide due to clock shifts, so this is a bit hacky.
343    if (existingServer != null &&
344        (existingServer.getStartcode() < serverName.getStartcode())) {
345      LOG.info("Triggering server recovery; existingServer " +
346          existingServer + " looks stale, new server:" + serverName);
347      expireServer(existingServer);
348    }
349    return true;
350  }
351
352  /**
353   * Checks if the clock skew between the server and the master. If the clock skew exceeds the
354   * configured max, it will throw an exception; if it exceeds the configured warning threshold,
355   * it will log a warning but start normally.
356   * @param serverName Incoming servers's name
357   * @param serverCurrentTime
358   * @throws ClockOutOfSyncException if the skew exceeds the configured max value
359   */
360  private void checkClockSkew(final ServerName serverName, final long serverCurrentTime)
361  throws ClockOutOfSyncException {
362    long skew = Math.abs(System.currentTimeMillis() - serverCurrentTime);
363    if (skew > maxSkew) {
364      String message = "Server " + serverName + " has been " +
365        "rejected; Reported time is too far out of sync with master.  " +
366        "Time difference of " + skew + "ms > max allowed of " + maxSkew + "ms";
367      LOG.warn(message);
368      throw new ClockOutOfSyncException(message);
369    } else if (skew > warningSkew){
370      String message = "Reported time for server " + serverName + " is out of sync with master " +
371        "by " + skew + "ms. (Warning threshold is " + warningSkew + "ms; " +
372        "error threshold is " + maxSkew + "ms)";
373      LOG.warn(message);
374    }
375  }
376
377  /**
378   * If this server is on the dead list, reject it with a YouAreDeadException.
379   * If it was dead but came back with a new start code, remove the old entry
380   * from the dead list.
381   * @param serverName
382   * @param what START or REPORT
383   * @throws org.apache.hadoop.hbase.YouAreDeadException
384   */
385  private void checkIsDead(final ServerName serverName, final String what)
386      throws YouAreDeadException {
387    if (this.deadservers.isDeadServer(serverName)) {
388      // host name, port and start code all match with existing one of the
389      // dead servers. So, this server must be dead.
390      String message = "Server " + what + " rejected; currently processing " +
391          serverName + " as dead server";
392      LOG.debug(message);
393      throw new YouAreDeadException(message);
394    }
395    // remove dead server with same hostname and port of newly checking in rs after master
396    // initialization.See HBASE-5916 for more information.
397    if ((this.master == null || this.master.isInitialized())
398        && this.deadservers.cleanPreviousInstance(serverName)) {
399      // This server has now become alive after we marked it as dead.
400      // We removed it's previous entry from the dead list to reflect it.
401      LOG.debug(what + ":" + " Server " + serverName + " came back up," +
402          " removed it from the dead servers list");
403    }
404  }
405
406  /**
407   * Assumes onlineServers is locked.
408   * @return ServerName with matching hostname and port.
409   */
410  private ServerName findServerWithSameHostnamePortWithLock(
411      final ServerName serverName) {
412    ServerName end = ServerName.valueOf(serverName.getHostname(), serverName.getPort(),
413        Long.MAX_VALUE);
414
415    ServerName r = onlineServers.lowerKey(end);
416    if (r != null) {
417      if (ServerName.isSameAddress(r, serverName)) {
418        return r;
419      }
420    }
421    return null;
422  }
423
424  /**
425   * Adds the onlineServers list. onlineServers should be locked.
426   * @param serverName The remote servers name.
427   */
428  @VisibleForTesting
429  void recordNewServerWithLock(final ServerName serverName, final ServerMetrics sl) {
430    LOG.info("Registering regionserver=" + serverName);
431    this.onlineServers.put(serverName, sl);
432    this.rsAdmins.remove(serverName);
433  }
434
435  public RegionStoreSequenceIds getLastFlushedSequenceId(byte[] encodedRegionName) {
436    RegionStoreSequenceIds.Builder builder = RegionStoreSequenceIds.newBuilder();
437    Long seqId = flushedSequenceIdByRegion.get(encodedRegionName);
438    builder.setLastFlushedSequenceId(seqId != null ? seqId.longValue() : HConstants.NO_SEQNUM);
439    Map<byte[], Long> storeFlushedSequenceId =
440        storeFlushedSequenceIdsByRegion.get(encodedRegionName);
441    if (storeFlushedSequenceId != null) {
442      for (Map.Entry<byte[], Long> entry : storeFlushedSequenceId.entrySet()) {
443        builder.addStoreSequenceId(StoreSequenceId.newBuilder()
444            .setFamilyName(UnsafeByteOperations.unsafeWrap(entry.getKey()))
445            .setSequenceId(entry.getValue().longValue()).build());
446      }
447    }
448    return builder.build();
449  }
450
451  /**
452   * @param serverName
453   * @return ServerMetrics if serverName is known else null
454   */
455  public ServerMetrics getLoad(final ServerName serverName) {
456    return this.onlineServers.get(serverName);
457  }
458
459  /**
460   * Compute the average load across all region servers.
461   * Currently, this uses a very naive computation - just uses the number of
462   * regions being served, ignoring stats about number of requests.
463   * @return the average load
464   */
465  public double getAverageLoad() {
466    int totalLoad = 0;
467    int numServers = 0;
468    for (ServerMetrics sl : this.onlineServers.values()) {
469      numServers++;
470      totalLoad += sl.getRegionMetrics().size();
471    }
472    return numServers == 0 ? 0 :
473      (double)totalLoad / (double)numServers;
474  }
475
476  /** @return the count of active regionservers */
477  public int countOfRegionServers() {
478    // Presumes onlineServers is a concurrent map
479    return this.onlineServers.size();
480  }
481
482  /**
483   * @return Read-only map of servers to serverinfo
484   */
485  public Map<ServerName, ServerMetrics> getOnlineServers() {
486    // Presumption is that iterating the returned Map is OK.
487    synchronized (this.onlineServers) {
488      return Collections.unmodifiableMap(this.onlineServers);
489    }
490  }
491
492  public DeadServer getDeadServers() {
493    return this.deadservers;
494  }
495
496  /**
497   * Checks if any dead servers are currently in progress.
498   * @return true if any RS are being processed as dead, false if not
499   */
500  public boolean areDeadServersInProgress() {
501    return this.deadservers.areDeadServersInProgress();
502  }
503
504  void letRegionServersShutdown() {
505    long previousLogTime = 0;
506    ServerName sn = master.getServerName();
507    ZKWatcher zkw = master.getZooKeeper();
508    int onlineServersCt;
509    while ((onlineServersCt = onlineServers.size()) > 0){
510
511      if (System.currentTimeMillis() > (previousLogTime + 1000)) {
512        Set<ServerName> remainingServers = onlineServers.keySet();
513        synchronized (onlineServers) {
514          if (remainingServers.size() == 1 && remainingServers.contains(sn)) {
515            // Master will delete itself later.
516            return;
517          }
518        }
519        StringBuilder sb = new StringBuilder();
520        // It's ok here to not sync on onlineServers - merely logging
521        for (ServerName key : remainingServers) {
522          if (sb.length() > 0) {
523            sb.append(", ");
524          }
525          sb.append(key);
526        }
527        LOG.info("Waiting on regionserver(s) " + sb.toString());
528        previousLogTime = System.currentTimeMillis();
529      }
530
531      try {
532        List<String> servers = getRegionServersInZK(zkw);
533        if (servers == null || servers.isEmpty() || (servers.size() == 1
534            && servers.contains(sn.toString()))) {
535          LOG.info("ZK shows there is only the master self online, exiting now");
536          // Master could have lost some ZK events, no need to wait more.
537          break;
538        }
539      } catch (KeeperException ke) {
540        LOG.warn("Failed to list regionservers", ke);
541        // ZK is malfunctioning, don't hang here
542        break;
543      }
544      synchronized (onlineServers) {
545        try {
546          if (onlineServersCt == onlineServers.size()) onlineServers.wait(100);
547        } catch (InterruptedException ignored) {
548          // continue
549        }
550      }
551    }
552  }
553
554  private List<String> getRegionServersInZK(final ZKWatcher zkw)
555  throws KeeperException {
556    return ZKUtil.listChildrenNoWatch(zkw, zkw.znodePaths.rsZNode);
557  }
558
559  /*
560   * Expire the passed server.  Add it to list of dead servers and queue a
561   * shutdown processing.
562   * @return True if we queued a ServerCrashProcedure else false if we did not (could happen
563   * for many reasons including the fact that its this server that is going down or we already
564   * have queued an SCP for this server or SCP processing is currently disabled because we are
565   * in startup phase).
566   */
567  public synchronized boolean expireServer(final ServerName serverName) {
568    // THIS server is going down... can't handle our own expiration.
569    if (serverName.equals(master.getServerName())) {
570      if (!(master.isAborted() || master.isStopped())) {
571        master.stop("We lost our znode?");
572      }
573      return false;
574    }
575    // No SCP handling during startup.
576    if (!master.isServerCrashProcessingEnabled()) {
577      LOG.info("Master doesn't enable ServerShutdownHandler during initialization, "
578          + "delay expiring server " + serverName);
579      // Even though we delay expire of this server, we still need to handle Meta's RIT
580      // that are against the crashed server; since when we do RecoverMetaProcedure,
581      // the SCP is not enabled yet and Meta's RIT may be suspend forever. See HBase-19287
582      master.getAssignmentManager().handleMetaRITOnCrashedServer(serverName);
583      this.queuedDeadServers.add(serverName);
584      // Return true because though on SCP queued, there will be one queued later.
585      return true;
586    }
587    if (this.deadservers.isDeadServer(serverName)) {
588      LOG.warn("Expiration called on {} but crash processing already in progress", serverName);
589      return false;
590    }
591    moveFromOnlineToDeadServers(serverName);
592
593    // If cluster is going down, yes, servers are going to be expiring; don't
594    // process as a dead server
595    if (isClusterShutdown()) {
596      LOG.info("Cluster shutdown set; " + serverName +
597        " expired; onlineServers=" + this.onlineServers.size());
598      if (this.onlineServers.isEmpty()) {
599        master.stop("Cluster shutdown set; onlineServer=0");
600      }
601      return false;
602    }
603    LOG.info("Processing expiration of " + serverName + " on " + this.master.getServerName());
604    master.getAssignmentManager().submitServerCrash(serverName, true);
605
606    // Tell our listeners that a server was removed
607    if (!this.listeners.isEmpty()) {
608      for (ServerListener listener : this.listeners) {
609        listener.serverRemoved(serverName);
610      }
611    }
612    return true;
613  }
614
615  @VisibleForTesting
616  public void moveFromOnlineToDeadServers(final ServerName sn) {
617    synchronized (onlineServers) {
618      if (!this.onlineServers.containsKey(sn)) {
619        LOG.warn("Expiration of " + sn + " but server not online");
620      }
621      // Remove the server from the known servers lists and update load info BUT
622      // add to deadservers first; do this so it'll show in dead servers list if
623      // not in online servers list.
624      this.deadservers.add(sn);
625      this.onlineServers.remove(sn);
626      onlineServers.notifyAll();
627    }
628    this.rsAdmins.remove(sn);
629  }
630
631  public synchronized void processDeadServer(final ServerName serverName, boolean shouldSplitWal) {
632    // When assignment manager is cleaning up the zookeeper nodes and rebuilding the
633    // in-memory region states, region servers could be down. Meta table can and
634    // should be re-assigned, log splitting can be done too. However, it is better to
635    // wait till the cleanup is done before re-assigning user regions.
636    //
637    // We should not wait in the server shutdown handler thread since it can clog
638    // the handler threads and meta table could not be re-assigned in case
639    // the corresponding server is down. So we queue them up here instead.
640    if (!master.getAssignmentManager().isFailoverCleanupDone()) {
641      requeuedDeadServers.put(serverName, shouldSplitWal);
642      return;
643    }
644
645    this.deadservers.add(serverName);
646    master.getAssignmentManager().submitServerCrash(serverName, shouldSplitWal);
647  }
648
649  /**
650   * Process the servers which died during master's initialization. It will be
651   * called after HMaster#assignMeta and AssignmentManager#joinCluster.
652   * */
653  synchronized void processQueuedDeadServers() {
654    if (!master.isServerCrashProcessingEnabled()) {
655      LOG.info("Master hasn't enabled ServerShutdownHandler");
656    }
657    Iterator<ServerName> serverIterator = queuedDeadServers.iterator();
658    while (serverIterator.hasNext()) {
659      ServerName tmpServerName = serverIterator.next();
660      expireServer(tmpServerName);
661      serverIterator.remove();
662      requeuedDeadServers.remove(tmpServerName);
663    }
664
665    if (!master.getAssignmentManager().isFailoverCleanupDone()) {
666      if (LOG.isTraceEnabled()) {
667        LOG.trace("AssignmentManager failover cleanup not done.");
668      }
669    }
670
671    for (Map.Entry<ServerName, Boolean> entry : requeuedDeadServers.entrySet()) {
672      processDeadServer(entry.getKey(), entry.getValue());
673    }
674    requeuedDeadServers.clear();
675  }
676
677  /*
678   * Remove the server from the drain list.
679   */
680  public synchronized boolean removeServerFromDrainList(final ServerName sn) {
681    // Warn if the server (sn) is not online.  ServerName is of the form:
682    // <hostname> , <port> , <startcode>
683
684    if (!this.isServerOnline(sn)) {
685      LOG.warn("Server " + sn + " is not currently online. " +
686               "Removing from draining list anyway, as requested.");
687    }
688    // Remove the server from the draining servers lists.
689    return this.drainingServers.remove(sn);
690  }
691
692  /**
693   * Add the server to the drain list.
694   * @param sn
695   * @return True if the server is added or the server is already on the drain list.
696   */
697  public synchronized boolean addServerToDrainList(final ServerName sn) {
698    // Warn if the server (sn) is not online.  ServerName is of the form:
699    // <hostname> , <port> , <startcode>
700
701    if (!this.isServerOnline(sn)) {
702      LOG.warn("Server " + sn + " is not currently online. " +
703               "Ignoring request to add it to draining list.");
704      return false;
705    }
706    // Add the server to the draining servers lists, if it's not already in
707    // it.
708    if (this.drainingServers.contains(sn)) {
709      LOG.warn("Server " + sn + " is already in the draining server list." +
710               "Ignoring request to add it again.");
711      return true;
712    }
713    LOG.info("Server " + sn + " added to draining server list.");
714    return this.drainingServers.add(sn);
715  }
716
717  // RPC methods to region servers
718
719  private HBaseRpcController newRpcController() {
720    return rpcControllerFactory == null ? null : rpcControllerFactory.newController();
721  }
722
723  /**
724   * Sends a WARMUP RPC to the specified server to warmup the specified region.
725   * <p>
726   * A region server could reject the close request because it either does not
727   * have the specified region or the region is being split.
728   * @param server server to warmup a region
729   * @param region region to  warmup
730   */
731  public void sendRegionWarmup(ServerName server,
732      RegionInfo region) {
733    if (server == null) return;
734    try {
735      AdminService.BlockingInterface admin = getRsAdmin(server);
736      HBaseRpcController controller = newRpcController();
737      ProtobufUtil.warmupRegion(controller, admin, region);
738    } catch (IOException e) {
739      LOG.error("Received exception in RPC for warmup server:" +
740        server + "region: " + region +
741        "exception: " + e);
742    }
743  }
744
745  /**
746   * Contacts a region server and waits up to timeout ms
747   * to close the region.  This bypasses the active hmaster.
748   */
749  public static void closeRegionSilentlyAndWait(ClusterConnection connection,
750    ServerName server, RegionInfo region, long timeout) throws IOException, InterruptedException {
751    AdminService.BlockingInterface rs = connection.getAdmin(server);
752    HBaseRpcController controller = connection.getRpcControllerFactory().newController();
753    try {
754      ProtobufUtil.closeRegion(controller, rs, server, region.getRegionName());
755    } catch (IOException e) {
756      LOG.warn("Exception when closing region: " + region.getRegionNameAsString(), e);
757    }
758    long expiration = timeout + System.currentTimeMillis();
759    while (System.currentTimeMillis() < expiration) {
760      controller.reset();
761      try {
762        RegionInfo rsRegion =
763          ProtobufUtil.getRegionInfo(controller, rs, region.getRegionName());
764        if (rsRegion == null) return;
765      } catch (IOException ioe) {
766        if (ioe instanceof NotServingRegionException) // no need to retry again
767          return;
768        LOG.warn("Exception when retrieving regioninfo from: "
769          + region.getRegionNameAsString(), ioe);
770      }
771      Thread.sleep(1000);
772    }
773    throw new IOException("Region " + region + " failed to close within"
774        + " timeout " + timeout);
775  }
776
777  /**
778   * @param sn
779   * @return Admin interface for the remote regionserver named <code>sn</code>
780   * @throws IOException
781   * @throws RetriesExhaustedException wrapping a ConnectException if failed
782   */
783  public AdminService.BlockingInterface getRsAdmin(final ServerName sn)
784  throws IOException {
785    AdminService.BlockingInterface admin = this.rsAdmins.get(sn);
786    if (admin == null) {
787      LOG.debug("New admin connection to " + sn.toString());
788      if (sn.equals(master.getServerName()) && master instanceof HRegionServer) {
789        // A master is also a region server now, see HBASE-10569 for details
790        admin = ((HRegionServer)master).getRSRpcServices();
791      } else {
792        admin = this.connection.getAdmin(sn);
793      }
794      this.rsAdmins.put(sn, admin);
795    }
796    return admin;
797  }
798
799  /**
800   * Calculate min necessary to start. This is not an absolute. It is just
801   * a friction that will cause us hang around a bit longer waiting on
802   * RegionServers to check-in.
803   */
804  private int getMinToStart() {
805    // One server should be enough to get us off the ground.
806    int requiredMinToStart = 1;
807    if (LoadBalancer.isTablesOnMaster(master.getConfiguration())) {
808      if (LoadBalancer.isSystemTablesOnlyOnMaster(master.getConfiguration())) {
809        // If Master is carrying regions but NOT user-space regions, it
810        // still shows as a 'server'. We need at least one more server to check
811        // in before we can start up so set defaultMinToStart to 2.
812        requiredMinToStart = requiredMinToStart + 1;
813      }
814    }
815    int minToStart = this.master.getConfiguration().getInt(WAIT_ON_REGIONSERVERS_MINTOSTART, -1);
816    // Ensure we are never less than requiredMinToStart else stuff won't work.
817    return minToStart == -1 || minToStart < requiredMinToStart? requiredMinToStart: minToStart;
818  }
819
820  /**
821   * Wait for the region servers to report in.
822   * We will wait until one of this condition is met:
823   *  - the master is stopped
824   *  - the 'hbase.master.wait.on.regionservers.maxtostart' number of
825   *    region servers is reached
826   *  - the 'hbase.master.wait.on.regionservers.mintostart' is reached AND
827   *   there have been no new region server in for
828   *      'hbase.master.wait.on.regionservers.interval' time AND
829   *   the 'hbase.master.wait.on.regionservers.timeout' is reached
830   *
831   * @throws InterruptedException
832   */
833  public void waitForRegionServers(MonitoredTask status) throws InterruptedException {
834    final long interval = this.master.getConfiguration().
835        getLong(WAIT_ON_REGIONSERVERS_INTERVAL, 1500);
836    final long timeout = this.master.getConfiguration().
837        getLong(WAIT_ON_REGIONSERVERS_TIMEOUT, 4500);
838    // Min is not an absolute; just a friction making us wait longer on server checkin.
839    int minToStart = getMinToStart();
840    int maxToStart = this.master.getConfiguration().
841        getInt(WAIT_ON_REGIONSERVERS_MAXTOSTART, Integer.MAX_VALUE);
842    if (maxToStart < minToStart) {
843      LOG.warn(String.format("The value of '%s' (%d) is set less than '%s' (%d), ignoring.",
844          WAIT_ON_REGIONSERVERS_MAXTOSTART, maxToStart,
845          WAIT_ON_REGIONSERVERS_MINTOSTART, minToStart));
846      maxToStart = Integer.MAX_VALUE;
847    }
848
849    long now =  System.currentTimeMillis();
850    final long startTime = now;
851    long slept = 0;
852    long lastLogTime = 0;
853    long lastCountChange = startTime;
854    int count = countOfRegionServers();
855    int oldCount = 0;
856    // This while test is a little hard to read. We try to comment it in below but in essence:
857    // Wait if Master is not stopped and the number of regionservers that have checked-in is
858    // less than the maxToStart. Both of these conditions will be true near universally.
859    // Next, we will keep cycling if ANY of the following three conditions are true:
860    // 1. The time since a regionserver registered is < interval (means servers are actively checking in).
861    // 2. We are under the total timeout.
862    // 3. The count of servers is < minimum.
863    for (ServerListener listener: this.listeners) {
864      listener.waiting();
865    }
866    while (!this.master.isStopped() && !isClusterShutdown() && count < maxToStart &&
867        ((lastCountChange + interval) > now || timeout > slept || count < minToStart)) {
868      // Log some info at every interval time or if there is a change
869      if (oldCount != count || lastLogTime + interval < now) {
870        lastLogTime = now;
871        String msg =
872            "Waiting on regionserver count=" + count + "; waited="+
873                slept + "ms, expecting min=" + minToStart + " server(s), max="+ getStrForMax(maxToStart) +
874                " server(s), " + "timeout=" + timeout + "ms, lastChange=" + (lastCountChange - now) + "ms";
875        LOG.info(msg);
876        status.setStatus(msg);
877      }
878
879      // We sleep for some time
880      final long sleepTime = 50;
881      Thread.sleep(sleepTime);
882      now =  System.currentTimeMillis();
883      slept = now - startTime;
884
885      oldCount = count;
886      count = countOfRegionServers();
887      if (count != oldCount) {
888        lastCountChange = now;
889      }
890    }
891    // Did we exit the loop because cluster is going down?
892    if (isClusterShutdown()) {
893      this.master.stop("Cluster shutdown");
894    }
895    LOG.info("Finished waiting on RegionServer count=" + count + "; waited=" + slept + "ms," +
896        " expected min=" + minToStart + " server(s), max=" +  getStrForMax(maxToStart) + " server(s),"+
897        " master is "+ (this.master.isStopped() ? "stopped.": "running"));
898  }
899
900  private String getStrForMax(final int max) {
901    return max == Integer.MAX_VALUE? "NO_LIMIT": Integer.toString(max);
902  }
903
904  /**
905   * @return A copy of the internal list of online servers.
906   */
907  public List<ServerName> getOnlineServersList() {
908    // TODO: optimize the load balancer call so we don't need to make a new list
909    // TODO: FIX. THIS IS POPULAR CALL.
910    return new ArrayList<>(this.onlineServers.keySet());
911  }
912
913  /**
914   * @param keys The target server name
915   * @param idleServerPredicator Evaluates the server on the given load
916   * @return A copy of the internal list of online servers matched by the predicator
917   */
918  public List<ServerName> getOnlineServersListWithPredicator(List<ServerName> keys,
919    Predicate<ServerMetrics> idleServerPredicator) {
920    List<ServerName> names = new ArrayList<>();
921    if (keys != null && idleServerPredicator != null) {
922      keys.forEach(name -> {
923        ServerMetrics load = onlineServers.get(name);
924        if (load != null) {
925          if (idleServerPredicator.test(load)) {
926            names.add(name);
927          }
928        }
929      });
930    }
931    return names;
932  }
933
934  /**
935   * @return A copy of the internal list of draining servers.
936   */
937  public List<ServerName> getDrainingServersList() {
938    return new ArrayList<>(this.drainingServers);
939  }
940
941  /**
942   * @return A copy of the internal set of deadNotExpired servers.
943   */
944  Set<ServerName> getDeadNotExpiredServers() {
945    return new HashSet<>(this.queuedDeadServers);
946  }
947
948  public boolean isServerOnline(ServerName serverName) {
949    return serverName != null && onlineServers.containsKey(serverName);
950  }
951
952  /**
953   * Check if a server is known to be dead.  A server can be online,
954   * or known to be dead, or unknown to this manager (i.e, not online,
955   * not known to be dead either. it is simply not tracked by the
956   * master any more, for example, a very old previous instance).
957   */
958  public synchronized boolean isServerDead(ServerName serverName) {
959    return serverName == null || deadservers.isDeadServer(serverName)
960      || queuedDeadServers.contains(serverName)
961      || requeuedDeadServers.containsKey(serverName);
962  }
963
964  public void shutdownCluster() {
965    String statusStr = "Cluster shutdown requested of master=" + this.master.getServerName();
966    LOG.info(statusStr);
967    this.clusterShutdown.set(true);
968    if (onlineServers.isEmpty()) {
969      // we do not synchronize here so this may cause a double stop, but not a big deal
970      master.stop("OnlineServer=0 right after cluster shutdown set");
971    }
972  }
973
974  boolean isClusterShutdown() {
975    return this.clusterShutdown.get();
976  }
977
978  /**
979   * Stop the ServerManager.
980   */
981  public void stop() {
982    // Nothing to do.
983  }
984
985  /**
986   * Creates a list of possible destinations for a region. It contains the online servers, but not
987   *  the draining or dying servers.
988   *  @param serversToExclude can be null if there is no server to exclude
989   */
990  public List<ServerName> createDestinationServersList(final List<ServerName> serversToExclude){
991    final List<ServerName> destServers = getOnlineServersList();
992
993    if (serversToExclude != null) {
994      destServers.removeAll(serversToExclude);
995    }
996
997    // Loop through the draining server list and remove them from the server list
998    final List<ServerName> drainingServersCopy = getDrainingServersList();
999    destServers.removeAll(drainingServersCopy);
1000
1001    // Remove the deadNotExpired servers from the server list.
1002    removeDeadNotExpiredServers(destServers);
1003    return destServers;
1004  }
1005
1006  /**
1007   * Calls {@link #createDestinationServersList} without server to exclude.
1008   */
1009  public List<ServerName> createDestinationServersList(){
1010    return createDestinationServersList(null);
1011  }
1012
1013    /**
1014    * Loop through the deadNotExpired server list and remove them from the
1015    * servers.
1016    * This function should be used carefully outside of this class. You should use a high level
1017    *  method such as {@link #createDestinationServersList()} instead of managing you own list.
1018    */
1019  void removeDeadNotExpiredServers(List<ServerName> servers) {
1020    Set<ServerName> deadNotExpiredServersCopy = this.getDeadNotExpiredServers();
1021    if (!deadNotExpiredServersCopy.isEmpty()) {
1022      for (ServerName server : deadNotExpiredServersCopy) {
1023        LOG.debug("Removing dead but not expired server: " + server
1024          + " from eligible server pool.");
1025        servers.remove(server);
1026      }
1027    }
1028  }
1029
1030  /**
1031   * To clear any dead server with same host name and port of any online server
1032   */
1033  void clearDeadServersWithSameHostNameAndPortOfOnlineServer() {
1034    for (ServerName serverName : getOnlineServersList()) {
1035      deadservers.cleanAllPreviousInstances(serverName);
1036    }
1037  }
1038
1039  /**
1040   * Called by delete table and similar to notify the ServerManager that a region was removed.
1041   */
1042  public void removeRegion(final RegionInfo regionInfo) {
1043    final byte[] encodedName = regionInfo.getEncodedNameAsBytes();
1044    storeFlushedSequenceIdsByRegion.remove(encodedName);
1045    flushedSequenceIdByRegion.remove(encodedName);
1046  }
1047
1048  @VisibleForTesting
1049  public boolean isRegionInServerManagerStates(final RegionInfo hri) {
1050    final byte[] encodedName = hri.getEncodedNameAsBytes();
1051    return (storeFlushedSequenceIdsByRegion.containsKey(encodedName)
1052        || flushedSequenceIdByRegion.containsKey(encodedName));
1053  }
1054
1055  /**
1056   * Called by delete table and similar to notify the ServerManager that a region was removed.
1057   */
1058  public void removeRegions(final List<RegionInfo> regions) {
1059    for (RegionInfo hri: regions) {
1060      removeRegion(hri);
1061    }
1062  }
1063
1064  /**
1065   * May return 0 when server is not online.
1066   */
1067  public int getServerVersion(final ServerName serverName) {
1068    ServerMetrics serverMetrics = onlineServers.get(serverName);
1069    return serverMetrics != null ? serverMetrics.getVersionNumber() : 0;
1070  }
1071}