View Javadoc

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