View Javadoc

1   /**
2    *
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *     http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing, software
14   * distributed under the License is distributed on an "AS IS" BASIS,
15   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16   * See the License for the specific language governing permissions and
17   * limitations under the License.
18   */
19  package org.apache.hadoop.hbase.master;
20  
21  import java.io.IOException;
22  import java.net.InetAddress;
23  import java.util.ArrayList;
24  import java.util.Collections;
25  import java.util.HashMap;
26  import java.util.HashSet;
27  import java.util.Iterator;
28  import java.util.List;
29  import java.util.Map;
30  import java.util.Map.Entry;
31  import java.util.Set;
32  import java.util.concurrent.ConcurrentHashMap;
33  import java.util.concurrent.ConcurrentNavigableMap;
34  import java.util.concurrent.ConcurrentSkipListMap;
35  import java.util.concurrent.CopyOnWriteArrayList;
36  
37  import org.apache.commons.logging.Log;
38  import org.apache.commons.logging.LogFactory;
39  import org.apache.hadoop.conf.Configuration;
40  import org.apache.hadoop.hbase.ClockOutOfSyncException;
41  import org.apache.hadoop.hbase.HConstants;
42  import org.apache.hadoop.hbase.HRegionInfo;
43  import org.apache.hadoop.hbase.NotServingRegionException;
44  import org.apache.hadoop.hbase.RegionLoad;
45  import org.apache.hadoop.hbase.Server;
46  import org.apache.hadoop.hbase.ServerLoad;
47  import org.apache.hadoop.hbase.ServerName;
48  import org.apache.hadoop.hbase.YouAreDeadException;
49  import org.apache.hadoop.hbase.ZooKeeperConnectionException;
50  import org.apache.hadoop.hbase.classification.InterfaceAudience;
51  import org.apache.hadoop.hbase.client.ClusterConnection;
52  import org.apache.hadoop.hbase.client.ConnectionFactory;
53  import org.apache.hadoop.hbase.client.RetriesExhaustedException;
54  import org.apache.hadoop.hbase.ipc.PayloadCarryingRpcController;
55  import org.apache.hadoop.hbase.ipc.RpcControllerFactory;
56  import org.apache.hadoop.hbase.master.balancer.BaseLoadBalancer;
57  import org.apache.hadoop.hbase.master.procedure.MasterProcedureEnv;
58  import org.apache.hadoop.hbase.master.procedure.ServerCrashProcedure;
59  import org.apache.hadoop.hbase.monitoring.MonitoredTask;
60  import org.apache.hadoop.hbase.procedure2.ProcedureExecutor;
61  import org.apache.hadoop.hbase.protobuf.ProtobufUtil;
62  import org.apache.hadoop.hbase.protobuf.RequestConverter;
63  import org.apache.hadoop.hbase.protobuf.ResponseConverter;
64  import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.AdminService;
65  import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.OpenRegionRequest;
66  import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.OpenRegionResponse;
67  import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.ServerInfo;
68  import org.apache.hadoop.hbase.protobuf.generated.RegionServerStatusProtos.RegionServerStartupRequest;
69  import org.apache.hadoop.hbase.protobuf.generated.ClusterStatusProtos.RegionStoreSequenceIds;
70  import org.apache.hadoop.hbase.protobuf.generated.ClusterStatusProtos.StoreSequenceId;
71  import org.apache.hadoop.hbase.protobuf.generated.ZooKeeperProtos.SplitLogTask.RecoveryMode;
72  import org.apache.hadoop.hbase.regionserver.HRegionServer;
73  import org.apache.hadoop.hbase.regionserver.RegionOpeningState;
74  import org.apache.hadoop.hbase.security.User;
75  import org.apache.hadoop.hbase.util.Bytes;
76  import org.apache.hadoop.hbase.util.Triple;
77  import org.apache.hadoop.hbase.util.RetryCounter;
78  import org.apache.hadoop.hbase.util.RetryCounterFactory;
79  import org.apache.hadoop.hbase.zookeeper.ZKUtil;
80  import org.apache.hadoop.hbase.zookeeper.ZooKeeperWatcher;
81  import org.apache.zookeeper.KeeperException;
82  
83  import com.google.common.annotations.VisibleForTesting;
84  import com.google.protobuf.ByteString;
85  import com.google.protobuf.ServiceException;
86  
87  /**
88   * The ServerManager class manages info about region servers.
89   * <p>
90   * Maintains lists of online and dead servers.  Processes the startups,
91   * shutdowns, and deaths of region servers.
92   * <p>
93   * Servers are distinguished in two different ways.  A given server has a
94   * location, specified by hostname and port, and of which there can only be one
95   * online at any given time.  A server instance is specified by the location
96   * (hostname and port) as well as the startcode (timestamp from when the server
97   * was started).  This is used to differentiate a restarted instance of a given
98   * server from the original instance.
99   * <p>
100  * If a sever is known not to be running any more, it is called dead. The dead
101  * server needs to be handled by a ServerShutdownHandler.  If the handler is not
102  * enabled yet, the server can't be handled right away so it is queued up.
103  * After the handler is enabled, the server will be submitted to a handler to handle.
104  * However, the handler may be just partially enabled.  If so,
105  * the server cannot be fully processed, and be queued up for further processing.
106  * A server is fully processed only after the handler is fully enabled
107  * and has completed the handling.
108  */
109 @InterfaceAudience.Private
110 public class ServerManager {
111   public static final String WAIT_ON_REGIONSERVERS_MAXTOSTART =
112       "hbase.master.wait.on.regionservers.maxtostart";
113 
114   public static final String WAIT_ON_REGIONSERVERS_MINTOSTART =
115       "hbase.master.wait.on.regionservers.mintostart";
116 
117   public static final String WAIT_ON_REGIONSERVERS_TIMEOUT =
118       "hbase.master.wait.on.regionservers.timeout";
119 
120   public static final String WAIT_ON_REGIONSERVERS_INTERVAL =
121       "hbase.master.wait.on.regionservers.interval";
122 
123   private static final Log LOG = LogFactory.getLog(ServerManager.class);
124 
125   // Set if we are to shutdown the cluster.
126   private volatile boolean clusterShutdown = false;
127 
128   /**
129    * The last flushed sequence id for a region.
130    */
131   private final ConcurrentNavigableMap<byte[], Long> flushedSequenceIdByRegion =
132     new ConcurrentSkipListMap<byte[], Long>(Bytes.BYTES_COMPARATOR);
133 
134   /**
135    * The last flushed sequence id for a store in a region.
136    */
137   private final ConcurrentNavigableMap<byte[], ConcurrentNavigableMap<byte[], Long>>
138     storeFlushedSequenceIdsByRegion =
139     new ConcurrentSkipListMap<byte[], ConcurrentNavigableMap<byte[], Long>>(Bytes.BYTES_COMPARATOR);
140 
141   /** Map of registered servers to their current load */
142   private final ConcurrentHashMap<ServerName, ServerLoad> onlineServers =
143     new ConcurrentHashMap<ServerName, ServerLoad>();
144 
145   /**
146    * Map of admin interfaces per registered regionserver; these interfaces we use to control
147    * regionservers out on the cluster
148    */
149   private final Map<ServerName, AdminService.BlockingInterface> rsAdmins =
150     new HashMap<ServerName, AdminService.BlockingInterface>();
151 
152   /**
153    * List of region servers <ServerName> that should not get any more new
154    * regions.
155    */
156   private final ArrayList<ServerName> drainingServers =
157     new ArrayList<ServerName>();
158 
159   private final Server master;
160   private final MasterServices services;
161   private final ClusterConnection connection;
162 
163   private final DeadServer deadservers = new DeadServer();
164 
165   private final long maxSkew;
166   private final long warningSkew;
167 
168   private final RetryCounterFactory pingRetryCounterFactory;
169   private final RpcControllerFactory rpcControllerFactory;
170 
171   /**
172    * Set of region servers which are dead but not processed immediately. If one
173    * server died before master enables ServerShutdownHandler, the server will be
174    * added to this set and will be processed through calling
175    * {@link ServerManager#processQueuedDeadServers()} by master.
176    * <p>
177    * A dead server is a server instance known to be dead, not listed in the /hbase/rs
178    * znode any more. It may have not been submitted to ServerShutdownHandler yet
179    * because the handler is not enabled.
180    * <p>
181    * A dead server, which has been submitted to ServerShutdownHandler while the
182    * handler is not enabled, is queued up.
183    * <p>
184    * So this is a set of region servers known to be dead but not submitted to
185    * ServerShutdownHander for processing yet.
186    */
187   private Set<ServerName> queuedDeadServers = new HashSet<ServerName>();
188 
189   /**
190    * Set of region servers which are dead and submitted to ServerShutdownHandler to process but not
191    * fully processed immediately.
192    * <p>
193    * If one server died before assignment manager finished the failover cleanup, the server will be
194    * added to this set and will be processed through calling
195    * {@link ServerManager#processQueuedDeadServers()} by assignment manager.
196    * <p>
197    * The Boolean value indicates whether log split is needed inside ServerShutdownHandler
198    * <p>
199    * ServerShutdownHandler processes a dead server submitted to the handler after the handler is
200    * enabled. It may not be able to complete the processing because meta is not yet online or master
201    * is currently in startup mode. In this case, the dead server will be parked in this set
202    * temporarily.
203    */
204   private Map<ServerName, Boolean> requeuedDeadServers
205     = new ConcurrentHashMap<ServerName, Boolean>();
206 
207   /** Listeners that are called on server events. */
208   private List<ServerListener> listeners = new CopyOnWriteArrayList<ServerListener>();
209 
210   /**
211    * Constructor.
212    * @param master
213    * @param services
214    * @throws ZooKeeperConnectionException
215    */
216   public ServerManager(final Server master, final MasterServices services)
217       throws IOException {
218     this(master, services, true);
219   }
220 
221   ServerManager(final Server master, final MasterServices services,
222       final boolean connect) throws IOException {
223     this.master = master;
224     this.services = services;
225     Configuration c = master.getConfiguration();
226     maxSkew = c.getLong("hbase.master.maxclockskew", 30000);
227     warningSkew = c.getLong("hbase.master.warningclockskew", 10000);
228     this.connection = connect ? (ClusterConnection)ConnectionFactory.createConnection(c) : null;
229     int pingMaxAttempts = Math.max(1, master.getConfiguration().getInt(
230       "hbase.master.maximum.ping.server.attempts", 10));
231     int pingSleepInterval = Math.max(1, master.getConfiguration().getInt(
232       "hbase.master.ping.server.retry.sleep.interval", 100));
233     this.pingRetryCounterFactory = new RetryCounterFactory(pingMaxAttempts, pingSleepInterval);
234     this.rpcControllerFactory = this.connection == null
235         ? null
236         : connection.getRpcControllerFactory();
237   }
238 
239   /**
240    * Add the listener to the notification list.
241    * @param listener The ServerListener to register
242    */
243   public void registerListener(final ServerListener listener) {
244     this.listeners.add(listener);
245   }
246 
247   /**
248    * Remove the listener from the notification list.
249    * @param listener The ServerListener to unregister
250    */
251   public boolean unregisterListener(final ServerListener listener) {
252     return this.listeners.remove(listener);
253   }
254 
255   /**
256    * Let the server manager know a new regionserver has come online
257    * @param request the startup request
258    * @param ia the InetAddress from which request is received
259    * @return The ServerName we know this server as.
260    * @throws IOException
261    */
262   ServerName regionServerStartup(RegionServerStartupRequest request, InetAddress ia)
263       throws IOException {
264     // Test for case where we get a region startup message from a regionserver
265     // that has been quickly restarted but whose znode expiration handler has
266     // not yet run, or from a server whose fail we are currently processing.
267     // Test its host+port combo is present in serverAddresstoServerInfo.  If it
268     // is, reject the server and trigger its expiration. The next time it comes
269     // in, it should have been removed from serverAddressToServerInfo and queued
270     // for processing by ProcessServerShutdown.
271 
272     final String hostname = request.hasUseThisHostnameInstead() ?
273         request.getUseThisHostnameInstead() :ia.getHostName();
274     ServerName sn = ServerName.valueOf(hostname, request.getPort(),
275       request.getServerStartCode());
276     checkClockSkew(sn, request.getServerCurrentTime());
277     checkIsDead(sn, "STARTUP");
278     if (!checkAndRecordNewServer(sn, ServerLoad.EMPTY_SERVERLOAD)) {
279       LOG.warn("THIS SHOULD NOT HAPPEN, RegionServerStartup"
280         + " could not record the server: " + sn);
281     }
282     return sn;
283   }
284 
285   private ConcurrentNavigableMap<byte[], Long> getOrCreateStoreFlushedSequenceId(
286     byte[] regionName) {
287     ConcurrentNavigableMap<byte[], Long> storeFlushedSequenceId =
288         storeFlushedSequenceIdsByRegion.get(regionName);
289     if (storeFlushedSequenceId != null) {
290       return storeFlushedSequenceId;
291     }
292     storeFlushedSequenceId = new ConcurrentSkipListMap<byte[], Long>(Bytes.BYTES_COMPARATOR);
293     ConcurrentNavigableMap<byte[], Long> alreadyPut =
294         storeFlushedSequenceIdsByRegion.putIfAbsent(regionName, storeFlushedSequenceId);
295     return alreadyPut == null ? storeFlushedSequenceId : alreadyPut;
296   }
297   /**
298    * Updates last flushed sequence Ids for the regions on server sn
299    * @param sn
300    * @param hsl
301    */
302   private void updateLastFlushedSequenceIds(ServerName sn, ServerLoad hsl) {
303     Map<byte[], RegionLoad> regionsLoad = hsl.getRegionsLoad();
304     for (Entry<byte[], RegionLoad> entry : regionsLoad.entrySet()) {
305       byte[] encodedRegionName = Bytes.toBytes(HRegionInfo.encodeRegionName(entry.getKey()));
306       Long existingValue = flushedSequenceIdByRegion.get(encodedRegionName);
307       long l = entry.getValue().getCompleteSequenceId();
308       // Don't let smaller sequence ids override greater sequence ids.
309       if (LOG.isTraceEnabled()) {
310         LOG.trace(Bytes.toString(encodedRegionName) + ", existingValue=" + existingValue +
311           ", completeSequenceId=" + l);
312       }
313       if (existingValue == null || (l != HConstants.NO_SEQNUM && l > existingValue)) {
314         flushedSequenceIdByRegion.put(encodedRegionName, l);
315       } else if (l != HConstants.NO_SEQNUM && l < existingValue) {
316         LOG.warn("RegionServer " + sn + " indicates a last flushed sequence id ("
317             + l + ") that is less than the previous last flushed sequence id ("
318             + existingValue + ") for region " + Bytes.toString(entry.getKey()) + " Ignoring.");
319       }
320       ConcurrentNavigableMap<byte[], Long> storeFlushedSequenceId =
321           getOrCreateStoreFlushedSequenceId(encodedRegionName);
322       for (StoreSequenceId storeSeqId : entry.getValue().getStoreCompleteSequenceId()) {
323         byte[] family = storeSeqId.getFamilyName().toByteArray();
324         existingValue = storeFlushedSequenceId.get(family);
325         l = storeSeqId.getSequenceId();
326         if (LOG.isTraceEnabled()) {
327           LOG.trace(Bytes.toString(encodedRegionName) + ", family=" + Bytes.toString(family) +
328             ", existingValue=" + existingValue + ", completeSequenceId=" + l);
329         }
330         // Don't let smaller sequence ids override greater sequence ids.
331         if (existingValue == null || (l != HConstants.NO_SEQNUM && l > existingValue.longValue())) {
332           storeFlushedSequenceId.put(family, l);
333         }
334       }
335     }
336   }
337 
338   void regionServerReport(ServerName sn,
339       ServerLoad sl) throws YouAreDeadException {
340     checkIsDead(sn, "REPORT");
341     if (null == this.onlineServers.replace(sn, sl)) {
342       // Already have this host+port combo and its just different start code?
343       // Just let the server in. Presume master joining a running cluster.
344       // recordNewServer is what happens at the end of reportServerStartup.
345       // The only thing we are skipping is passing back to the regionserver
346       // the ServerName to use. Here we presume a master has already done
347       // that so we'll press on with whatever it gave us for ServerName.
348       if (!checkAndRecordNewServer(sn, sl)) {
349         LOG.info("RegionServerReport ignored, could not record the server: " + sn);
350         return; // Not recorded, so no need to move on
351       }
352     }
353     updateLastFlushedSequenceIds(sn, sl);
354   }
355 
356   /**
357    * Check is a server of same host and port already exists,
358    * if not, or the existed one got a smaller start code, record it.
359    *
360    * @param sn the server to check and record
361    * @param sl the server load on the server
362    * @return true if the server is recorded, otherwise, false
363    */
364   boolean checkAndRecordNewServer(
365       final ServerName serverName, final ServerLoad sl) {
366     ServerName existingServer = null;
367     synchronized (this.onlineServers) {
368       existingServer = findServerWithSameHostnamePortWithLock(serverName);
369       if (existingServer != null && (existingServer.getStartcode() > serverName.getStartcode())) {
370         LOG.info("Server serverName=" + serverName + " rejected; we already have "
371             + existingServer.toString() + " registered with same hostname and port");
372         return false;
373       }
374       recordNewServerWithLock(serverName, sl);
375     }
376 
377     // Tell our listeners that a server was added
378     if (!this.listeners.isEmpty()) {
379       for (ServerListener listener : this.listeners) {
380         listener.serverAdded(serverName);
381       }
382     }
383 
384     // Note that we assume that same ts means same server, and don't expire in that case.
385     //  TODO: ts can theoretically collide due to clock shifts, so this is a bit hacky.
386     if (existingServer != null && (existingServer.getStartcode() < serverName.getStartcode())) {
387       LOG.info("Triggering server recovery; existingServer " +
388           existingServer + " looks stale, new server:" + serverName);
389       expireServer(existingServer);
390     }
391     return true;
392   }
393 
394   /**
395    * Checks if the clock skew between the server and the master. If the clock skew exceeds the
396    * configured max, it will throw an exception; if it exceeds the configured warning threshold,
397    * it will log a warning but start normally.
398    * @param serverName Incoming servers's name
399    * @param serverCurrentTime
400    * @throws ClockOutOfSyncException if the skew exceeds the configured max value
401    */
402   private void checkClockSkew(final ServerName serverName, final long serverCurrentTime)
403   throws ClockOutOfSyncException {
404     long skew = Math.abs(System.currentTimeMillis() - serverCurrentTime);
405     if (skew > maxSkew) {
406       String message = "Server " + serverName + " has been " +
407         "rejected; Reported time is too far out of sync with master.  " +
408         "Time difference of " + skew + "ms > max allowed of " + maxSkew + "ms";
409       LOG.warn(message);
410       throw new ClockOutOfSyncException(message);
411     } else if (skew > warningSkew){
412       String message = "Reported time for server " + serverName + " is out of sync with master " +
413         "by " + skew + "ms. (Warning threshold is " + warningSkew + "ms; " +
414         "error threshold is " + maxSkew + "ms)";
415       LOG.warn(message);
416     }
417   }
418 
419   /**
420    * If this server is on the dead list, reject it with a YouAreDeadException.
421    * If it was dead but came back with a new start code, remove the old entry
422    * from the dead list.
423    * @param serverName
424    * @param what START or REPORT
425    * @throws org.apache.hadoop.hbase.YouAreDeadException
426    */
427   private void checkIsDead(final ServerName serverName, final String what)
428       throws YouAreDeadException {
429     if (this.deadservers.isDeadServer(serverName)) {
430       // host name, port and start code all match with existing one of the
431       // dead servers. So, this server must be dead.
432       String message = "Server " + what + " rejected; currently processing " +
433           serverName + " as dead server";
434       LOG.debug(message);
435       throw new YouAreDeadException(message);
436     }
437     // remove dead server with same hostname and port of newly checking in rs after master
438     // initialization.See HBASE-5916 for more information.
439     if ((this.services == null || ((HMaster) this.services).isInitialized())
440         && this.deadservers.cleanPreviousInstance(serverName)) {
441       // This server has now become alive after we marked it as dead.
442       // We removed it's previous entry from the dead list to reflect it.
443       LOG.debug(what + ":" + " Server " + serverName + " came back up," +
444           " removed it from the dead servers list");
445     }
446   }
447 
448   /**
449    * Assumes onlineServers is locked.
450    * @return ServerName with matching hostname and port.
451    */
452   private ServerName findServerWithSameHostnamePortWithLock(
453       final ServerName serverName) {
454     for (ServerName sn: this.onlineServers.keySet()) {
455       if (ServerName.isSameHostnameAndPort(serverName, sn)) return sn;
456     }
457     return null;
458   }
459 
460   /**
461    * Adds the onlineServers list. onlineServers should be locked.
462    * @param serverName The remote servers name.
463    * @param sl
464    * @return Server load from the removed server, if any.
465    */
466   @VisibleForTesting
467   void recordNewServerWithLock(final ServerName serverName, final ServerLoad sl) {
468     LOG.info("Registering server=" + serverName);
469     this.onlineServers.put(serverName, sl);
470     this.rsAdmins.remove(serverName);
471   }
472 
473   public RegionStoreSequenceIds getLastFlushedSequenceId(byte[] encodedRegionName) {
474     RegionStoreSequenceIds.Builder builder = RegionStoreSequenceIds.newBuilder();
475     Long seqId = flushedSequenceIdByRegion.get(encodedRegionName);
476     builder.setLastFlushedSequenceId(seqId != null ? seqId.longValue() : HConstants.NO_SEQNUM);
477     Map<byte[], Long> storeFlushedSequenceId =
478         storeFlushedSequenceIdsByRegion.get(encodedRegionName);
479     if (storeFlushedSequenceId != null) {
480       for (Map.Entry<byte[], Long> entry : storeFlushedSequenceId.entrySet()) {
481         builder.addStoreSequenceId(StoreSequenceId.newBuilder()
482             .setFamilyName(ByteString.copyFrom(entry.getKey()))
483             .setSequenceId(entry.getValue().longValue()).build());
484       }
485     }
486     return builder.build();
487   }
488 
489   /**
490    * @param serverName
491    * @return ServerLoad if serverName is known else null
492    */
493   public ServerLoad getLoad(final ServerName serverName) {
494     return this.onlineServers.get(serverName);
495   }
496 
497   /**
498    * Compute the average load across all region servers.
499    * Currently, this uses a very naive computation - just uses the number of
500    * regions being served, ignoring stats about number of requests.
501    * @return the average load
502    */
503   public double getAverageLoad() {
504     int totalLoad = 0;
505     int numServers = 0;
506     for (ServerLoad sl: this.onlineServers.values()) {
507         numServers++;
508         totalLoad += sl.getNumberOfRegions();
509     }
510     return numServers == 0 ? 0 :
511       (double)totalLoad / (double)numServers;
512   }
513 
514   /** @return the count of active regionservers */
515   public int countOfRegionServers() {
516     // Presumes onlineServers is a concurrent map
517     return this.onlineServers.size();
518   }
519 
520   /**
521    * @return Read-only map of servers to serverinfo
522    */
523   public Map<ServerName, ServerLoad> getOnlineServers() {
524     // Presumption is that iterating the returned Map is OK.
525     synchronized (this.onlineServers) {
526       return Collections.unmodifiableMap(this.onlineServers);
527     }
528   }
529 
530   public DeadServer getDeadServers() {
531     return this.deadservers;
532   }
533 
534   /**
535    * Checks if any dead servers are currently in progress.
536    * @return true if any RS are being processed as dead, false if not
537    */
538   public boolean areDeadServersInProgress() {
539     return this.deadservers.areDeadServersInProgress();
540   }
541 
542   void letRegionServersShutdown() {
543     long previousLogTime = 0;
544     ServerName sn = master.getServerName();
545     ZooKeeperWatcher zkw = master.getZooKeeper();
546     int onlineServersCt;
547     while ((onlineServersCt = onlineServers.size()) > 0){
548 
549       if (System.currentTimeMillis() > (previousLogTime + 1000)) {
550         Set<ServerName> remainingServers = onlineServers.keySet();
551         synchronized (onlineServers) {
552           if (remainingServers.size() == 1 && remainingServers.contains(sn)) {
553             // Master will delete itself later.
554             return;
555           }
556         }
557         StringBuilder sb = new StringBuilder();
558         // It's ok here to not sync on onlineServers - merely logging
559         for (ServerName key : remainingServers) {
560           if (sb.length() > 0) {
561             sb.append(", ");
562           }
563           sb.append(key);
564         }
565         LOG.info("Waiting on regionserver(s) to go down " + sb.toString());
566         previousLogTime = System.currentTimeMillis();
567       }
568 
569       try {
570         List<String> servers = ZKUtil.listChildrenNoWatch(zkw, zkw.rsZNode);
571         if (servers == null || servers.size() == 0 || (servers.size() == 1
572             && servers.contains(sn.toString()))) {
573           LOG.info("ZK shows there is only the master self online, exiting now");
574           // Master could have lost some ZK events, no need to wait more.
575           break;
576         }
577       } catch (KeeperException ke) {
578         LOG.warn("Failed to list regionservers", ke);
579         // ZK is malfunctioning, don't hang here
580         break;
581       }
582       synchronized (onlineServers) {
583         try {
584           if (onlineServersCt == onlineServers.size()) onlineServers.wait(100);
585         } catch (InterruptedException ignored) {
586           // continue
587         }
588       }
589     }
590   }
591 
592   /*
593    * Expire the passed server.  Add it to list of dead servers and queue a
594    * shutdown processing.
595    */
596   public synchronized void expireServer(final ServerName serverName) {
597     if (serverName.equals(master.getServerName())) {
598       if (!(master.isAborted() || master.isStopped())) {
599         master.stop("We lost our znode?");
600       }
601       return;
602     }
603     if (!services.isServerCrashProcessingEnabled()) {
604       LOG.info("Master doesn't enable ServerShutdownHandler during initialization, "
605           + "delay expiring server " + serverName);
606       this.queuedDeadServers.add(serverName);
607       return;
608     }
609     if (this.deadservers.isDeadServer(serverName)) {
610       // TODO: Can this happen?  It shouldn't be online in this case?
611       LOG.warn("Expiration of " + serverName +
612           " but server shutdown already in progress");
613       return;
614     }
615     moveFromOnelineToDeadServers(serverName);
616 
617     // If cluster is going down, yes, servers are going to be expiring; don't
618     // process as a dead server
619     if (this.clusterShutdown) {
620       LOG.info("Cluster shutdown set; " + serverName +
621         " expired; onlineServers=" + this.onlineServers.size());
622       if (this.onlineServers.isEmpty()) {
623         master.stop("Cluster shutdown set; onlineServer=0");
624       }
625       return;
626     }
627 
628     boolean carryingMeta = services.getAssignmentManager().isCarryingMeta(serverName) ==
629         AssignmentManager.ServerHostRegion.HOSTING_REGION;
630     ProcedureExecutor<MasterProcedureEnv> procExec = this.services.getMasterProcedureExecutor();
631     procExec.submitProcedure(new ServerCrashProcedure(
632       procExec.getEnvironment(), serverName, true, carryingMeta));
633     LOG.debug("Added=" + serverName +
634       " to dead servers, submitted shutdown handler to be executed meta=" + carryingMeta);
635 
636     // Tell our listeners that a server was removed
637     if (!this.listeners.isEmpty()) {
638       for (ServerListener listener : this.listeners) {
639         listener.serverRemoved(serverName);
640       }
641     }
642   }
643 
644   @VisibleForTesting
645   public void moveFromOnelineToDeadServers(final ServerName sn) {
646     synchronized (onlineServers) {
647       if (!this.onlineServers.containsKey(sn)) {
648         LOG.warn("Expiration of " + sn + " but server not online");
649       }
650       // Remove the server from the known servers lists and update load info BUT
651       // add to deadservers first; do this so it'll show in dead servers list if
652       // not in online servers list.
653       this.deadservers.add(sn);
654       this.onlineServers.remove(sn);
655       onlineServers.notifyAll();
656     }
657     this.rsAdmins.remove(sn);
658   }
659 
660   public synchronized void processDeadServer(final ServerName serverName, boolean shouldSplitWal) {
661     // When assignment manager is cleaning up the zookeeper nodes and rebuilding the
662     // in-memory region states, region servers could be down. Meta table can and
663     // should be re-assigned, log splitting can be done too. However, it is better to
664     // wait till the cleanup is done before re-assigning user regions.
665     //
666     // We should not wait in the server shutdown handler thread since it can clog
667     // the handler threads and meta table could not be re-assigned in case
668     // the corresponding server is down. So we queue them up here instead.
669     if (!services.getAssignmentManager().isFailoverCleanupDone()) {
670       requeuedDeadServers.put(serverName, shouldSplitWal);
671       return;
672     }
673 
674     this.deadservers.add(serverName);
675     ProcedureExecutor<MasterProcedureEnv> procExec = this.services.getMasterProcedureExecutor();
676     procExec.submitProcedure(new ServerCrashProcedure(
677       procExec.getEnvironment(), serverName, shouldSplitWal, false));
678   }
679 
680   /**
681    * Process the servers which died during master's initialization. It will be
682    * called after HMaster#assignMeta and AssignmentManager#joinCluster.
683    * */
684   synchronized void processQueuedDeadServers() {
685     if (!services.isServerCrashProcessingEnabled()) {
686       LOG.info("Master hasn't enabled ServerShutdownHandler");
687     }
688     Iterator<ServerName> serverIterator = queuedDeadServers.iterator();
689     while (serverIterator.hasNext()) {
690       ServerName tmpServerName = serverIterator.next();
691       expireServer(tmpServerName);
692       serverIterator.remove();
693       requeuedDeadServers.remove(tmpServerName);
694     }
695 
696     if (!services.getAssignmentManager().isFailoverCleanupDone()) {
697       LOG.info("AssignmentManager hasn't finished failover cleanup; waiting");
698     }
699 
700     for(ServerName tmpServerName : requeuedDeadServers.keySet()){
701       processDeadServer(tmpServerName, requeuedDeadServers.get(tmpServerName));
702     }
703     requeuedDeadServers.clear();
704   }
705 
706   /*
707    * Remove the server from the drain list.
708    */
709   public boolean removeServerFromDrainList(final ServerName sn) {
710     // Warn if the server (sn) is not online.  ServerName is of the form:
711     // <hostname> , <port> , <startcode>
712 
713     if (!this.isServerOnline(sn)) {
714       LOG.warn("Server " + sn + " is not currently online. " +
715                "Removing from draining list anyway, as requested.");
716     }
717     // Remove the server from the draining servers lists.
718     return this.drainingServers.remove(sn);
719   }
720 
721   /*
722    * Add the server to the drain list.
723    */
724   public boolean addServerToDrainList(final ServerName sn) {
725     // Warn if the server (sn) is not online.  ServerName is of the form:
726     // <hostname> , <port> , <startcode>
727 
728     if (!this.isServerOnline(sn)) {
729       LOG.warn("Server " + sn + " is not currently online. " +
730                "Ignoring request to add it to draining list.");
731       return false;
732     }
733     // Add the server to the draining servers lists, if it's not already in
734     // it.
735     if (this.drainingServers.contains(sn)) {
736       LOG.warn("Server " + sn + " is already in the draining server list." +
737                "Ignoring request to add it again.");
738       return false;
739     }
740     LOG.info("Server " + sn + " added to draining server list.");
741     return this.drainingServers.add(sn);
742   }
743 
744   // RPC methods to region servers
745 
746   /**
747    * Sends an OPEN RPC to the specified server to open the specified region.
748    * <p>
749    * Open should not fail but can if server just crashed.
750    * <p>
751    * @param server server to open a region
752    * @param region region to open
753    * @param versionOfOfflineNode that needs to be present in the offline node
754    * when RS tries to change the state from OFFLINE to other states.
755    * @param favoredNodes
756    */
757   public RegionOpeningState sendRegionOpen(final ServerName server,
758       HRegionInfo region, int versionOfOfflineNode, List<ServerName> favoredNodes)
759   throws IOException {
760     AdminService.BlockingInterface admin = getRsAdmin(server);
761     if (admin == null) {
762       LOG.warn("Attempting to send OPEN RPC to server " + server.toString() +
763         " failed because no RPC connection found to this server");
764       return RegionOpeningState.FAILED_OPENING;
765     }
766     OpenRegionRequest request = RequestConverter.buildOpenRegionRequest(server, 
767       region, versionOfOfflineNode, favoredNodes, 
768       (RecoveryMode.LOG_REPLAY == this.services.getMasterFileSystem().getLogRecoveryMode()));
769     try {
770       OpenRegionResponse response = admin.openRegion(null, request);
771       return ResponseConverter.getRegionOpeningState(response);
772     } catch (ServiceException se) {
773       throw ProtobufUtil.getRemoteException(se);
774     }
775   }
776 
777   /**
778    * Sends an OPEN RPC to the specified server to open the specified region.
779    * <p>
780    * Open should not fail but can if server just crashed.
781    * <p>
782    * @param server server to open a region
783    * @param regionOpenInfos info of a list of regions to open
784    * @return a list of region opening states
785    */
786   public List<RegionOpeningState> sendRegionOpen(ServerName server,
787       List<Triple<HRegionInfo, Integer, List<ServerName>>> regionOpenInfos)
788   throws IOException {
789     AdminService.BlockingInterface admin = getRsAdmin(server);
790     if (admin == null) {
791       LOG.warn("Attempting to send OPEN RPC to server " + server.toString() +
792         " failed because no RPC connection found to this server");
793       return null;
794     }
795 
796     OpenRegionRequest request = RequestConverter.buildOpenRegionRequest(server, regionOpenInfos,
797       (RecoveryMode.LOG_REPLAY == this.services.getMasterFileSystem().getLogRecoveryMode()));
798     try {
799       OpenRegionResponse response = admin.openRegion(null, request);
800       return ResponseConverter.getRegionOpeningStateList(response);
801     } catch (ServiceException se) {
802       throw ProtobufUtil.getRemoteException(se);
803     }
804   }
805 
806   private PayloadCarryingRpcController newRpcController() {
807     return rpcControllerFactory == null ? null : rpcControllerFactory.newController();
808   }
809 
810   /**
811    * Sends an CLOSE RPC to the specified server to close the specified region.
812    * <p>
813    * A region server could reject the close request because it either does not
814    * have the specified region or the region is being split.
815    * @param server server to open a region
816    * @param region region to open
817    * @param versionOfClosingNode
818    *   the version of znode to compare when RS transitions the znode from
819    *   CLOSING state.
820    * @param dest - if the region is moved to another server, the destination server. null otherwise.
821    * @return true if server acknowledged close, false if not
822    * @throws IOException
823    */
824   public boolean sendRegionClose(ServerName server, HRegionInfo region,
825     int versionOfClosingNode, ServerName dest, boolean transitionInZK) throws IOException {
826     if (server == null) throw new NullPointerException("Passed server is null");
827     AdminService.BlockingInterface admin = getRsAdmin(server);
828     if (admin == null) {
829       throw new IOException("Attempting to send CLOSE RPC to server " +
830         server.toString() + " for region " +
831         region.getRegionNameAsString() +
832         " failed because no RPC connection found to this server");
833     }
834     PayloadCarryingRpcController controller = newRpcController();
835     return ProtobufUtil.closeRegion(controller, admin, server, region.getRegionName(),
836       versionOfClosingNode, dest, transitionInZK);
837   }
838 
839   public boolean sendRegionClose(ServerName server,
840       HRegionInfo region, int versionOfClosingNode) throws IOException {
841     return sendRegionClose(server, region, versionOfClosingNode, null, true);
842   }
843 
844   /**
845    * Sends a WARMUP RPC to the specified server to warmup the specified region.
846    * <p>
847    * A region server could reject the close request because it either does not
848    * have the specified region or the region is being split.
849    * @param server server to warmup a region
850    * @param region region to  warmup
851    */
852   public void sendRegionWarmup(ServerName server,
853       HRegionInfo region) {
854     if (server == null) return;
855     try {
856       AdminService.BlockingInterface admin = getRsAdmin(server);
857       PayloadCarryingRpcController controller = newRpcController();
858       ProtobufUtil.warmupRegion(controller, admin, region);
859     } catch (IOException e) {
860       LOG.error("Received exception in RPC for warmup server:" +
861         server + "region: " + region +
862         "exception: " + e);
863     }
864   }
865 
866   /**
867    * Contacts a region server and waits up to timeout ms
868    * to close the region.  This bypasses the active hmaster.
869    */
870   public static void closeRegionSilentlyAndWait(ClusterConnection connection,
871     ServerName server, HRegionInfo region, long timeout) throws IOException, InterruptedException {
872     AdminService.BlockingInterface rs = connection.getAdmin(server);
873     PayloadCarryingRpcController controller = connection.getRpcControllerFactory().newController();
874     try {
875       ProtobufUtil.closeRegion(controller, rs, server, region.getRegionName(), false);
876     } catch (IOException e) {
877       LOG.warn("Exception when closing region: " + region.getRegionNameAsString(), e);
878     }
879     long expiration = timeout + System.currentTimeMillis();
880     while (System.currentTimeMillis() < expiration) {
881       try {
882         HRegionInfo rsRegion =
883           ProtobufUtil.getRegionInfo(controller, rs, region.getRegionName());
884         if (rsRegion == null) return;
885       } catch (IOException ioe) {
886         if (ioe instanceof NotServingRegionException) // no need to retry again
887           return;
888         LOG.warn("Exception when retrieving regioninfo from: "
889           + region.getRegionNameAsString(), ioe);
890       }
891       Thread.sleep(1000);
892     }
893     throw new IOException("Region " + region + " failed to close within"
894         + " timeout " + timeout);
895   }
896 
897   /**
898    * Sends an MERGE REGIONS RPC to the specified server to merge the specified
899    * regions.
900    * <p>
901    * A region server could reject the close request because it either does not
902    * have the specified region.
903    * @param server server to merge regions
904    * @param region_a region to merge
905    * @param region_b region to merge
906    * @param forcible true if do a compulsory merge, otherwise we will only merge
907    *          two adjacent regions
908    * @throws IOException
909    */
910   public void sendRegionsMerge(ServerName server, HRegionInfo region_a,
911       HRegionInfo region_b, boolean forcible, User user) throws IOException {
912     if (server == null)
913       throw new NullPointerException("Passed server is null");
914     if (region_a == null || region_b == null)
915       throw new NullPointerException("Passed region is null");
916     AdminService.BlockingInterface admin = getRsAdmin(server);
917     if (admin == null) {
918       throw new IOException("Attempting to send MERGE REGIONS RPC to server "
919           + server.toString() + " for region "
920           + region_a.getRegionNameAsString() + ","
921           + region_b.getRegionNameAsString()
922           + " failed because no RPC connection found to this server");
923     }
924     PayloadCarryingRpcController controller = newRpcController();
925     ProtobufUtil.mergeRegions(controller, admin, region_a, region_b, forcible, user);
926   }
927 
928   /**
929    * Check if a region server is reachable and has the expected start code
930    */
931   public boolean isServerReachable(ServerName server) {
932     if (server == null) throw new NullPointerException("Passed server is null");
933 
934 
935     RetryCounter retryCounter = pingRetryCounterFactory.create();
936     while (retryCounter.shouldRetry()) {
937       synchronized (this.onlineServers) {
938         if (this.deadservers.isDeadServer(server)) {
939           return false;
940         }
941       }
942       try {
943         PayloadCarryingRpcController controller = newRpcController();
944         AdminService.BlockingInterface admin = getRsAdmin(server);
945         if (admin != null) {
946           ServerInfo info = ProtobufUtil.getServerInfo(controller, admin);
947           return info != null && info.hasServerName()
948             && server.getStartcode() == info.getServerName().getStartCode();
949         }
950       } catch (IOException ioe) {
951         if (LOG.isDebugEnabled()) {
952           LOG.debug("Couldn't reach " + server + ", try=" + retryCounter.getAttemptTimes() + " of "
953               + retryCounter.getMaxAttempts(), ioe);
954         }
955         try {
956           retryCounter.sleepUntilNextRetry();
957         } catch(InterruptedException ie) {
958           Thread.currentThread().interrupt();
959           break;
960         }
961       }
962     }
963     return false;
964   }
965 
966     /**
967     * @param sn
968     * @return Admin interface for the remote regionserver named <code>sn</code>
969     * @throws IOException
970     * @throws RetriesExhaustedException wrapping a ConnectException if failed
971     */
972   private AdminService.BlockingInterface getRsAdmin(final ServerName sn)
973   throws IOException {
974     AdminService.BlockingInterface admin = this.rsAdmins.get(sn);
975     if (admin == null) {
976       LOG.debug("New admin connection to " + sn.toString());
977       if (sn.equals(master.getServerName()) && master instanceof HRegionServer) {
978         // A master is also a region server now, see HBASE-10569 for details
979         admin = ((HRegionServer)master).getRSRpcServices();
980       } else {
981         admin = this.connection.getAdmin(sn);
982       }
983       this.rsAdmins.put(sn, admin);
984     }
985     return admin;
986   }
987 
988   /**
989    * Wait for the region servers to report in.
990    * We will wait until one of this condition is met:
991    *  - the master is stopped
992    *  - the 'hbase.master.wait.on.regionservers.maxtostart' number of
993    *    region servers is reached
994    *  - the 'hbase.master.wait.on.regionservers.mintostart' is reached AND
995    *   there have been no new region server in for
996    *      'hbase.master.wait.on.regionservers.interval' time AND
997    *   the 'hbase.master.wait.on.regionservers.timeout' is reached
998    *
999    * @throws InterruptedException
1000    */
1001   public void waitForRegionServers(MonitoredTask status)
1002   throws InterruptedException {
1003     final long interval = this.master.getConfiguration().
1004       getLong(WAIT_ON_REGIONSERVERS_INTERVAL, 1500);
1005     final long timeout = this.master.getConfiguration().
1006       getLong(WAIT_ON_REGIONSERVERS_TIMEOUT, 4500);
1007     int defaultMinToStart = 1;
1008     if (BaseLoadBalancer.tablesOnMaster(master.getConfiguration())) {
1009       // If we assign regions to master, we'd like to start
1010       // at least another region server so that we don't
1011       // assign all regions to master if other region servers
1012       // don't come up in time.
1013       defaultMinToStart = 2;
1014     }
1015     int minToStart = this.master.getConfiguration().
1016       getInt(WAIT_ON_REGIONSERVERS_MINTOSTART, defaultMinToStart);
1017     if (minToStart < 1) {
1018       LOG.warn(String.format(
1019         "The value of '%s' (%d) can not be less than 1, ignoring.",
1020         WAIT_ON_REGIONSERVERS_MINTOSTART, minToStart));
1021       minToStart = 1;
1022     }
1023     int maxToStart = this.master.getConfiguration().
1024       getInt(WAIT_ON_REGIONSERVERS_MAXTOSTART, Integer.MAX_VALUE);
1025     if (maxToStart < minToStart) {
1026         LOG.warn(String.format(
1027             "The value of '%s' (%d) is set less than '%s' (%d), ignoring.",
1028             WAIT_ON_REGIONSERVERS_MAXTOSTART, maxToStart,
1029             WAIT_ON_REGIONSERVERS_MINTOSTART, minToStart));
1030         maxToStart = Integer.MAX_VALUE;
1031     }
1032 
1033     long now =  System.currentTimeMillis();
1034     final long startTime = now;
1035     long slept = 0;
1036     long lastLogTime = 0;
1037     long lastCountChange = startTime;
1038     int count = countOfRegionServers();
1039     int oldCount = 0;
1040     while (!this.master.isStopped() && count < maxToStart
1041         && (lastCountChange+interval > now || timeout > slept || count < minToStart)) {
1042       // Log some info at every interval time or if there is a change
1043       if (oldCount != count || lastLogTime+interval < now){
1044         lastLogTime = now;
1045         String msg =
1046           "Waiting for region servers count to settle; currently"+
1047             " checked in " + count + ", slept for " + slept + " ms," +
1048             " expecting minimum of " + minToStart + ", maximum of "+ maxToStart+
1049             ", timeout of "+timeout+" ms, interval of "+interval+" ms.";
1050         LOG.info(msg);
1051         status.setStatus(msg);
1052       }
1053 
1054       // We sleep for some time
1055       final long sleepTime = 50;
1056       Thread.sleep(sleepTime);
1057       now =  System.currentTimeMillis();
1058       slept = now - startTime;
1059 
1060       oldCount = count;
1061       count = countOfRegionServers();
1062       if (count != oldCount) {
1063         lastCountChange = now;
1064       }
1065     }
1066 
1067     LOG.info("Finished waiting for region servers count to settle;" +
1068       " checked in " + count + ", slept for " + slept + " ms," +
1069       " expecting minimum of " + minToStart + ", maximum of "+ maxToStart+","+
1070       " master is "+ (this.master.isStopped() ? "stopped.": "running")
1071     );
1072   }
1073 
1074   /**
1075    * @return A copy of the internal list of online servers.
1076    */
1077   public List<ServerName> getOnlineServersList() {
1078     // TODO: optimize the load balancer call so we don't need to make a new list
1079     // TODO: FIX. THIS IS POPULAR CALL.
1080     return new ArrayList<ServerName>(this.onlineServers.keySet());
1081   }
1082 
1083   /**
1084    * @return A copy of the internal list of draining servers.
1085    */
1086   public List<ServerName> getDrainingServersList() {
1087     return new ArrayList<ServerName>(this.drainingServers);
1088   }
1089 
1090   /**
1091    * @return A copy of the internal set of deadNotExpired servers.
1092    */
1093   Set<ServerName> getDeadNotExpiredServers() {
1094     return new HashSet<ServerName>(this.queuedDeadServers);
1095   }
1096 
1097   /**
1098    * During startup, if we figure it is not a failover, i.e. there is
1099    * no more WAL files to split, we won't try to recover these dead servers.
1100    * So we just remove them from the queue. Use caution in calling this.
1101    */
1102   void removeRequeuedDeadServers() {
1103     requeuedDeadServers.clear();
1104   }
1105 
1106   /**
1107    * @return A copy of the internal map of requeuedDeadServers servers and their corresponding
1108    *         splitlog need flag.
1109    */
1110   Map<ServerName, Boolean> getRequeuedDeadServers() {
1111     return Collections.unmodifiableMap(this.requeuedDeadServers);
1112   }
1113 
1114   public boolean isServerOnline(ServerName serverName) {
1115     return serverName != null && onlineServers.containsKey(serverName);
1116   }
1117 
1118   /**
1119    * Check if a server is known to be dead.  A server can be online,
1120    * or known to be dead, or unknown to this manager (i.e, not online,
1121    * not known to be dead either. it is simply not tracked by the
1122    * master any more, for example, a very old previous instance).
1123    */
1124   public synchronized boolean isServerDead(ServerName serverName) {
1125     return serverName == null || deadservers.isDeadServer(serverName)
1126       || queuedDeadServers.contains(serverName)
1127       || requeuedDeadServers.containsKey(serverName);
1128   }
1129 
1130   public void shutdownCluster() {
1131     this.clusterShutdown = true;
1132     this.master.stop("Cluster shutdown requested");
1133   }
1134 
1135   public boolean isClusterShutdown() {
1136     return this.clusterShutdown;
1137   }
1138 
1139   /**
1140    * Stop the ServerManager.  Currently closes the connection to the master.
1141    */
1142   public void stop() {
1143     if (connection != null) {
1144       try {
1145         connection.close();
1146       } catch (IOException e) {
1147         LOG.error("Attempt to close connection to master failed", e);
1148       }
1149     }
1150   }
1151 
1152   /**
1153    * Creates a list of possible destinations for a region. It contains the online servers, but not
1154    *  the draining or dying servers.
1155    *  @param serverToExclude can be null if there is no server to exclude
1156    */
1157   public List<ServerName> createDestinationServersList(final ServerName serverToExclude){
1158     final List<ServerName> destServers = getOnlineServersList();
1159 
1160     if (serverToExclude != null){
1161       destServers.remove(serverToExclude);
1162     }
1163 
1164     // Loop through the draining server list and remove them from the server list
1165     final List<ServerName> drainingServersCopy = getDrainingServersList();
1166     if (!drainingServersCopy.isEmpty()) {
1167       for (final ServerName server: drainingServersCopy) {
1168         destServers.remove(server);
1169       }
1170     }
1171 
1172     // Remove the deadNotExpired servers from the server list.
1173     removeDeadNotExpiredServers(destServers);
1174     return destServers;
1175   }
1176 
1177   /**
1178    * Calls {@link #createDestinationServersList} without server to exclude.
1179    */
1180   public List<ServerName> createDestinationServersList(){
1181     return createDestinationServersList(null);
1182   }
1183 
1184     /**
1185     * Loop through the deadNotExpired server list and remove them from the
1186     * servers.
1187     * This function should be used carefully outside of this class. You should use a high level
1188     *  method such as {@link #createDestinationServersList()} instead of managing you own list.
1189     */
1190   void removeDeadNotExpiredServers(List<ServerName> servers) {
1191     Set<ServerName> deadNotExpiredServersCopy = this.getDeadNotExpiredServers();
1192     if (!deadNotExpiredServersCopy.isEmpty()) {
1193       for (ServerName server : deadNotExpiredServersCopy) {
1194         LOG.debug("Removing dead but not expired server: " + server
1195           + " from eligible server pool.");
1196         servers.remove(server);
1197       }
1198     }
1199   }
1200 
1201   /**
1202    * To clear any dead server with same host name and port of any online server
1203    */
1204   void clearDeadServersWithSameHostNameAndPortOfOnlineServer() {
1205     for (ServerName serverName : getOnlineServersList()) {
1206       deadservers.cleanAllPreviousInstances(serverName);
1207     }
1208   }
1209 
1210   /**
1211    * Called by delete table and similar to notify the ServerManager that a region was removed.
1212    */
1213   public void removeRegion(final HRegionInfo regionInfo) {
1214     final byte[] encodedName = regionInfo.getEncodedNameAsBytes();
1215     storeFlushedSequenceIdsByRegion.remove(encodedName);
1216     flushedSequenceIdByRegion.remove(encodedName);
1217   }
1218 
1219   /**
1220    * Called by delete table and similar to notify the ServerManager that a region was removed.
1221    */
1222   public void removeRegions(final List<HRegionInfo> regions) {
1223     for (HRegionInfo hri: regions) {
1224       removeRegion(hri);
1225     }
1226   }
1227 }