View Javadoc

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