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.Pair;
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    * ServerShutdownHandler 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 serverName 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 favoredNodes
721    */
722   public RegionOpeningState sendRegionOpen(final ServerName server,
723       HRegionInfo region, List<ServerName> favoredNodes)
724   throws IOException {
725     AdminService.BlockingInterface admin = getRsAdmin(server);
726     if (admin == null) {
727       LOG.warn("Attempting to send OPEN RPC to server " + server.toString() +
728         " failed because no RPC connection found to this server");
729       return RegionOpeningState.FAILED_OPENING;
730     }
731     OpenRegionRequest request = RequestConverter.buildOpenRegionRequest(server,
732       region, favoredNodes,
733       (RecoveryMode.LOG_REPLAY == this.services.getMasterFileSystem().getLogRecoveryMode()));
734     try {
735       OpenRegionResponse response = admin.openRegion(null, request);
736       return ResponseConverter.getRegionOpeningState(response);
737     } catch (ServiceException se) {
738       throw ProtobufUtil.getRemoteException(se);
739     }
740   }
741 
742   /**
743    * Sends an OPEN RPC to the specified server to open the specified region.
744    * <p>
745    * Open should not fail but can if server just crashed.
746    * <p>
747    * @param server server to open a region
748    * @param regionOpenInfos info of a list of regions to open
749    * @return a list of region opening states
750    */
751   public List<RegionOpeningState> sendRegionOpen(ServerName server,
752       List<Pair<HRegionInfo, List<ServerName>>> regionOpenInfos)
753   throws IOException {
754     AdminService.BlockingInterface admin = getRsAdmin(server);
755     if (admin == null) {
756       LOG.warn("Attempting to send OPEN RPC to server " + server.toString() +
757         " failed because no RPC connection found to this server");
758       return null;
759     }
760 
761     OpenRegionRequest request = RequestConverter.buildOpenRegionRequest(regionOpenInfos,
762       (RecoveryMode.LOG_REPLAY == this.services.getMasterFileSystem().getLogRecoveryMode()));
763     try {
764       OpenRegionResponse response = admin.openRegion(null, request);
765       return ResponseConverter.getRegionOpeningStateList(response);
766     } catch (ServiceException se) {
767       throw ProtobufUtil.getRemoteException(se);
768     }
769   }
770 
771   /**
772    * Sends an CLOSE RPC to the specified server to close the specified region.
773    * <p>
774    * A region server could reject the close request because it either does not
775    * have the specified region or the region is being split.
776    * @param server server to open a region
777    * @param region region to open
778    * @param dest - if the region is moved to another server, the destination server. null otherwise.
779    * @throws IOException
780    */
781   public boolean sendRegionClose(ServerName server, HRegionInfo region,
782       ServerName dest) throws IOException {
783     if (server == null) throw new NullPointerException("Passed server is null");
784     AdminService.BlockingInterface admin = getRsAdmin(server);
785     if (admin == null) {
786       throw new IOException("Attempting to send CLOSE RPC to server " +
787         server.toString() + " for region " +
788         region.getRegionNameAsString() +
789         " failed because no RPC connection found to this server");
790     }
791     return ProtobufUtil.closeRegion(admin, server, region.getRegionName(),
792       dest);
793   }
794 
795   public boolean sendRegionClose(ServerName server,
796       HRegionInfo region) throws IOException {
797     return sendRegionClose(server, region, null);
798   }
799 
800   /**
801    * Sends an MERGE REGIONS RPC to the specified server to merge the specified
802    * regions.
803    * <p>
804    * A region server could reject the close request because it either does not
805    * have the specified region.
806    * @param server server to merge regions
807    * @param region_a region to merge
808    * @param region_b region to merge
809    * @param forcible true if do a compulsory merge, otherwise we will only merge
810    *          two adjacent regions
811    * @throws IOException
812    */
813   public void sendRegionsMerge(ServerName server, HRegionInfo region_a,
814       HRegionInfo region_b, boolean forcible) throws IOException {
815     if (server == null)
816       throw new NullPointerException("Passed server is null");
817     if (region_a == null || region_b == null)
818       throw new NullPointerException("Passed region is null");
819     AdminService.BlockingInterface admin = getRsAdmin(server);
820     if (admin == null) {
821       throw new IOException("Attempting to send MERGE REGIONS RPC to server "
822           + server.toString() + " for region "
823           + region_a.getRegionNameAsString() + ","
824           + region_b.getRegionNameAsString()
825           + " failed because no RPC connection found to this server");
826     }
827     ProtobufUtil.mergeRegions(admin, region_a, region_b, forcible);
828   }
829 
830   /**
831    * Check if a region server is reachable and has the expected start code
832    */
833   public boolean isServerReachable(ServerName server) {
834     if (server == null) throw new NullPointerException("Passed server is null");
835     int maximumAttempts = Math.max(1, master.getConfiguration().getInt(
836       "hbase.master.maximum.ping.server.attempts", 10));
837     for (int i = 0; i < maximumAttempts; i++) {
838       try {
839         AdminService.BlockingInterface admin = getRsAdmin(server);
840         if (admin != null) {
841           ServerInfo info = ProtobufUtil.getServerInfo(admin);
842           return info != null && info.hasServerName()
843             && server.getStartcode() == info.getServerName().getStartCode();
844         }
845       } catch (IOException ioe) {
846         LOG.debug("Couldn't reach " + server + ", try=" + i
847           + " of " + maximumAttempts, ioe);
848       }
849     }
850     return false;
851   }
852 
853     /**
854     * @param sn
855     * @return Admin interface for the remote regionserver named <code>sn</code>
856     * @throws IOException
857     * @throws RetriesExhaustedException wrapping a ConnectException if failed
858     */
859   @SuppressWarnings("deprecation")
860   private AdminService.BlockingInterface getRsAdmin(final ServerName sn)
861   throws IOException {
862     AdminService.BlockingInterface admin = this.rsAdmins.get(sn);
863     if (admin == null) {
864       LOG.debug("New admin connection to " + sn.toString());
865       if (sn.equals(master.getServerName()) && master instanceof HRegionServer) {
866         // A master is also a region server now, see HBASE-10569 for details
867         admin = ((HRegionServer)master).getRSRpcServices();
868       } else {
869         admin = this.connection.getAdmin(sn);
870       }
871       this.rsAdmins.put(sn, admin);
872     }
873     return admin;
874   }
875 
876   /**
877    * Wait for the region servers to report in.
878    * We will wait until one of this condition is met:
879    *  - the master is stopped
880    *  - the 'hbase.master.wait.on.regionservers.maxtostart' number of
881    *    region servers is reached
882    *  - the 'hbase.master.wait.on.regionservers.mintostart' is reached AND
883    *   there have been no new region server in for
884    *      'hbase.master.wait.on.regionservers.interval' time AND
885    *   the 'hbase.master.wait.on.regionservers.timeout' is reached
886    *
887    * @throws InterruptedException
888    */
889   public void waitForRegionServers(MonitoredTask status)
890   throws InterruptedException {
891     final long interval = this.master.getConfiguration().
892       getLong(WAIT_ON_REGIONSERVERS_INTERVAL, 1500);
893     final long timeout = this.master.getConfiguration().
894       getLong(WAIT_ON_REGIONSERVERS_TIMEOUT, 4500);
895     int minToStart = this.master.getConfiguration().
896       getInt(WAIT_ON_REGIONSERVERS_MINTOSTART, 2);
897     if (minToStart < 1) {
898       LOG.warn(String.format(
899         "The value of '%s' (%d) can not be less than 1, ignoring.",
900         WAIT_ON_REGIONSERVERS_MINTOSTART, minToStart));
901       minToStart = 1;
902     }
903     int maxToStart = this.master.getConfiguration().
904       getInt(WAIT_ON_REGIONSERVERS_MAXTOSTART, Integer.MAX_VALUE);
905     if (maxToStart < minToStart) {
906         LOG.warn(String.format(
907             "The value of '%s' (%d) is set less than '%s' (%d), ignoring.",
908             WAIT_ON_REGIONSERVERS_MAXTOSTART, maxToStart,
909             WAIT_ON_REGIONSERVERS_MINTOSTART, minToStart));
910         maxToStart = Integer.MAX_VALUE;
911     }
912 
913     long now =  System.currentTimeMillis();
914     final long startTime = now;
915     long slept = 0;
916     long lastLogTime = 0;
917     long lastCountChange = startTime;
918     int count = countOfRegionServers();
919     int oldCount = 0;
920     ServerName masterSn = master.getServerName();
921     boolean selfCheckedIn = isServerOnline(masterSn);
922     while (!this.master.isStopped() && (!selfCheckedIn || (count < maxToStart
923         && (lastCountChange+interval > now || timeout > slept || count < minToStart)))) {
924       // Log some info at every interval time or if there is a change
925       if (oldCount != count || lastLogTime+interval < now){
926         lastLogTime = now;
927         String msg =
928           "Waiting for region servers count to settle; currently"+
929             " checked in " + count + ", slept for " + slept + " ms," +
930             " expecting minimum of " + minToStart + ", maximum of "+ maxToStart+
931             ", timeout of "+timeout+" ms, interval of "+interval+" ms," +
932             " selfCheckedIn " + selfCheckedIn;
933         LOG.info(msg);
934         status.setStatus(msg);
935       }
936 
937       // We sleep for some time
938       final long sleepTime = 50;
939       Thread.sleep(sleepTime);
940       now =  System.currentTimeMillis();
941       slept = now - startTime;
942 
943       selfCheckedIn = isServerOnline(masterSn);
944 
945       oldCount = count;
946       count = countOfRegionServers();
947       if (count != oldCount) {
948         lastCountChange = now;
949       }
950     }
951 
952     LOG.info("Finished waiting for region servers count to settle;" +
953       " checked in " + count + ", slept for " + slept + " ms," +
954       " expecting minimum of " + minToStart + ", maximum of "+ maxToStart+","+
955       " master is "+ (this.master.isStopped() ? "stopped.": "running," +
956       " selfCheckedIn " + selfCheckedIn)
957     );
958   }
959 
960   /**
961    * @return A copy of the internal list of online servers.
962    */
963   public List<ServerName> getOnlineServersList() {
964     // TODO: optimize the load balancer call so we don't need to make a new list
965     // TODO: FIX. THIS IS POPULAR CALL.
966     return new ArrayList<ServerName>(this.onlineServers.keySet());
967   }
968 
969   /**
970    * @return A copy of the internal list of draining servers.
971    */
972   public List<ServerName> getDrainingServersList() {
973     return new ArrayList<ServerName>(this.drainingServers);
974   }
975 
976   /**
977    * @return A copy of the internal set of deadNotExpired servers.
978    */
979   Set<ServerName> getDeadNotExpiredServers() {
980     return new HashSet<ServerName>(this.queuedDeadServers);
981   }
982 
983   /**
984    * During startup, if we figure it is not a failover, i.e. there is
985    * no more HLog files to split, we won't try to recover these dead servers.
986    * So we just remove them from the queue. Use caution in calling this.
987    */
988   void removeRequeuedDeadServers() {
989     requeuedDeadServers.clear();
990   }
991 
992   /**
993    * @return A copy of the internal map of requeuedDeadServers servers and their corresponding
994    *         splitlog need flag.
995    */
996   Map<ServerName, Boolean> getRequeuedDeadServers() {
997     return Collections.unmodifiableMap(this.requeuedDeadServers);
998   }
999 
1000   public boolean isServerOnline(ServerName serverName) {
1001     return serverName != null && onlineServers.containsKey(serverName);
1002   }
1003 
1004   /**
1005    * Check if a server is known to be dead.  A server can be online,
1006    * or known to be dead, or unknown to this manager (i.e, not online,
1007    * not known to be dead either. it is simply not tracked by the
1008    * master any more, for example, a very old previous instance).
1009    */
1010   public synchronized boolean isServerDead(ServerName serverName) {
1011     return serverName == null || deadservers.isDeadServer(serverName)
1012       || queuedDeadServers.contains(serverName)
1013       || requeuedDeadServers.containsKey(serverName);
1014   }
1015 
1016   public void shutdownCluster() {
1017     this.clusterShutdown = true;
1018     this.master.stop("Cluster shutdown requested");
1019   }
1020 
1021   public boolean isClusterShutdown() {
1022     return this.clusterShutdown;
1023   }
1024 
1025   /**
1026    * Stop the ServerManager.  Currently closes the connection to the master.
1027    */
1028   public void stop() {
1029     if (connection != null) {
1030       try {
1031         connection.close();
1032       } catch (IOException e) {
1033         LOG.error("Attempt to close connection to master failed", e);
1034       }
1035     }
1036   }
1037 
1038   /**
1039    * Creates a list of possible destinations for a region. It contains the online servers, but not
1040    *  the draining or dying servers.
1041    *  @param serverToExclude can be null if there is no server to exclude
1042    */
1043   public List<ServerName> createDestinationServersList(final ServerName serverToExclude){
1044     final List<ServerName> destServers = getOnlineServersList();
1045 
1046     if (serverToExclude != null){
1047       destServers.remove(serverToExclude);
1048     }
1049 
1050     // Loop through the draining server list and remove them from the server list
1051     final List<ServerName> drainingServersCopy = getDrainingServersList();
1052     if (!drainingServersCopy.isEmpty()) {
1053       for (final ServerName server: drainingServersCopy) {
1054         destServers.remove(server);
1055       }
1056     }
1057 
1058     // Remove the deadNotExpired servers from the server list.
1059     removeDeadNotExpiredServers(destServers);
1060     return destServers;
1061   }
1062 
1063   /**
1064    * Calls {@link #createDestinationServersList} without server to exclude.
1065    */
1066   public List<ServerName> createDestinationServersList(){
1067     return createDestinationServersList(null);
1068   }
1069 
1070     /**
1071     * Loop through the deadNotExpired server list and remove them from the
1072     * servers.
1073     * This function should be used carefully outside of this class. You should use a high level
1074     *  method such as {@link #createDestinationServersList()} instead of managing you own list.
1075     */
1076   void removeDeadNotExpiredServers(List<ServerName> servers) {
1077     Set<ServerName> deadNotExpiredServersCopy = this.getDeadNotExpiredServers();
1078     if (!deadNotExpiredServersCopy.isEmpty()) {
1079       for (ServerName server : deadNotExpiredServersCopy) {
1080         LOG.debug("Removing dead but not expired server: " + server
1081           + " from eligible server pool.");
1082         servers.remove(server);
1083       }
1084     }
1085   }
1086 
1087   /**
1088    * To clear any dead server with same host name and port of any online server
1089    */
1090   void clearDeadServersWithSameHostNameAndPortOfOnlineServer() {
1091     for (ServerName serverName : getOnlineServersList()) {
1092       deadservers.cleanAllPreviousInstances(serverName);
1093     }
1094   }
1095 }