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