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