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