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