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.master;
019
020import static org.apache.hadoop.hbase.util.ConcurrentMapUtils.computeIfAbsent;
021
022import java.io.IOException;
023import java.net.InetAddress;
024import java.util.ArrayList;
025import java.util.Collections;
026import java.util.HashSet;
027import java.util.Iterator;
028import java.util.List;
029import java.util.Map;
030import java.util.Map.Entry;
031import java.util.Objects;
032import java.util.Set;
033import java.util.concurrent.ConcurrentNavigableMap;
034import java.util.concurrent.ConcurrentSkipListMap;
035import java.util.concurrent.CopyOnWriteArrayList;
036import java.util.concurrent.atomic.AtomicBoolean;
037import java.util.function.Predicate;
038import org.apache.hadoop.conf.Configuration;
039import org.apache.hadoop.fs.FSDataInputStream;
040import org.apache.hadoop.fs.FSDataOutputStream;
041import org.apache.hadoop.fs.FileSystem;
042import org.apache.hadoop.fs.Path;
043import org.apache.hadoop.hbase.ClockOutOfSyncException;
044import org.apache.hadoop.hbase.HConstants;
045import org.apache.hadoop.hbase.NotServingRegionException;
046import org.apache.hadoop.hbase.RegionMetrics;
047import org.apache.hadoop.hbase.ScheduledChore;
048import org.apache.hadoop.hbase.ServerMetrics;
049import org.apache.hadoop.hbase.ServerMetricsBuilder;
050import org.apache.hadoop.hbase.ServerName;
051import org.apache.hadoop.hbase.YouAreDeadException;
052import org.apache.hadoop.hbase.client.AsyncClusterConnection;
053import org.apache.hadoop.hbase.client.AsyncRegionServerAdmin;
054import org.apache.hadoop.hbase.client.RegionInfo;
055import org.apache.hadoop.hbase.conf.ConfigurationObserver;
056import org.apache.hadoop.hbase.ipc.DecommissionedHostRejectedException;
057import org.apache.hadoop.hbase.ipc.RemoteWithExtrasException;
058import org.apache.hadoop.hbase.master.assignment.RegionStates;
059import org.apache.hadoop.hbase.master.procedure.ServerCrashProcedure;
060import org.apache.hadoop.hbase.monitoring.MonitoredTask;
061import org.apache.hadoop.hbase.procedure2.Procedure;
062import org.apache.hadoop.hbase.util.Bytes;
063import org.apache.hadoop.hbase.util.CommonFSUtils;
064import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
065import org.apache.hadoop.hbase.util.FutureUtils;
066import org.apache.hadoop.hbase.zookeeper.ZKUtil;
067import org.apache.hadoop.hbase.zookeeper.ZKWatcher;
068import org.apache.hadoop.hbase.zookeeper.ZNodePaths;
069import org.apache.yetus.audience.InterfaceAudience;
070import org.apache.zookeeper.KeeperException;
071import org.slf4j.Logger;
072import org.slf4j.LoggerFactory;
073
074import org.apache.hbase.thirdparty.com.google.protobuf.ByteString;
075import org.apache.hbase.thirdparty.com.google.protobuf.UnsafeByteOperations;
076
077import org.apache.hadoop.hbase.shaded.protobuf.ProtobufUtil;
078import org.apache.hadoop.hbase.shaded.protobuf.RequestConverter;
079import org.apache.hadoop.hbase.shaded.protobuf.generated.ClusterStatusProtos.RegionStoreSequenceIds;
080import org.apache.hadoop.hbase.shaded.protobuf.generated.ClusterStatusProtos.StoreSequenceId;
081import org.apache.hadoop.hbase.shaded.protobuf.generated.HBaseProtos.FlushedRegionSequenceId;
082import org.apache.hadoop.hbase.shaded.protobuf.generated.HBaseProtos.FlushedSequenceId;
083import org.apache.hadoop.hbase.shaded.protobuf.generated.HBaseProtos.FlushedStoreSequenceId;
084import org.apache.hadoop.hbase.shaded.protobuf.generated.RegionServerStatusProtos.RegionServerStartupRequest;
085
086/**
087 * The ServerManager class manages info about region servers.
088 * <p>
089 * Maintains lists of online and dead servers. Processes the startups, shutdowns, and deaths of
090 * region servers.
091 * <p>
092 * Servers are distinguished in two different ways. A given server has a location, specified by
093 * hostname and port, and of which there can only be one online at any given time. A server instance
094 * is specified by the location (hostname and port) as well as the startcode (timestamp from when
095 * the server was started). This is used to differentiate a restarted instance of a given server
096 * from the original instance.
097 * <p>
098 * If a sever is known not to be running any more, it is called dead. The dead server needs to be
099 * handled by a ServerShutdownHandler. If the handler is not enabled yet, the server can't be
100 * handled right away so it is queued up. After the handler is enabled, the server will be submitted
101 * to a handler to handle. However, the handler may be just partially enabled. If so, the server
102 * cannot be fully processed, and be queued up for further processing. A server is fully processed
103 * only after the handler is fully enabled and has completed the handling.
104 */
105@InterfaceAudience.Private
106public class ServerManager implements ConfigurationObserver {
107  public static final String WAIT_ON_REGIONSERVERS_MAXTOSTART =
108    "hbase.master.wait.on.regionservers.maxtostart";
109
110  public static final String WAIT_ON_REGIONSERVERS_MINTOSTART =
111    "hbase.master.wait.on.regionservers.mintostart";
112
113  public static final String WAIT_ON_REGIONSERVERS_TIMEOUT =
114    "hbase.master.wait.on.regionservers.timeout";
115
116  public static final String WAIT_ON_REGIONSERVERS_INTERVAL =
117    "hbase.master.wait.on.regionservers.interval";
118
119  /**
120   * see HBASE-20727 if set to true, flushedSequenceIdByRegion and storeFlushedSequenceIdsByRegion
121   * will be persisted to HDFS and loaded when master restart to speed up log split
122   */
123  public static final String PERSIST_FLUSHEDSEQUENCEID =
124    "hbase.master.persist.flushedsequenceid.enabled";
125
126  public static final boolean PERSIST_FLUSHEDSEQUENCEID_DEFAULT = true;
127
128  public static final String FLUSHEDSEQUENCEID_FLUSHER_INTERVAL =
129    "hbase.master.flushedsequenceid.flusher.interval";
130
131  public static final int FLUSHEDSEQUENCEID_FLUSHER_INTERVAL_DEFAULT = 3 * 60 * 60 * 1000; // 3
132                                                                                           // hours
133
134  public static final String MAX_CLOCK_SKEW_MS = "hbase.master.maxclockskew";
135  public static final long DEFAULT_MAX_CLOCK_SKEW_MS = 30000;
136
137  private static final Logger LOG = LoggerFactory.getLogger(ServerManager.class);
138
139  // Set if we are to shutdown the cluster.
140  private AtomicBoolean clusterShutdown = new AtomicBoolean(false);
141
142  /**
143   * The last flushed sequence id for a region.
144   */
145  private final ConcurrentNavigableMap<byte[], Long> flushedSequenceIdByRegion =
146    new ConcurrentSkipListMap<>(Bytes.BYTES_COMPARATOR);
147
148  private boolean persistFlushedSequenceId = true;
149  private volatile boolean isFlushSeqIdPersistInProgress = false;
150  /** File on hdfs to store last flushed sequence id of regions */
151  private static final String LAST_FLUSHED_SEQ_ID_FILE = ".lastflushedseqids";
152  private FlushedSequenceIdFlusher flushedSeqIdFlusher;
153
154  /**
155   * The last flushed sequence id for a store in a region.
156   */
157  private final ConcurrentNavigableMap<byte[],
158    ConcurrentNavigableMap<byte[], Long>> storeFlushedSequenceIdsByRegion =
159      new ConcurrentSkipListMap<>(Bytes.BYTES_COMPARATOR);
160
161  /** Map of registered servers to their current load */
162  private final ConcurrentNavigableMap<ServerName, ServerMetrics> onlineServers =
163    new ConcurrentSkipListMap<>();
164
165  /** List of region servers that should not get any more new regions. */
166  private final ArrayList<ServerName> drainingServers = new ArrayList<>();
167
168  private final MasterServices master;
169  private final RegionServerList storage;
170
171  private final DeadServer deadservers = new DeadServer();
172
173  private final long maxSkew;
174  private final long warningSkew;
175
176  /** Listeners that are called on server events. */
177  private List<ServerListener> listeners = new CopyOnWriteArrayList<>();
178
179  /** Configured value of HConstants.REJECT_DECOMMISSIONED_HOSTS_KEY */
180  private volatile boolean rejectDecommissionedHostsConfig;
181
182  /**
183   * Constructor.
184   */
185  public ServerManager(final MasterServices master, RegionServerList storage) {
186    this.master = master;
187    this.storage = storage;
188    Configuration c = master.getConfiguration();
189    maxSkew = c.getLong(MAX_CLOCK_SKEW_MS, DEFAULT_MAX_CLOCK_SKEW_MS);
190    warningSkew = c.getLong("hbase.master.warningclockskew", 10000);
191    persistFlushedSequenceId =
192      c.getBoolean(PERSIST_FLUSHEDSEQUENCEID, PERSIST_FLUSHEDSEQUENCEID_DEFAULT);
193    rejectDecommissionedHostsConfig = getRejectDecommissionedHostsConfig(c);
194  }
195
196  /**
197   * Implementation of the ConfigurationObserver interface. We are interested in live-loading the
198   * configuration value of HConstants.REJECT_DECOMMISSIONED_HOSTS_KEY
199   * @param conf Server configuration instance
200   */
201  @Override
202  public void onConfigurationChange(Configuration conf) {
203    final boolean newValue = getRejectDecommissionedHostsConfig(conf);
204    if (rejectDecommissionedHostsConfig == newValue) {
205      // no-op
206      return;
207    }
208
209    LOG.info("Config Reload for RejectDecommissionedHosts. previous value: {}, new value: {}",
210      rejectDecommissionedHostsConfig, newValue);
211
212    rejectDecommissionedHostsConfig = newValue;
213  }
214
215  /**
216   * Reads the value of HConstants.REJECT_DECOMMISSIONED_HOSTS_KEY from the config and returns it
217   * @param conf Configuration instance of the Master
218   */
219  public boolean getRejectDecommissionedHostsConfig(Configuration conf) {
220    return conf.getBoolean(HConstants.REJECT_DECOMMISSIONED_HOSTS_KEY,
221      HConstants.REJECT_DECOMMISSIONED_HOSTS_DEFAULT);
222  }
223
224  /**
225   * Add the listener to the notification list.
226   * @param listener The ServerListener to register
227   */
228  public void registerListener(final ServerListener listener) {
229    this.listeners.add(listener);
230  }
231
232  /**
233   * Remove the listener from the notification list.
234   * @param listener The ServerListener to unregister
235   */
236  public boolean unregisterListener(final ServerListener listener) {
237    return this.listeners.remove(listener);
238  }
239
240  /**
241   * Removes all of the ServerListeners of this collection that satisfy the given predicate.
242   * @param filter a predicate which returns true for ServerListener to be removed
243   */
244  public boolean unregisterListenerIf(final Predicate<ServerListener> filter) {
245    return this.listeners.removeIf(filter);
246  }
247
248  /**
249   * Let the server manager know a new regionserver has come online
250   * @param request       the startup request
251   * @param versionNumber the version number of the new regionserver
252   * @param version       the version of the new regionserver, could contain strings like "SNAPSHOT"
253   * @param ia            the InetAddress from which request is received
254   * @return The ServerName we know this server as.
255   */
256  ServerName regionServerStartup(RegionServerStartupRequest request, int versionNumber,
257    String version, InetAddress ia) throws IOException {
258    // Test for case where we get a region startup message from a regionserver
259    // that has been quickly restarted but whose znode expiration handler has
260    // not yet run, or from a server whose fail we are currently processing.
261    // Test its host+port combo is present in serverAddressToServerInfo. If it
262    // is, reject the server and trigger its expiration. The next time it comes
263    // in, it should have been removed from serverAddressToServerInfo and queued
264    // for processing by ProcessServerShutdown.
265
266    // if use-ip is enabled, we will use ip to expose Master/RS service for client,
267    // see HBASE-27304 for details.
268    boolean useIp = master.getConfiguration().getBoolean(HConstants.HBASE_SERVER_USEIP_ENABLED_KEY,
269      HConstants.HBASE_SERVER_USEIP_ENABLED_DEFAULT);
270    String isaHostName = useIp ? ia.getHostAddress() : ia.getHostName();
271    final String hostname =
272      request.hasUseThisHostnameInstead() ? request.getUseThisHostnameInstead() : isaHostName;
273    ServerName sn = ServerName.valueOf(hostname, request.getPort(), request.getServerStartCode());
274
275    // Check if the host should be rejected based on it's decommissioned status
276    checkRejectableDecommissionedStatus(sn);
277
278    checkClockSkew(sn, request.getServerCurrentTime());
279    checkIsDead(sn, "STARTUP");
280    if (!checkAndRecordNewServer(sn, ServerMetricsBuilder.of(sn, versionNumber, version))) {
281      LOG.warn("THIS SHOULD NOT HAPPEN, RegionServerStartup could not record the server: {}", sn);
282    }
283    storage.started(sn);
284    return sn;
285  }
286
287  /**
288   * Updates last flushed sequence Ids for the regions on server sn
289   */
290  private void updateLastFlushedSequenceIds(ServerName sn, ServerMetrics hsl) {
291    for (Entry<byte[], RegionMetrics> entry : hsl.getRegionMetrics().entrySet()) {
292      byte[] encodedRegionName = Bytes.toBytes(RegionInfo.encodeRegionName(entry.getKey()));
293      final long completedSeqId = entry.getValue().getCompletedSequenceId();
294      // Atomic read-modify-write so a concurrent advanceRegionFlushedSeq seed (which uses
295      // merge(Math::max)) cannot be clobbered by a stale in-flight heartbeat carrying a
296      // lower completedSequenceId. Don't let smaller sequence ids override greater ones.
297      flushedSequenceIdByRegion.compute(encodedRegionName, (k, existingValue) -> {
298        if (LOG.isTraceEnabled()) {
299          LOG.trace(Bytes.toString(k) + ", existingValue=" + existingValue + ", completeSequenceId="
300            + completedSeqId);
301        }
302        if (existingValue == null) {
303          return completedSeqId;
304        }
305        if (completedSeqId != HConstants.NO_SEQNUM && completedSeqId > existingValue) {
306          return completedSeqId;
307        }
308        if (completedSeqId != HConstants.NO_SEQNUM && completedSeqId < existingValue) {
309          LOG.warn("RegionServer " + sn + " indicates a last flushed sequence id (" + completedSeqId
310            + ") that is less than the previous last flushed sequence id (" + existingValue
311            + ") for region " + Bytes.toString(entry.getKey()) + " Ignoring.");
312        }
313        return existingValue;
314      });
315      ConcurrentNavigableMap<byte[], Long> storeFlushedSequenceId =
316        computeIfAbsent(storeFlushedSequenceIdsByRegion, encodedRegionName,
317          () -> new ConcurrentSkipListMap<>(Bytes.BYTES_COMPARATOR));
318      for (Entry<byte[], Long> storeSeqId : entry.getValue().getStoreSequenceId().entrySet()) {
319        byte[] family = storeSeqId.getKey();
320        final long storeCompletedSeqId = storeSeqId.getValue();
321        storeFlushedSequenceId.compute(family, (k, existingValue) -> {
322          if (LOG.isTraceEnabled()) {
323            LOG.trace(Bytes.toString(encodedRegionName) + ", family=" + Bytes.toString(k)
324              + ", existingValue=" + existingValue + ", completeSequenceId=" + storeCompletedSeqId);
325          }
326          if (existingValue == null) {
327            return storeCompletedSeqId;
328          }
329          if (
330            storeCompletedSeqId != HConstants.NO_SEQNUM
331              && storeCompletedSeqId > existingValue.longValue()
332          ) {
333            return storeCompletedSeqId;
334          }
335          return existingValue;
336        });
337      }
338    }
339  }
340
341  public void regionServerReport(ServerName sn, ServerMetrics sl) throws YouAreDeadException {
342    checkIsDead(sn, "REPORT");
343    if (null == this.onlineServers.replace(sn, sl)) {
344      // Already have this host+port combo and its just different start code?
345      // Just let the server in. Presume master joining a running cluster.
346      // recordNewServer is what happens at the end of reportServerStartup.
347      // The only thing we are skipping is passing back to the regionserver
348      // the ServerName to use. Here we presume a master has already done
349      // that so we'll press on with whatever it gave us for ServerName.
350      if (!checkAndRecordNewServer(sn, sl)) {
351        // Master already registered server with same (host + port) and higher startcode.
352        // This can happen if regionserver report comes late from old server
353        // (possible race condition), by that time master has already processed SCP for that
354        // server and started accepting regionserver report from new server i.e. server with
355        // same (host + port) and higher startcode.
356        // The exception thrown here is not meant to tell the region server it is dead because if
357        // there is a new server on the same host port, the old server should have already been
358        // dead in ideal situation.
359        // The exception thrown here is to skip the later steps of the whole regionServerReport
360        // request processing. Usually, after recording it in ServerManager, we will call the
361        // related methods in AssignmentManager to record region states. If the region server
362        // is already dead, we should not do these steps anymore, so here we throw an exception
363        // to let the upper layer know that they should not continue processing anymore.
364        final String errorMsg = "RegionServerReport received from " + sn
365          + ", but another server with the same name and higher startcode is already registered,"
366          + " ignoring";
367        LOG.warn(errorMsg);
368        throw new YouAreDeadException(errorMsg);
369      }
370    }
371    updateLastFlushedSequenceIds(sn, sl);
372  }
373
374  /**
375   * Checks if the Master is configured to reject decommissioned hosts or not. When it's configured
376   * to do so, any RegionServer trying to join the cluster will have it's host checked against the
377   * list of hosts of currently decommissioned servers and potentially get prevented from reporting
378   * for duty; otherwise, we do nothing and we let them pass to the next check. See HBASE-28342 for
379   * details.
380   * @param sn The ServerName to check for
381   * @throws DecommissionedHostRejectedException if the Master is configured to reject
382   *                                             decommissioned hosts and this host exists in the
383   *                                             list of the decommissioned servers
384   */
385  private void checkRejectableDecommissionedStatus(ServerName sn)
386    throws DecommissionedHostRejectedException {
387    LOG.info("Checking decommissioned status of RegionServer {}", sn.getServerName());
388
389    // If the Master is not configured to reject decommissioned hosts, return early.
390    if (!rejectDecommissionedHostsConfig) {
391      return;
392    }
393
394    // Look for a match for the hostname in the list of decommissioned servers
395    for (ServerName server : getDrainingServersList()) {
396      if (Objects.equals(server.getHostname(), sn.getHostname())) {
397        // Found a match and master is configured to reject decommissioned hosts, throw exception!
398        LOG.warn(
399          "Rejecting RegionServer {} from reporting for duty because Master is configured "
400            + "to reject decommissioned hosts and this host was marked as such in the past.",
401          sn.getServerName());
402        throw new DecommissionedHostRejectedException(String.format(
403          "Host %s exists in the list of decommissioned servers and Master is configured to "
404            + "reject decommissioned hosts",
405          sn.getHostname()));
406      }
407    }
408  }
409
410  /**
411   * Check is a server of same host and port already exists, if not, or the existed one got a
412   * smaller start code, record it.
413   * @param serverName the server to check and record
414   * @param sl         the server load on the server
415   * @return true if the server is recorded, otherwise, false
416   */
417  boolean checkAndRecordNewServer(final ServerName serverName, final ServerMetrics sl) {
418    ServerName existingServer = null;
419    synchronized (this.onlineServers) {
420      existingServer = findServerWithSameHostnamePortWithLock(serverName);
421      if (existingServer != null && (existingServer.getStartcode() > serverName.getStartcode())) {
422        LOG.info("Server serverName=" + serverName + " rejected; we already have "
423          + existingServer.toString() + " registered with same hostname and port");
424        return false;
425      }
426      recordNewServerWithLock(serverName, sl);
427    }
428
429    // Tell our listeners that a server was added
430    if (!this.listeners.isEmpty()) {
431      for (ServerListener listener : this.listeners) {
432        listener.serverAdded(serverName);
433      }
434    }
435
436    // Note that we assume that same ts means same server, and don't expire in that case.
437    // TODO: ts can theoretically collide due to clock shifts, so this is a bit hacky.
438    if (existingServer != null && (existingServer.getStartcode() < serverName.getStartcode())) {
439      LOG.info("Triggering server recovery; existingServer " + existingServer
440        + " looks stale, new server:" + serverName);
441      expireServer(existingServer);
442    }
443    return true;
444  }
445
446  /**
447   * Find out the region servers crashed between the crash of the previous master instance and the
448   * current master instance and schedule SCP for them.
449   * <p/>
450   * Since the {@code RegionServerTracker} has already helped us to construct the online servers set
451   * by scanning zookeeper, now we can compare the online servers with {@code liveServersFromWALDir}
452   * to find out whether there are servers which are already dead.
453   * <p/>
454   * Must be called inside the initialization method of {@code RegionServerTracker} to avoid
455   * concurrency issue.
456   * @param deadServersWithDeathTimeFromPE the region servers which already have an SCP associated,
457   *                                       have time of death as value.
458   * @param liveServersFromWALDir          the live region servers from wal directory.
459   */
460  void findDeadServersAndProcess(Map<ServerName, Long> deadServersWithDeathTimeFromPE,
461    Set<ServerName> liveServersFromWALDir) {
462    deadServersWithDeathTimeFromPE.forEach(deadservers::putIfAbsent);
463    liveServersFromWALDir.stream().filter(sn -> !onlineServers.containsKey(sn))
464      .forEach(this::expireServer);
465  }
466
467  /**
468   * Checks if the clock skew between the server and the master. If the clock skew exceeds the
469   * configured max, it will throw an exception; if it exceeds the configured warning threshold, it
470   * will log a warning but start normally.
471   * @param serverName Incoming servers's name
472   * @throws ClockOutOfSyncException if the skew exceeds the configured max value
473   */
474  private void checkClockSkew(final ServerName serverName, final long serverCurrentTime)
475    throws ClockOutOfSyncException {
476    long skew = Math.abs(EnvironmentEdgeManager.currentTime() - serverCurrentTime);
477    if (skew > maxSkew) {
478      String message = "Server " + serverName + " has been "
479        + "rejected; Reported time is too far out of sync with master.  " + "Time difference of "
480        + skew + "ms > max allowed of " + maxSkew + "ms";
481      LOG.warn(message);
482      throw new ClockOutOfSyncException(message);
483    } else if (skew > warningSkew) {
484      String message = "Reported time for server " + serverName + " is out of sync with master "
485        + "by " + skew + "ms. (Warning threshold is " + warningSkew + "ms; " + "error threshold is "
486        + maxSkew + "ms)";
487      LOG.warn(message);
488    }
489  }
490
491  /**
492   * Called when RegionServer first reports in for duty and thereafter each time it heartbeats to
493   * make sure it is has not been figured for dead. If this server is on the dead list, reject it
494   * with a YouAreDeadException. If it was dead but came back with a new start code, remove the old
495   * entry from the dead list.
496   * @param what START or REPORT
497   */
498  private void checkIsDead(final ServerName serverName, final String what)
499    throws YouAreDeadException {
500    if (this.deadservers.isDeadServer(serverName)) {
501      // Exact match: host name, port and start code all match with existing one of the
502      // dead servers. So, this server must be dead. Tell it to kill itself.
503      String message =
504        "Server " + what + " rejected; currently processing " + serverName + " as dead server";
505      LOG.debug(message);
506      throw new YouAreDeadException(message);
507    }
508    // Remove dead server with same hostname and port of newly checking in rs after master
509    // initialization. See HBASE-5916 for more information.
510    if (
511      (this.master == null || this.master.isInitialized())
512        && this.deadservers.cleanPreviousInstance(serverName)
513    ) {
514      // This server has now become alive after we marked it as dead.
515      // We removed it's previous entry from the dead list to reflect it.
516      LOG.debug("{} {} came back up, removed it from the dead servers list", what, serverName);
517    }
518  }
519
520  /**
521   * Assumes onlineServers is locked.
522   * @return ServerName with matching hostname and port.
523   */
524  public ServerName findServerWithSameHostnamePortWithLock(final ServerName serverName) {
525    ServerName end =
526      ServerName.valueOf(serverName.getHostname(), serverName.getPort(), Long.MAX_VALUE);
527
528    ServerName r = onlineServers.lowerKey(end);
529    if (r != null) {
530      if (ServerName.isSameAddress(r, serverName)) {
531        return r;
532      }
533    }
534    return null;
535  }
536
537  /**
538   * Adds the onlineServers list. onlineServers should be locked.
539   * @param serverName The remote servers name.
540   */
541  void recordNewServerWithLock(final ServerName serverName, final ServerMetrics sl) {
542    LOG.info("Registering regionserver=" + serverName);
543    this.onlineServers.put(serverName, sl);
544    master.getAssignmentManager().getRegionStates().createServer(serverName);
545  }
546
547  public ConcurrentNavigableMap<byte[], Long> getFlushedSequenceIdByRegion() {
548    return flushedSequenceIdByRegion;
549  }
550
551  public RegionStoreSequenceIds getLastFlushedSequenceId(byte[] encodedRegionName) {
552    RegionStoreSequenceIds.Builder builder = RegionStoreSequenceIds.newBuilder();
553    Long seqId = flushedSequenceIdByRegion.get(encodedRegionName);
554    builder.setLastFlushedSequenceId(seqId != null ? seqId.longValue() : HConstants.NO_SEQNUM);
555    Map<byte[], Long> storeFlushedSequenceId =
556      storeFlushedSequenceIdsByRegion.get(encodedRegionName);
557    if (storeFlushedSequenceId != null) {
558      for (Map.Entry<byte[], Long> entry : storeFlushedSequenceId.entrySet()) {
559        builder.addStoreSequenceId(StoreSequenceId.newBuilder()
560          .setFamilyName(UnsafeByteOperations.unsafeWrap(entry.getKey()))
561          .setSequenceId(entry.getValue().longValue()).build());
562      }
563    }
564    return builder.build();
565  }
566
567  /** Returns ServerMetrics if serverName is known else null */
568  public ServerMetrics getLoad(final ServerName serverName) {
569    return this.onlineServers.get(serverName);
570  }
571
572  /**
573   * Compute the average load across all region servers. Currently, this uses a very naive
574   * computation - just uses the number of regions being served, ignoring stats about number of
575   * requests.
576   * @return the average load
577   */
578  public double getAverageLoad() {
579    int totalLoad = 0;
580    int numServers = 0;
581    for (ServerMetrics sl : this.onlineServers.values()) {
582      numServers++;
583      totalLoad += sl.getRegionMetrics().size();
584    }
585    return numServers == 0 ? 0 : (double) totalLoad / (double) numServers;
586  }
587
588  /** Returns the count of active regionservers */
589  public int countOfRegionServers() {
590    // Presumes onlineServers is a concurrent map
591    return this.onlineServers.size();
592  }
593
594  /** Returns Read-only map of servers to serverinfo */
595  public Map<ServerName, ServerMetrics> getOnlineServers() {
596    // Presumption is that iterating the returned Map is OK.
597    synchronized (this.onlineServers) {
598      return Collections.unmodifiableMap(this.onlineServers);
599    }
600  }
601
602  public DeadServer getDeadServers() {
603    return this.deadservers;
604  }
605
606  /**
607   * Checks if any dead servers are currently in progress.
608   * @return true if any RS are being processed as dead, false if not
609   */
610  public boolean areDeadServersInProgress() throws IOException {
611    return master.getProcedures().stream()
612      .anyMatch(p -> !p.isFinished() && p instanceof ServerCrashProcedure);
613  }
614
615  void letRegionServersShutdown() {
616    long previousLogTime = 0;
617    ServerName sn = master.getServerName();
618    ZKWatcher zkw = master.getZooKeeper();
619    int onlineServersCt;
620    while ((onlineServersCt = onlineServers.size()) > 0) {
621      if (EnvironmentEdgeManager.currentTime() > (previousLogTime + 1000)) {
622        Set<ServerName> remainingServers = onlineServers.keySet();
623        synchronized (onlineServers) {
624          if (remainingServers.size() == 1 && remainingServers.contains(sn)) {
625            // Master will delete itself later.
626            return;
627          }
628        }
629        StringBuilder sb = new StringBuilder();
630        // It's ok here to not sync on onlineServers - merely logging
631        for (ServerName key : remainingServers) {
632          if (sb.length() > 0) {
633            sb.append(", ");
634          }
635          sb.append(key);
636        }
637        LOG.info("Waiting on regionserver(s) " + sb.toString());
638        previousLogTime = EnvironmentEdgeManager.currentTime();
639      }
640
641      try {
642        List<String> servers = getRegionServersInZK(zkw);
643        if (
644          servers == null || servers.isEmpty()
645            || (servers.size() == 1 && servers.contains(sn.toString()))
646        ) {
647          LOG.info("ZK shows there is only the master self online, exiting now");
648          // Master could have lost some ZK events, no need to wait more.
649          break;
650        }
651      } catch (KeeperException ke) {
652        LOG.warn("Failed to list regionservers", ke);
653        // ZK is malfunctioning, don't hang here
654        break;
655      }
656      synchronized (onlineServers) {
657        try {
658          if (onlineServersCt == onlineServers.size()) onlineServers.wait(100);
659        } catch (InterruptedException ignored) {
660          // continue
661        }
662      }
663    }
664  }
665
666  private List<String> getRegionServersInZK(final ZKWatcher zkw) throws KeeperException {
667    return ZKUtil.listChildrenNoWatch(zkw, zkw.getZNodePaths().rsZNode);
668  }
669
670  /**
671   * Expire the passed server. Add it to list of dead servers and queue a shutdown processing.
672   * @return pid if we queued a ServerCrashProcedure else {@link Procedure#NO_PROC_ID} if we did not
673   *         (could happen for many reasons including the fact that its this server that is going
674   *         down or we already have queued an SCP for this server or SCP processing is currently
675   *         disabled because we are in startup phase).
676   */
677  // Redo test so we can make this protected.
678  public synchronized long expireServer(final ServerName serverName) {
679    return expireServer(serverName, false);
680
681  }
682
683  synchronized long expireServer(final ServerName serverName, boolean force) {
684    // THIS server is going down... can't handle our own expiration.
685    if (serverName.equals(master.getServerName())) {
686      if (!(master.isAborted() || master.isStopped())) {
687        master.stop("We lost our znode?");
688      }
689      return Procedure.NO_PROC_ID;
690    }
691    if (this.deadservers.isDeadServer(serverName)) {
692      LOG.warn("Expiration called on {} but already in DeadServer", serverName);
693      return Procedure.NO_PROC_ID;
694    }
695    moveFromOnlineToDeadServers(serverName);
696
697    // If server is in draining mode, remove corresponding znode
698    // In some tests, the mocked HM may not have ZK Instance, hence null check
699    if (master.getZooKeeper() != null) {
700      String drainingZnode = ZNodePaths
701        .joinZNode(master.getZooKeeper().getZNodePaths().drainingZNode, serverName.getServerName());
702      try {
703        ZKUtil.deleteNodeFailSilent(master.getZooKeeper(), drainingZnode);
704      } catch (KeeperException e) {
705        LOG.warn(
706          "Error deleting the draining znode for stopping server " + serverName.getServerName(), e);
707      }
708    }
709
710    // If cluster is going down, yes, servers are going to be expiring; don't
711    // process as a dead server
712    if (isClusterShutdown()) {
713      LOG.info("Cluster shutdown set; " + serverName + " expired; onlineServers="
714        + this.onlineServers.size());
715      if (this.onlineServers.isEmpty()) {
716        master.stop("Cluster shutdown set; onlineServer=0");
717      }
718      return Procedure.NO_PROC_ID;
719    }
720    LOG.info("Processing expiration of " + serverName + " on " + this.master.getServerName());
721    long pid = master.getAssignmentManager().submitServerCrash(serverName, true, force);
722    if (pid == Procedure.NO_PROC_ID) {
723      // skip later processing as we failed to submit SCP
724      return Procedure.NO_PROC_ID;
725    }
726    storage.expired(serverName);
727    // Tell our listeners that a server was removed
728    if (!this.listeners.isEmpty()) {
729      this.listeners.stream().forEach(l -> l.serverRemoved(serverName));
730    }
731    // trigger a persist of flushedSeqId
732    if (flushedSeqIdFlusher != null) {
733      flushedSeqIdFlusher.triggerNow();
734    }
735    return pid;
736  }
737
738  /**
739   * Called when server has expired.
740   */
741  // Locking in this class needs cleanup.
742  public synchronized void moveFromOnlineToDeadServers(final ServerName sn) {
743    synchronized (this.onlineServers) {
744      boolean online = this.onlineServers.containsKey(sn);
745      if (online) {
746        // Remove the server from the known servers lists and update load info BUT
747        // add to deadservers first; do this so it'll show in dead servers list if
748        // not in online servers list.
749        this.deadservers.putIfAbsent(sn);
750        this.onlineServers.remove(sn);
751        onlineServers.notifyAll();
752      } else {
753        // If not online, that is odd but may happen if 'Unknown Servers' -- where meta
754        // has references to servers not online nor in dead servers list. If
755        // 'Unknown Server', don't add to DeadServers else will be there for ever.
756        LOG.trace("Expiration of {} but server not online", sn);
757      }
758    }
759  }
760
761  /*
762   * Remove the server from the drain list.
763   */
764  public synchronized boolean removeServerFromDrainList(final ServerName sn) {
765    LOG.info("Removing server {} from the draining list.", sn);
766
767    // Remove the server from the draining servers lists.
768    return this.drainingServers.remove(sn);
769  }
770
771  /**
772   * Add the server to the drain list.
773   * @return True if the server is added or the server is already on the drain list.
774   */
775  public synchronized boolean addServerToDrainList(final ServerName sn) {
776    // If master is not rejecting decommissioned hosts, warn if the server (sn) is not online.
777    // However, we want to add servers even if they're not online if the master is configured
778    // to reject decommissioned hosts
779    if (!rejectDecommissionedHostsConfig && !this.isServerOnline(sn)) {
780      LOG.warn("Server {} is not currently online. Ignoring request to add it to draining list.",
781        sn);
782      return false;
783    }
784
785    // Add the server to the draining servers lists, if it's not already in it.
786    if (this.drainingServers.contains(sn)) {
787      LOG.warn(
788        "Server {} is already in the draining server list. Ignoring request to add it again.", sn);
789      return true;
790    }
791
792    LOG.info("Server {} added to draining server list.", sn);
793    return this.drainingServers.add(sn);
794  }
795
796  /**
797   * Contacts a region server and waits up to timeout ms to close the region. This bypasses the
798   * active hmaster. Pass -1 as timeout if you do not want to wait on result.
799   */
800  public static void closeRegionSilentlyAndWait(AsyncClusterConnection connection,
801    ServerName server, RegionInfo region, long timeout) throws IOException, InterruptedException {
802    AsyncRegionServerAdmin admin = connection.getRegionServerAdmin(server);
803    try {
804      FutureUtils.get(
805        admin.closeRegion(ProtobufUtil.buildCloseRegionRequest(server, region.getRegionName())));
806    } catch (IOException e) {
807      LOG.warn("Exception when closing region: " + region.getRegionNameAsString(), e);
808    }
809    if (timeout < 0) {
810      return;
811    }
812    long expiration = timeout + EnvironmentEdgeManager.currentTime();
813    while (EnvironmentEdgeManager.currentTime() < expiration) {
814      try {
815        RegionInfo rsRegion = ProtobufUtil.toRegionInfo(FutureUtils
816          .get(
817            admin.getRegionInfo(RequestConverter.buildGetRegionInfoRequest(region.getRegionName())))
818          .getRegionInfo());
819        if (rsRegion == null) {
820          return;
821        }
822      } catch (IOException ioe) {
823        if (
824          ioe instanceof NotServingRegionException
825            || (ioe instanceof RemoteWithExtrasException && ((RemoteWithExtrasException) ioe)
826              .unwrapRemoteException() instanceof NotServingRegionException)
827        ) {
828          // no need to retry again
829          return;
830        }
831        LOG.warn("Exception when retrieving regioninfo from: " + region.getRegionNameAsString(),
832          ioe);
833      }
834      Thread.sleep(1000);
835    }
836    throw new IOException("Region " + region + " failed to close within" + " timeout " + timeout);
837  }
838
839  /**
840   * Calculate min necessary to start. This is not an absolute. It is just a friction that will
841   * cause us hang around a bit longer waiting on RegionServers to check-in.
842   */
843  private int getMinToStart() {
844    if (master.isInMaintenanceMode()) {
845      // If in maintenance mode, then in process region server hosting meta will be the only server
846      // available
847      return 1;
848    }
849
850    int minimumRequired = 1;
851    int minToStart = this.master.getConfiguration().getInt(WAIT_ON_REGIONSERVERS_MINTOSTART, -1);
852    // Ensure we are never less than minimumRequired else stuff won't work.
853    return Math.max(minToStart, minimumRequired);
854  }
855
856  /**
857   * Wait for the region servers to report in. We will wait until one of this condition is met: -
858   * the master is stopped - the 'hbase.master.wait.on.regionservers.maxtostart' number of region
859   * servers is reached - the 'hbase.master.wait.on.regionservers.mintostart' is reached AND there
860   * have been no new region server in for 'hbase.master.wait.on.regionservers.interval' time AND
861   * the 'hbase.master.wait.on.regionservers.timeout' is reached
862   */
863  public void waitForRegionServers(MonitoredTask status) throws InterruptedException {
864    final long interval =
865      this.master.getConfiguration().getLong(WAIT_ON_REGIONSERVERS_INTERVAL, 1500);
866    final long timeout =
867      this.master.getConfiguration().getLong(WAIT_ON_REGIONSERVERS_TIMEOUT, 4500);
868    // Min is not an absolute; just a friction making us wait longer on server checkin.
869    int minToStart = getMinToStart();
870    int maxToStart =
871      this.master.getConfiguration().getInt(WAIT_ON_REGIONSERVERS_MAXTOSTART, Integer.MAX_VALUE);
872    if (maxToStart < minToStart) {
873      LOG.warn(String.format("The value of '%s' (%d) is set less than '%s' (%d), ignoring.",
874        WAIT_ON_REGIONSERVERS_MAXTOSTART, maxToStart, WAIT_ON_REGIONSERVERS_MINTOSTART,
875        minToStart));
876      maxToStart = Integer.MAX_VALUE;
877    }
878
879    long now = EnvironmentEdgeManager.currentTime();
880    final long startTime = now;
881    long slept = 0;
882    long lastLogTime = 0;
883    long lastCountChange = startTime;
884    int count = countOfRegionServers();
885    int oldCount = 0;
886    // This while test is a little hard to read. We try to comment it in below but in essence:
887    // Wait if Master is not stopped and the number of regionservers that have checked-in is
888    // less than the maxToStart. Both of these conditions will be true near universally.
889    // Next, we will keep cycling if ANY of the following three conditions are true:
890    // 1. The time since a regionserver registered is < interval (means servers are actively
891    // checking in).
892    // 2. We are under the total timeout.
893    // 3. The count of servers is < minimum.
894    for (ServerListener listener : this.listeners) {
895      listener.waiting();
896    }
897    while (
898      !this.master.isStopped() && !isClusterShutdown() && count < maxToStart
899        && ((lastCountChange + interval) > now || timeout > slept || count < minToStart)
900    ) {
901      // Log some info at every interval time or if there is a change
902      if (oldCount != count || lastLogTime + interval < now) {
903        lastLogTime = now;
904        String msg =
905          "Waiting on regionserver count=" + count + "; waited=" + slept + "ms, expecting min="
906            + minToStart + " server(s), max=" + getStrForMax(maxToStart) + " server(s), "
907            + "timeout=" + timeout + "ms, lastChange=" + (now - lastCountChange) + "ms";
908        LOG.info(msg);
909        status.setStatus(msg);
910      }
911
912      // We sleep for some time
913      final long sleepTime = 50;
914      Thread.sleep(sleepTime);
915      now = EnvironmentEdgeManager.currentTime();
916      slept = now - startTime;
917
918      oldCount = count;
919      count = countOfRegionServers();
920      if (count != oldCount) {
921        lastCountChange = now;
922      }
923    }
924    // Did we exit the loop because cluster is going down?
925    if (isClusterShutdown()) {
926      this.master.stop("Cluster shutdown");
927    }
928    LOG.info("Finished waiting on RegionServer count=" + count + "; waited=" + slept + "ms,"
929      + " expected min=" + minToStart + " server(s), max=" + getStrForMax(maxToStart)
930      + " server(s)," + " master is " + (this.master.isStopped() ? "stopped." : "running"));
931  }
932
933  private String getStrForMax(final int max) {
934    return max == Integer.MAX_VALUE ? "NO_LIMIT" : Integer.toString(max);
935  }
936
937  /** Returns A copy of the internal list of online servers. */
938  public List<ServerName> getOnlineServersList() {
939    // TODO: optimize the load balancer call so we don't need to make a new list
940    // TODO: FIX. THIS IS POPULAR CALL.
941    return new ArrayList<>(this.onlineServers.keySet());
942  }
943
944  /**
945   * @param keys                 The target server name
946   * @param idleServerPredicator Evaluates the server on the given load
947   * @return A copy of the internal list of online servers matched by the predicator
948   */
949  public List<ServerName> getOnlineServersListWithPredicator(List<ServerName> keys,
950    Predicate<ServerMetrics> idleServerPredicator) {
951    List<ServerName> names = new ArrayList<>();
952    if (keys != null && idleServerPredicator != null) {
953      keys.forEach(name -> {
954        ServerMetrics load = onlineServers.get(name);
955        if (load != null) {
956          if (idleServerPredicator.test(load)) {
957            names.add(name);
958          }
959        }
960      });
961    }
962    return names;
963  }
964
965  /** Returns A copy of the internal list of draining servers. */
966  public List<ServerName> getDrainingServersList() {
967    return new ArrayList<>(this.drainingServers);
968  }
969
970  public boolean isServerOnline(ServerName serverName) {
971    return serverName != null && onlineServers.containsKey(serverName);
972  }
973
974  public enum ServerLiveState {
975    LIVE,
976    DEAD,
977    UNKNOWN
978  }
979
980  /** Returns whether the server is online, dead, or unknown. */
981  public synchronized ServerLiveState isServerKnownAndOnline(ServerName serverName) {
982    return onlineServers.containsKey(serverName)
983      ? ServerLiveState.LIVE
984      : (deadservers.isDeadServer(serverName) ? ServerLiveState.DEAD : ServerLiveState.UNKNOWN);
985  }
986
987  /**
988   * Check if a server is known to be dead. A server can be online, or known to be dead, or unknown
989   * to this manager (i.e, not online, not known to be dead either; it is simply not tracked by the
990   * master any more, for example, a very old previous instance).
991   */
992  public synchronized boolean isServerDead(ServerName serverName) {
993    return serverName == null || deadservers.isDeadServer(serverName);
994  }
995
996  /**
997   * Check if a server is unknown. A server can be online, or known to be dead, or unknown to this
998   * manager (i.e, not online, not known to be dead either; it is simply not tracked by the master
999   * anymore, for example, a very old previous instance). A serverName with value null should not be
1000   * considered unknown. We set value of regionLocation to null just before finding the assign
1001   * candidate (in-between region transition) or while marking it OFFLINE/FAILED_OPEN. Refer
1002   * HBASE-30142.
1003   */
1004  public boolean isServerUnknown(ServerName serverName) {
1005    return serverName != null
1006      && (!onlineServers.containsKey(serverName) && !deadservers.isDeadServer(serverName));
1007  }
1008
1009  public void shutdownCluster() {
1010    String statusStr = "Cluster shutdown requested of master=" + this.master.getServerName();
1011    LOG.info(statusStr);
1012    this.clusterShutdown.set(true);
1013    if (onlineServers.isEmpty()) {
1014      // we do not synchronize here so this may cause a double stop, but not a big deal
1015      master.stop("OnlineServer=0 right after cluster shutdown set");
1016    }
1017  }
1018
1019  public boolean isClusterShutdown() {
1020    return this.clusterShutdown.get();
1021  }
1022
1023  /**
1024   * start chore in ServerManager
1025   */
1026  public void startChore() {
1027    Configuration c = master.getConfiguration();
1028    if (persistFlushedSequenceId) {
1029      new Thread(() -> {
1030        // after AM#loadMeta, RegionStates should be loaded, and some regions are
1031        // deleted by drop/split/merge during removeDeletedRegionFromLoadedFlushedSequenceIds,
1032        // but these deleted regions are not added back to RegionStates,
1033        // so we can safely remove deleted regions.
1034        removeDeletedRegionFromLoadedFlushedSequenceIds();
1035      }, "RemoveDeletedRegionSyncThread").start();
1036      int flushPeriod =
1037        c.getInt(FLUSHEDSEQUENCEID_FLUSHER_INTERVAL, FLUSHEDSEQUENCEID_FLUSHER_INTERVAL_DEFAULT);
1038      flushedSeqIdFlusher = new FlushedSequenceIdFlusher("FlushedSequenceIdFlusher", flushPeriod);
1039      master.getChoreService().scheduleChore(flushedSeqIdFlusher);
1040    }
1041  }
1042
1043  /**
1044   * Stop the ServerManager.
1045   */
1046  public void stop() {
1047    if (flushedSeqIdFlusher != null) {
1048      flushedSeqIdFlusher.shutdown();
1049    }
1050    if (persistFlushedSequenceId) {
1051      try {
1052        persistRegionLastFlushedSequenceIds();
1053      } catch (IOException e) {
1054        LOG.warn("Failed to persist last flushed sequence id of regions" + " to file system", e);
1055      }
1056    }
1057  }
1058
1059  /**
1060   * Creates a list of possible destinations for a region. It contains the online servers, but not
1061   * the draining or dying servers.
1062   * @param serversToExclude can be null if there is no server to exclude
1063   */
1064  public List<ServerName> createDestinationServersList(final List<ServerName> serversToExclude) {
1065    Set<ServerName> destServers = new HashSet<>();
1066    onlineServers.forEach((sn, sm) -> {
1067      if (sm.getLastReportTimestamp() > 0) {
1068        // This means we have already called regionServerReport at leaset once, then let's include
1069        // this server for region assignment. This is an optimization to avoid assigning regions to
1070        // an uninitialized server. See HBASE-25032 for more details.
1071        destServers.add(sn);
1072      }
1073    });
1074
1075    if (serversToExclude != null) {
1076      destServers.removeAll(serversToExclude);
1077    }
1078
1079    // Loop through the draining server list and remove them from the server list
1080    final List<ServerName> drainingServersCopy = getDrainingServersList();
1081    destServers.removeAll(drainingServersCopy);
1082
1083    return new ArrayList<>(destServers);
1084  }
1085
1086  /**
1087   * Calls {@link #createDestinationServersList} without server to exclude.
1088   */
1089  public List<ServerName> createDestinationServersList() {
1090    return createDestinationServersList(null);
1091  }
1092
1093  /**
1094   * To clear any dead server with same host name and port of any online server
1095   */
1096  void clearDeadServersWithSameHostNameAndPortOfOnlineServer() {
1097    for (ServerName serverName : getOnlineServersList()) {
1098      deadservers.cleanAllPreviousInstances(serverName);
1099    }
1100  }
1101
1102  /**
1103   * Called by delete table and similar to notify the ServerManager that a region was removed.
1104   */
1105  public void removeRegion(final RegionInfo regionInfo) {
1106    final byte[] encodedName = regionInfo.getEncodedNameAsBytes();
1107    storeFlushedSequenceIdsByRegion.remove(encodedName);
1108    flushedSequenceIdByRegion.remove(encodedName);
1109  }
1110
1111  /**
1112   * Advances {@link #flushedSequenceIdByRegion} for the region to at least {@code flushedSeqId}.
1113   * Called on region OPEN with the region's {@code openSeqNum} (HBASE-30335) and on region CLOSE
1114   * with the region's final durable flushed seqid (HBASE-30433). Without this, the entry stays
1115   * absent or stale until the hosting server's next heartbeat, so {@link #getLastFlushedSequenceId}
1116   * may return {@link HConstants#NO_SEQNUM} or a too-low value and WALSplitter conservatively
1117   * treats already-durable edits as unflushed - producing orphaned recovered.edits when the source
1118   * server crashes soon after a drain-move or close. Uses {@code merge} with {@link Math#max} so a
1119   * heartbeat-supplied value is never regressed - and, unlike {@code putIfAbsent}, a stale-low
1120   * prior value is lifted to {@code flushedSeqId}. Safe because both callers pass a seqid at or
1121   * below what the region has actually made durable.
1122   */
1123  public void advanceRegionFlushedSeq(final RegionInfo regionInfo, final long flushedSeqId) {
1124    if (flushedSeqId < 0) { // NO_SEQNUM == -1
1125      return;
1126    }
1127    flushedSequenceIdByRegion.merge(regionInfo.getEncodedNameAsBytes(), flushedSeqId, Math::max);
1128  }
1129
1130  public boolean isRegionInServerManagerStates(final RegionInfo hri) {
1131    final byte[] encodedName = hri.getEncodedNameAsBytes();
1132    return (storeFlushedSequenceIdsByRegion.containsKey(encodedName)
1133      || flushedSequenceIdByRegion.containsKey(encodedName));
1134  }
1135
1136  /**
1137   * Called by delete table and similar to notify the ServerManager that a region was removed.
1138   */
1139  public void removeRegions(final List<RegionInfo> regions) {
1140    for (RegionInfo hri : regions) {
1141      removeRegion(hri);
1142    }
1143  }
1144
1145  /**
1146   * May return 0 when server is not online.
1147   */
1148  public int getVersionNumber(ServerName serverName) {
1149    ServerMetrics serverMetrics = onlineServers.get(serverName);
1150    return serverMetrics != null ? serverMetrics.getVersionNumber() : 0;
1151  }
1152
1153  /**
1154   * May return "0.0.0" when server is not online
1155   */
1156  public String getVersion(ServerName serverName) {
1157    ServerMetrics serverMetrics = onlineServers.get(serverName);
1158    return serverMetrics != null ? serverMetrics.getVersion() : "0.0.0";
1159  }
1160
1161  public int getInfoPort(ServerName serverName) {
1162    ServerMetrics serverMetrics = onlineServers.get(serverName);
1163    return serverMetrics != null ? serverMetrics.getInfoServerPort() : 0;
1164  }
1165
1166  /**
1167   * Persist last flushed sequence id of each region to HDFS
1168   * @throws IOException if persit to HDFS fails
1169   */
1170  private void persistRegionLastFlushedSequenceIds() throws IOException {
1171    if (isFlushSeqIdPersistInProgress) {
1172      return;
1173    }
1174    isFlushSeqIdPersistInProgress = true;
1175    try {
1176      Configuration conf = master.getConfiguration();
1177      Path rootDir = CommonFSUtils.getRootDir(conf);
1178      Path lastFlushedSeqIdPath = new Path(rootDir, LAST_FLUSHED_SEQ_ID_FILE);
1179      FileSystem fs = FileSystem.get(conf);
1180      if (fs.exists(lastFlushedSeqIdPath)) {
1181        LOG.info("Rewriting .lastflushedseqids file at: " + lastFlushedSeqIdPath);
1182        if (!fs.delete(lastFlushedSeqIdPath, false)) {
1183          throw new IOException("Unable to remove existing " + lastFlushedSeqIdPath);
1184        }
1185      } else {
1186        LOG.info("Writing .lastflushedseqids file at: " + lastFlushedSeqIdPath);
1187      }
1188      FSDataOutputStream out = fs.create(lastFlushedSeqIdPath);
1189      FlushedSequenceId.Builder flushedSequenceIdBuilder = FlushedSequenceId.newBuilder();
1190      try {
1191        for (Entry<byte[], Long> entry : flushedSequenceIdByRegion.entrySet()) {
1192          FlushedRegionSequenceId.Builder flushedRegionSequenceIdBuilder =
1193            FlushedRegionSequenceId.newBuilder();
1194          flushedRegionSequenceIdBuilder.setRegionEncodedName(ByteString.copyFrom(entry.getKey()));
1195          flushedRegionSequenceIdBuilder.setSeqId(entry.getValue());
1196          ConcurrentNavigableMap<byte[], Long> storeSeqIds =
1197            storeFlushedSequenceIdsByRegion.get(entry.getKey());
1198          if (storeSeqIds != null) {
1199            for (Entry<byte[], Long> store : storeSeqIds.entrySet()) {
1200              FlushedStoreSequenceId.Builder flushedStoreSequenceIdBuilder =
1201                FlushedStoreSequenceId.newBuilder();
1202              flushedStoreSequenceIdBuilder.setFamily(ByteString.copyFrom(store.getKey()));
1203              flushedStoreSequenceIdBuilder.setSeqId(store.getValue());
1204              flushedRegionSequenceIdBuilder.addStores(flushedStoreSequenceIdBuilder);
1205            }
1206          }
1207          flushedSequenceIdBuilder.addRegionSequenceId(flushedRegionSequenceIdBuilder);
1208        }
1209        flushedSequenceIdBuilder.build().writeDelimitedTo(out);
1210      } finally {
1211        if (out != null) {
1212          out.close();
1213        }
1214      }
1215    } finally {
1216      isFlushSeqIdPersistInProgress = false;
1217    }
1218  }
1219
1220  /**
1221   * Load last flushed sequence id of each region from HDFS, if persisted
1222   */
1223  public void loadLastFlushedSequenceIds() throws IOException {
1224    if (!persistFlushedSequenceId) {
1225      return;
1226    }
1227    Configuration conf = master.getConfiguration();
1228    Path rootDir = CommonFSUtils.getRootDir(conf);
1229    Path lastFlushedSeqIdPath = new Path(rootDir, LAST_FLUSHED_SEQ_ID_FILE);
1230    FileSystem fs = FileSystem.get(conf);
1231    if (!fs.exists(lastFlushedSeqIdPath)) {
1232      LOG.info("No .lastflushedseqids found at " + lastFlushedSeqIdPath
1233        + " will record last flushed sequence id"
1234        + " for regions by regionserver report all over again");
1235      return;
1236    } else {
1237      LOG.info("begin to load .lastflushedseqids at " + lastFlushedSeqIdPath);
1238    }
1239    FSDataInputStream in = fs.open(lastFlushedSeqIdPath);
1240    try {
1241      FlushedSequenceId flushedSequenceId = FlushedSequenceId.parseDelimitedFrom(in);
1242      if (flushedSequenceId == null) {
1243        LOG.info(".lastflushedseqids found at {} is empty", lastFlushedSeqIdPath);
1244        return;
1245      }
1246      for (FlushedRegionSequenceId flushedRegionSequenceId : flushedSequenceId
1247        .getRegionSequenceIdList()) {
1248        byte[] encodedRegionName = flushedRegionSequenceId.getRegionEncodedName().toByteArray();
1249        flushedSequenceIdByRegion.putIfAbsent(encodedRegionName,
1250          flushedRegionSequenceId.getSeqId());
1251        if (
1252          flushedRegionSequenceId.getStoresList() != null
1253            && flushedRegionSequenceId.getStoresList().size() != 0
1254        ) {
1255          ConcurrentNavigableMap<byte[], Long> storeFlushedSequenceId =
1256            computeIfAbsent(storeFlushedSequenceIdsByRegion, encodedRegionName,
1257              () -> new ConcurrentSkipListMap<>(Bytes.BYTES_COMPARATOR));
1258          for (FlushedStoreSequenceId flushedStoreSequenceId : flushedRegionSequenceId
1259            .getStoresList()) {
1260            storeFlushedSequenceId.put(flushedStoreSequenceId.getFamily().toByteArray(),
1261              flushedStoreSequenceId.getSeqId());
1262          }
1263        }
1264      }
1265    } finally {
1266      in.close();
1267    }
1268  }
1269
1270  /**
1271   * Regions may have been removed between latest persist of FlushedSequenceIds and master abort. So
1272   * after loading FlushedSequenceIds from file, and after meta loaded, we need to remove the
1273   * deleted region according to RegionStates.
1274   */
1275  public void removeDeletedRegionFromLoadedFlushedSequenceIds() {
1276    RegionStates regionStates = master.getAssignmentManager().getRegionStates();
1277    Iterator<byte[]> it = flushedSequenceIdByRegion.keySet().iterator();
1278    while (it.hasNext()) {
1279      byte[] regionEncodedName = it.next();
1280      if (regionStates.getRegionState(Bytes.toStringBinary(regionEncodedName)) == null) {
1281        it.remove();
1282        storeFlushedSequenceIdsByRegion.remove(regionEncodedName);
1283      }
1284    }
1285  }
1286
1287  private class FlushedSequenceIdFlusher extends ScheduledChore {
1288
1289    public FlushedSequenceIdFlusher(String name, int p) {
1290      super(name, master, p, 60 * 1000); // delay one minute before first execute
1291    }
1292
1293    @Override
1294    protected void chore() {
1295      try {
1296        persistRegionLastFlushedSequenceIds();
1297      } catch (IOException e) {
1298        LOG.debug("Failed to persist last flushed sequence id of regions" + " to file system", e);
1299      }
1300    }
1301  }
1302}