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.regionserver;
20  
21  import com.google.common.annotations.VisibleForTesting;
22  import com.google.common.base.Preconditions;
23  import com.google.common.collect.Maps;
24  import com.google.protobuf.BlockingRpcChannel;
25  import com.google.protobuf.Descriptors;
26  import com.google.protobuf.Message;
27  import com.google.protobuf.RpcCallback;
28  import com.google.protobuf.RpcController;
29  import com.google.protobuf.Service;
30  import com.google.protobuf.ServiceException;
31  
32  import java.io.IOException;
33  import java.io.InterruptedIOException;
34  import java.lang.Thread.UncaughtExceptionHandler;
35  import java.lang.management.MemoryUsage;
36  import java.lang.reflect.Constructor;
37  import java.net.BindException;
38  import java.net.InetAddress;
39  import java.net.InetSocketAddress;
40  import java.security.PrivilegedExceptionAction;
41  import java.util.ArrayList;
42  import java.util.Collection;
43  import java.util.Collections;
44  import java.util.Comparator;
45  import java.util.HashMap;
46  import java.util.HashSet;
47  import java.util.Iterator;
48  import java.util.List;
49  import java.util.Map;
50  import java.util.Map.Entry;
51  import java.util.Set;
52  import java.util.SortedMap;
53  import java.util.TreeMap;
54  import java.util.TreeSet;
55  import java.util.concurrent.ConcurrentHashMap;
56  import java.util.concurrent.ConcurrentMap;
57  import java.util.concurrent.ConcurrentSkipListMap;
58  import java.util.concurrent.CountDownLatch;
59  import java.util.concurrent.TimeUnit;
60  import java.util.concurrent.atomic.AtomicBoolean;
61  import java.util.concurrent.atomic.AtomicReference;
62  import java.util.concurrent.locks.ReentrantReadWriteLock;
63  
64  import javax.management.MalformedObjectNameException;
65  import javax.management.ObjectName;
66  import javax.servlet.http.HttpServlet;
67  
68  import org.apache.commons.lang.SystemUtils;
69  import org.apache.commons.lang.math.RandomUtils;
70  import org.apache.commons.logging.Log;
71  import org.apache.commons.logging.LogFactory;
72  import org.apache.hadoop.conf.Configuration;
73  import org.apache.hadoop.fs.FileSystem;
74  import org.apache.hadoop.fs.Path;
75  import org.apache.hadoop.hbase.ChoreService;
76  import org.apache.hadoop.hbase.ClockOutOfSyncException;
77  import org.apache.hadoop.hbase.CoordinatedStateManager;
78  import org.apache.hadoop.hbase.CoordinatedStateManagerFactory;
79  import org.apache.hadoop.hbase.HBaseConfiguration;
80  import org.apache.hadoop.hbase.HBaseInterfaceAudience;
81  import org.apache.hadoop.hbase.HConstants;
82  import org.apache.hadoop.hbase.HRegionInfo;
83  import org.apache.hadoop.hbase.HealthCheckChore;
84  import org.apache.hadoop.hbase.MetaTableAccessor;
85  import org.apache.hadoop.hbase.NotServingRegionException;
86  import org.apache.hadoop.hbase.RemoteExceptionHandler;
87  import org.apache.hadoop.hbase.ScheduledChore;
88  import org.apache.hadoop.hbase.ServerName;
89  import org.apache.hadoop.hbase.Stoppable;
90  import org.apache.hadoop.hbase.TableDescriptors;
91  import org.apache.hadoop.hbase.TableName;
92  import org.apache.hadoop.hbase.YouAreDeadException;
93  import org.apache.hadoop.hbase.ZNodeClearer;
94  import org.apache.hadoop.hbase.classification.InterfaceAudience;
95  import org.apache.hadoop.hbase.client.ClusterConnection;
96  import org.apache.hadoop.hbase.client.ConnectionUtils;
97  import org.apache.hadoop.hbase.client.RpcRetryingCallerFactory;
98  import org.apache.hadoop.hbase.conf.ConfigurationManager;
99  import org.apache.hadoop.hbase.conf.ConfigurationObserver;
100 import org.apache.hadoop.hbase.coordination.BaseCoordinatedStateManager;
101 import org.apache.hadoop.hbase.coordination.CloseRegionCoordination;
102 import org.apache.hadoop.hbase.coordination.SplitLogWorkerCoordination;
103 import org.apache.hadoop.hbase.coprocessor.CoprocessorHost;
104 import org.apache.hadoop.hbase.exceptions.RegionMovedException;
105 import org.apache.hadoop.hbase.exceptions.RegionOpeningException;
106 import org.apache.hadoop.hbase.exceptions.UnknownProtocolException;
107 import org.apache.hadoop.hbase.executor.ExecutorService;
108 import org.apache.hadoop.hbase.executor.ExecutorType;
109 import org.apache.hadoop.hbase.fs.HFileSystem;
110 import org.apache.hadoop.hbase.http.InfoServer;
111 import org.apache.hadoop.hbase.io.hfile.CacheConfig;
112 import org.apache.hadoop.hbase.io.util.HeapMemorySizeUtil;
113 import org.apache.hadoop.hbase.ipc.CoprocessorRpcUtils;
114 import org.apache.hadoop.hbase.ipc.RpcClient;
115 import org.apache.hadoop.hbase.ipc.RpcClientFactory;
116 import org.apache.hadoop.hbase.ipc.RpcControllerFactory;
117 import org.apache.hadoop.hbase.ipc.RpcServerInterface;
118 import org.apache.hadoop.hbase.ipc.ServerNotRunningYetException;
119 import org.apache.hadoop.hbase.ipc.ServerRpcController;
120 import org.apache.hadoop.hbase.master.HMaster;
121 import org.apache.hadoop.hbase.master.RegionState.State;
122 import org.apache.hadoop.hbase.master.TableLockManager;
123 import org.apache.hadoop.hbase.master.balancer.BaseLoadBalancer;
124 import org.apache.hadoop.hbase.procedure.RegionServerProcedureManagerHost;
125 import org.apache.hadoop.hbase.protobuf.ProtobufUtil;
126 import org.apache.hadoop.hbase.protobuf.RequestConverter;
127 import org.apache.hadoop.hbase.protobuf.ResponseConverter;
128 import org.apache.hadoop.hbase.protobuf.generated.ClientProtos;
129 import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.CoprocessorServiceCall;
130 import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.CoprocessorServiceRequest;
131 import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.CoprocessorServiceResponse;
132 import org.apache.hadoop.hbase.protobuf.generated.ClusterStatusProtos;
133 import org.apache.hadoop.hbase.protobuf.generated.ClusterStatusProtos.RegionLoad;
134 import org.apache.hadoop.hbase.protobuf.generated.ClusterStatusProtos.RegionStoreSequenceIds;
135 import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.Coprocessor;
136 import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.Coprocessor.Builder;
137 import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.NameStringPair;
138 import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.RegionServerInfo;
139 import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.RegionSpecifier;
140 import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.RegionSpecifier.RegionSpecifierType;
141 import org.apache.hadoop.hbase.protobuf.generated.RegionServerStatusProtos.GetLastFlushedSequenceIdRequest;
142 import org.apache.hadoop.hbase.protobuf.generated.RegionServerStatusProtos.GetLastFlushedSequenceIdResponse;
143 import org.apache.hadoop.hbase.protobuf.generated.RegionServerStatusProtos.RegionServerReportRequest;
144 import org.apache.hadoop.hbase.protobuf.generated.RegionServerStatusProtos.RegionServerStartupRequest;
145 import org.apache.hadoop.hbase.protobuf.generated.RegionServerStatusProtos.RegionServerStartupResponse;
146 import org.apache.hadoop.hbase.protobuf.generated.RegionServerStatusProtos.RegionServerStatusService;
147 import org.apache.hadoop.hbase.protobuf.generated.RegionServerStatusProtos.RegionStateTransition;
148 import org.apache.hadoop.hbase.protobuf.generated.RegionServerStatusProtos.RegionStateTransition.TransitionCode;
149 import org.apache.hadoop.hbase.protobuf.generated.RegionServerStatusProtos.ReportRSFatalErrorRequest;
150 import org.apache.hadoop.hbase.protobuf.generated.RegionServerStatusProtos.ReportRegionStateTransitionRequest;
151 import org.apache.hadoop.hbase.protobuf.generated.RegionServerStatusProtos.ReportRegionStateTransitionResponse;
152 import org.apache.hadoop.hbase.quotas.RegionServerQuotaManager;
153 import org.apache.hadoop.hbase.regionserver.compactions.CompactionConfiguration;
154 import org.apache.hadoop.hbase.regionserver.compactions.CompactionProgress;
155 import org.apache.hadoop.hbase.regionserver.handler.CloseMetaHandler;
156 import org.apache.hadoop.hbase.regionserver.handler.CloseRegionHandler;
157 import org.apache.hadoop.hbase.regionserver.handler.RegionReplicaFlushHandler;
158 import org.apache.hadoop.hbase.regionserver.throttle.FlushThroughputControllerFactory;
159 import org.apache.hadoop.hbase.regionserver.throttle.ThroughputController;
160 import org.apache.hadoop.hbase.regionserver.wal.MetricsWAL;
161 import org.apache.hadoop.hbase.regionserver.wal.WALActionsListener;
162 import org.apache.hadoop.hbase.replication.regionserver.Replication;
163 import org.apache.hadoop.hbase.replication.regionserver.ReplicationLoad;
164 import org.apache.hadoop.hbase.security.Superusers;
165 import org.apache.hadoop.hbase.security.User;
166 import org.apache.hadoop.hbase.security.UserProvider;
167 import org.apache.hadoop.hbase.trace.SpanReceiverHost;
168 import org.apache.hadoop.hbase.util.Addressing;
169 import org.apache.hadoop.hbase.util.ByteStringer;
170 import org.apache.hadoop.hbase.util.Bytes;
171 import org.apache.hadoop.hbase.util.CompressionTest;
172 import org.apache.hadoop.hbase.util.ConfigUtil;
173 import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
174 import org.apache.hadoop.hbase.util.FSTableDescriptors;
175 import org.apache.hadoop.hbase.util.FSUtils;
176 import org.apache.hadoop.hbase.util.HasThread;
177 import org.apache.hadoop.hbase.util.JSONBean;
178 import org.apache.hadoop.hbase.util.JvmPauseMonitor;
179 import org.apache.hadoop.hbase.util.MBeanUtil;
180 import org.apache.hadoop.hbase.util.ServerRegionReplicaUtil;
181 import org.apache.hadoop.hbase.util.Sleeper;
182 import org.apache.hadoop.hbase.util.Threads;
183 import org.apache.hadoop.hbase.util.VersionInfo;
184 import org.apache.hadoop.hbase.wal.DefaultWALProvider;
185 import org.apache.hadoop.hbase.wal.WAL;
186 import org.apache.hadoop.hbase.wal.WALFactory;
187 import org.apache.hadoop.hbase.zookeeper.ClusterStatusTracker;
188 import org.apache.hadoop.hbase.zookeeper.MasterAddressTracker;
189 import org.apache.hadoop.hbase.zookeeper.MetaTableLocator;
190 import org.apache.hadoop.hbase.zookeeper.RecoveringRegionWatcher;
191 import org.apache.hadoop.hbase.zookeeper.ZKClusterId;
192 import org.apache.hadoop.hbase.zookeeper.ZKSplitLog;
193 import org.apache.hadoop.hbase.zookeeper.ZKUtil;
194 import org.apache.hadoop.hbase.zookeeper.ZooKeeperNodeTracker;
195 import org.apache.hadoop.hbase.zookeeper.ZooKeeperWatcher;
196 import org.apache.hadoop.ipc.RemoteException;
197 import org.apache.hadoop.util.ReflectionUtils;
198 import org.apache.hadoop.util.StringUtils;
199 import org.apache.zookeeper.KeeperException;
200 import org.apache.zookeeper.KeeperException.NoNodeException;
201 import org.apache.zookeeper.data.Stat;
202 import sun.misc.Signal;
203 import sun.misc.SignalHandler;
204 
205 /**
206  * HRegionServer makes a set of HRegions available to clients. It checks in with
207  * the HMaster. There are many HRegionServers in a single HBase deployment.
208  */
209 @InterfaceAudience.LimitedPrivate(HBaseInterfaceAudience.TOOLS)
210 @SuppressWarnings("deprecation")
211 @edu.umd.cs.findbugs.annotations.SuppressWarnings(value="JLM_JSR166_UTILCONCURRENT_MONITORENTER",
212   justification="Use of an atomic type both as monitor and condition variable is intended")
213 public class HRegionServer extends HasThread implements
214     RegionServerServices, LastSequenceId, ConfigurationObserver {
215 
216   private static final Log LOG = LogFactory.getLog(HRegionServer.class);
217 
218   /*
219    * Strings to be used in forming the exception message for
220    * RegionsAlreadyInTransitionException.
221    */
222   protected static final String OPEN = "OPEN";
223   protected static final String CLOSE = "CLOSE";
224 
225   //RegionName vs current action in progress
226   //true - if open region action in progress
227   //false - if close region action in progress
228   protected final ConcurrentMap<byte[], Boolean> regionsInTransitionInRS =
229     new ConcurrentSkipListMap<byte[], Boolean>(Bytes.BYTES_COMPARATOR);
230 
231   // Cache flushing
232   protected MemStoreFlusher cacheFlusher;
233 
234   protected HeapMemoryManager hMemManager;
235   protected CountDownLatch initLatch = null;
236 
237   /**
238    * Cluster connection to be shared by services.
239    * Initialized at server startup and closed when server shuts down.
240    * Clients must never close it explicitly.
241    */
242   protected ClusterConnection clusterConnection;
243 
244   /*
245    * Long-living meta table locator, which is created when the server is started and stopped
246    * when server shuts down. References to this locator shall be used to perform according
247    * operations in EventHandlers. Primary reason for this decision is to make it mockable
248    * for tests.
249    */
250   protected MetaTableLocator metaTableLocator;
251 
252   // Watch if a region is out of recovering state from ZooKeeper
253   @SuppressWarnings("unused")
254   private RecoveringRegionWatcher recoveringRegionWatcher;
255 
256   /**
257    * Go here to get table descriptors.
258    */
259   protected TableDescriptors tableDescriptors;
260 
261   // Replication services. If no replication, this handler will be null.
262   protected ReplicationSourceService replicationSourceHandler;
263   protected ReplicationSinkService replicationSinkHandler;
264 
265   // Compactions
266   public CompactSplitThread compactSplitThread;
267 
268   /**
269    * Map of regions currently being served by this region server. Key is the
270    * encoded region name.  All access should be synchronized.
271    */
272   protected final Map<String, Region> onlineRegions = new ConcurrentHashMap<String, Region>();
273 
274   /**
275    * Map of encoded region names to the DataNode locations they should be hosted on
276    * We store the value as InetSocketAddress since this is used only in HDFS
277    * API (create() that takes favored nodes as hints for placing file blocks).
278    * We could have used ServerName here as the value class, but we'd need to
279    * convert it to InetSocketAddress at some point before the HDFS API call, and
280    * it seems a bit weird to store ServerName since ServerName refers to RegionServers
281    * and here we really mean DataNode locations.
282    */
283   protected final Map<String, InetSocketAddress[]> regionFavoredNodesMap =
284       new ConcurrentHashMap<String, InetSocketAddress[]>();
285 
286   /**
287    * Set of regions currently being in recovering state which means it can accept writes(edits from
288    * previous failed region server) but not reads. A recovering region is also an online region.
289    */
290   protected final Map<String, Region> recoveringRegions = Collections
291       .synchronizedMap(new HashMap<String, Region>());
292 
293   // Leases
294   protected Leases leases;
295 
296   // Instance of the hbase executor service.
297   protected ExecutorService service;
298 
299   // If false, the file system has become unavailable
300   protected volatile boolean fsOk;
301   protected HFileSystem fs;
302   protected HFileSystem walFs;
303 
304   // Set when a report to the master comes back with a message asking us to
305   // shutdown. Also set by call to stop when debugging or running unit tests
306   // of HRegionServer in isolation.
307   private volatile boolean stopped = false;
308 
309   // Go down hard. Used if file system becomes unavailable and also in
310   // debugging and unit tests.
311   private volatile boolean abortRequested;
312 
313   ConcurrentMap<String, Integer> rowlocks = new ConcurrentHashMap<String, Integer>();
314 
315   // A state before we go into stopped state.  At this stage we're closing user
316   // space regions.
317   private boolean stopping = false;
318 
319   volatile boolean killed = false;
320 
321   protected final Configuration conf;
322 
323   private Path rootDir;
324   private Path walRootDir;
325 
326   protected final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
327 
328   final int numRetries;
329   protected final int threadWakeFrequency;
330   protected final int msgInterval;
331 
332   protected final int numRegionsToReport;
333 
334   // Stub to do region server status calls against the master.
335   private volatile RegionServerStatusService.BlockingInterface rssStub;
336   // RPC client. Used to make the stub above that does region server status checking.
337   RpcClient rpcClient;
338 
339   private RpcRetryingCallerFactory rpcRetryingCallerFactory;
340   private RpcControllerFactory rpcControllerFactory;
341 
342   private UncaughtExceptionHandler uncaughtExceptionHandler;
343 
344   // Info server. Default access so can be used by unit tests. REGIONSERVER
345   // is name of the webapp and the attribute name used stuffing this instance
346   // into web context.
347   protected InfoServer infoServer;
348   private JvmPauseMonitor pauseMonitor;
349 
350   /** region server process name */
351   public static final String REGIONSERVER = "regionserver";
352 
353   MetricsRegionServer metricsRegionServer;
354   MetricsTable metricsTable;
355   private SpanReceiverHost spanReceiverHost;
356 
357   /**
358    * ChoreService used to schedule tasks that we want to run periodically
359    */
360   private final ChoreService choreService;
361 
362   /*
363    * Check for compactions requests.
364    */
365   ScheduledChore compactionChecker;
366 
367   /*
368    * Check for flushes
369    */
370   ScheduledChore periodicFlusher;
371 
372   protected volatile WALFactory walFactory;
373 
374   // WAL roller. log is protected rather than private to avoid
375   // eclipse warning when accessed by inner classes
376   final LogRoller walRoller;
377   // Lazily initialized if this RegionServer hosts a meta table.
378   final AtomicReference<LogRoller> metawalRoller = new AtomicReference<LogRoller>();
379 
380   // flag set after we're done setting up server threads
381   final AtomicBoolean online = new AtomicBoolean(false);
382 
383   // zookeeper connection and watcher
384   protected ZooKeeperWatcher zooKeeper;
385 
386   // master address tracker
387   private MasterAddressTracker masterAddressTracker;
388 
389   // Cluster Status Tracker
390   protected ClusterStatusTracker clusterStatusTracker;
391 
392   // Log Splitting Worker
393   private SplitLogWorker splitLogWorker;
394 
395   // A sleeper that sleeps for msgInterval.
396   protected final Sleeper sleeper;
397 
398   private final int operationTimeout;
399   private final int shortOperationTimeout;
400 
401   private final RegionServerAccounting regionServerAccounting;
402 
403   // Cache configuration and block cache reference
404   protected CacheConfig cacheConfig;
405 
406   /** The health check chore. */
407   private HealthCheckChore healthCheckChore;
408 
409   /** The nonce manager chore. */
410   private ScheduledChore nonceManagerChore;
411 
412   private Map<String, Service> coprocessorServiceHandlers = Maps.newHashMap();
413 
414   /**
415    * The server name the Master sees us as.  Its made from the hostname the
416    * master passes us, port, and server startcode. Gets set after registration
417    * against  Master.
418    */
419   protected ServerName serverName;
420 
421   /*
422    * hostname specified by hostname config
423    */
424   protected String useThisHostnameInstead;
425 
426   // key to the config parameter of server hostname
427   // the specification of server hostname is optional. The hostname should be resolvable from
428   // both master and region server
429   @InterfaceAudience.LimitedPrivate(HBaseInterfaceAudience.CONFIG)
430   final static String RS_HOSTNAME_KEY = "hbase.regionserver.hostname";
431   @InterfaceAudience.LimitedPrivate(HBaseInterfaceAudience.CONFIG)
432   protected final static String MASTER_HOSTNAME_KEY = "hbase.master.hostname";
433 
434   // HBASE-18226: This config and hbase.regionserver.hostname are mutually exclusive.
435   // Exception will be thrown if both are used.
436   final static String RS_HOSTNAME_DISABLE_MASTER_REVERSEDNS_KEY =
437     "hbase.regionserver.hostname.disable.master.reversedns";
438 
439   /**
440    * This servers startcode.
441    */
442   protected final long startcode;
443 
444   /**
445    * Unique identifier for the cluster we are a part of.
446    */
447   private String clusterId;
448 
449   /**
450    * MX Bean for RegionServerInfo
451    */
452   private ObjectName mxBean = null;
453 
454   /**
455    * Chore to clean periodically the moved region list
456    */
457   private MovedRegionsCleaner movedRegionsCleaner;
458 
459   // chore for refreshing store files for secondary regions
460   private StorefileRefresherChore storefileRefresher;
461 
462   private RegionServerCoprocessorHost rsHost;
463 
464   private RegionServerProcedureManagerHost rspmHost;
465 
466   private RegionServerQuotaManager rsQuotaManager;
467 
468   // Table level lock manager for locking for region operations
469   protected TableLockManager tableLockManager;
470 
471   /**
472    * Nonce manager. Nonces are used to make operations like increment and append idempotent
473    * in the case where client doesn't receive the response from a successful operation and
474    * retries. We track the successful ops for some time via a nonce sent by client and handle
475    * duplicate operations (currently, by failing them; in future we might use MVCC to return
476    * result). Nonces are also recovered from WAL during, recovery; however, the caveats (from
477    * HBASE-3787) are:
478    * - WAL recovery is optimized, and under high load we won't read nearly nonce-timeout worth
479    *   of past records. If we don't read the records, we don't read and recover the nonces.
480    *   Some WALs within nonce-timeout at recovery may not even be present due to rolling/cleanup.
481    * - There's no WAL recovery during normal region move, so nonces will not be transfered.
482    * We can have separate additional "Nonce WAL". It will just contain bunch of numbers and
483    * won't be flushed on main path - because WAL itself also contains nonces, if we only flush
484    * it before memstore flush, for a given nonce we will either see it in the WAL (if it was
485    * never flushed to disk, it will be part of recovery), or we'll see it as part of the nonce
486    * log (or both occasionally, which doesn't matter). Nonce log file can be deleted after the
487    * latest nonce in it expired. It can also be recovered during move.
488    */
489   final ServerNonceManager nonceManager;
490 
491   private UserProvider userProvider;
492 
493   protected final RSRpcServices rpcServices;
494 
495   protected BaseCoordinatedStateManager csm;
496 
497   private final boolean useZKForAssignment;
498 
499   /**
500    * Configuration manager is used to register/deregister and notify the configuration observers
501    * when the regionserver is notified that there was a change in the on disk configs.
502    */
503   protected final ConfigurationManager configurationManager;
504 
505   private CompactedHFilesDischarger compactedFileDischarger;
506 
507   private volatile ThroughputController flushThroughputController;
508 
509   /**
510    * Starts a HRegionServer at the default location.
511    */
512   public HRegionServer(Configuration conf) throws IOException, InterruptedException {
513     this(conf, CoordinatedStateManagerFactory.getCoordinatedStateManager(conf));
514   }
515 
516   /**
517    * Starts a HRegionServer at the default location
518    * @param csm implementation of CoordinatedStateManager to be used
519    */
520   public HRegionServer(Configuration conf, CoordinatedStateManager csm)
521       throws IOException, InterruptedException {
522     super("RegionServer");  // thread name
523     this.startcode = System.currentTimeMillis();
524     this.fsOk = true;
525     this.conf = conf;
526     checkCodecs(this.conf);
527     this.userProvider = UserProvider.instantiate(conf);
528     FSUtils.setupShortCircuitRead(this.conf);
529 
530     Replication.decorateRegionServerConfiguration(this.conf);
531 
532     // Disable usage of meta replicas in the regionserver
533     this.conf.setBoolean(HConstants.USE_META_REPLICAS, false);
534 
535     // Config'ed params
536     this.numRetries = this.conf.getInt(HConstants.HBASE_CLIENT_RETRIES_NUMBER,
537         HConstants.DEFAULT_HBASE_CLIENT_RETRIES_NUMBER);
538     this.threadWakeFrequency = conf.getInt(HConstants.THREAD_WAKE_FREQUENCY, 10 * 1000);
539     this.msgInterval = conf.getInt("hbase.regionserver.msginterval", 3 * 1000);
540 
541     this.sleeper = new Sleeper(this.msgInterval, this);
542 
543     boolean isNoncesEnabled = conf.getBoolean(HConstants.HBASE_RS_NONCES_ENABLED, true);
544     this.nonceManager = isNoncesEnabled ? new ServerNonceManager(this.conf) : null;
545 
546     this.numRegionsToReport = conf.getInt(
547       "hbase.regionserver.numregionstoreport", 10);
548 
549     this.operationTimeout = conf.getInt(
550       HConstants.HBASE_CLIENT_OPERATION_TIMEOUT,
551       HConstants.DEFAULT_HBASE_CLIENT_OPERATION_TIMEOUT);
552 
553     this.shortOperationTimeout = conf.getInt(
554       HConstants.HBASE_RPC_SHORTOPERATION_TIMEOUT_KEY,
555       HConstants.DEFAULT_HBASE_RPC_SHORTOPERATION_TIMEOUT);
556 
557     this.abortRequested = false;
558     this.stopped = false;
559 
560     rpcServices = createRpcServices();
561     if (this instanceof HMaster) {
562       useThisHostnameInstead = conf.get(MASTER_HOSTNAME_KEY);
563     } else {
564       useThisHostnameInstead = conf.get(RS_HOSTNAME_KEY);
565       if (conf.getBoolean(RS_HOSTNAME_DISABLE_MASTER_REVERSEDNS_KEY, false)) {
566         if (shouldUseThisHostnameInstead()) {
567           String msg = RS_HOSTNAME_DISABLE_MASTER_REVERSEDNS_KEY + " and " + RS_HOSTNAME_KEY +
568             " are mutually exclusive. Do not set " + RS_HOSTNAME_DISABLE_MASTER_REVERSEDNS_KEY +
569             " to true while " + RS_HOSTNAME_KEY + " is used";
570           throw new IOException(msg);
571         } else {
572           useThisHostnameInstead = rpcServices.isa.getHostName();
573         }
574       }
575     }
576     String hostName = shouldUseThisHostnameInstead() ? useThisHostnameInstead :
577       rpcServices.isa.getHostName();
578     serverName = ServerName.valueOf(hostName, rpcServices.isa.getPort(), startcode);
579 
580     rpcControllerFactory = RpcControllerFactory.instantiate(this.conf);
581     rpcRetryingCallerFactory = RpcRetryingCallerFactory.instantiate(this.conf);
582 
583     // login the zookeeper client principal (if using security)
584     ZKUtil.loginClient(this.conf, HConstants.ZK_CLIENT_KEYTAB_FILE,
585       HConstants.ZK_CLIENT_KERBEROS_PRINCIPAL, hostName);
586     // login the server principal (if using secure Hadoop)
587     login(userProvider, hostName);
588     // init superusers and add the server principal (if using security)
589     // or process owner as default super user.
590     Superusers.initialize(conf);
591 
592     regionServerAccounting = new RegionServerAccounting();
593     uncaughtExceptionHandler = new UncaughtExceptionHandler() {
594       @Override
595       public void uncaughtException(Thread t, Throwable e) {
596         abort("Uncaught exception in service thread " + t.getName(), e);
597       }
598     };
599 
600     useZKForAssignment = ConfigUtil.useZKForAssignment(conf);
601 
602     initializeFileSystem();
603 
604     service = new ExecutorService(getServerName().toShortString());
605     spanReceiverHost = SpanReceiverHost.getInstance(getConfiguration());
606 
607     // Some unit tests don't need a cluster, so no zookeeper at all
608     if (!conf.getBoolean("hbase.testing.nocluster", false)) {
609       // Open connection to zookeeper and set primary watcher
610       zooKeeper = new ZooKeeperWatcher(conf, getProcessName() + ":" +
611         rpcServices.isa.getPort(), this, canCreateBaseZNode());
612 
613       this.csm = (BaseCoordinatedStateManager) csm;
614       this.csm.initialize(this);
615       this.csm.start();
616 
617       tableLockManager = TableLockManager.createTableLockManager(
618         conf, zooKeeper, serverName);
619 
620       masterAddressTracker = new MasterAddressTracker(getZooKeeper(), this);
621       masterAddressTracker.start();
622 
623       clusterStatusTracker = new ClusterStatusTracker(zooKeeper, this);
624       clusterStatusTracker.start();
625     }
626     this.configurationManager = new ConfigurationManager();
627 
628     rpcServices.start();
629     putUpWebUI();
630     this.walRoller = new LogRoller(this, this);
631     this.choreService = new ChoreService(getServerName().toString(), true);
632     this.flushThroughputController = FlushThroughputControllerFactory.create(this, conf);
633 
634     if (!SystemUtils.IS_OS_WINDOWS) {
635       Signal.handle(new Signal("HUP"), new SignalHandler() {
636         @Override
637         public void handle(Signal signal) {
638           getConfiguration().reloadConfiguration();
639           configurationManager.notifyAllObservers(getConfiguration());
640         }
641       });
642     }
643     // Create the CompactedFileDischarger chore service. This chore helps to
644     // remove the compacted files
645     // that will no longer be used in reads.
646     // Default is 2 mins. The default value for TTLCleaner is 5 mins so we set this to
647     // 2 mins so that compacted files can be archived before the TTLCleaner runs
648     int cleanerInterval = conf
649         .getInt(CompactionConfiguration.HBASE_HFILE_COMPACTION_DISCHARGER_INTERVAL, 2 * 60 * 1000);
650     this.compactedFileDischarger =
651         new CompactedHFilesDischarger(cleanerInterval, (Stoppable)this, (RegionServerServices)this);
652     choreService.scheduleChore(compactedFileDischarger);
653   }
654 
655   private void initializeFileSystem() throws IOException {
656     // Get fs instance used by this RS.  Do we use checksum verification in the hbase? If hbase
657     // checksum verification enabled, then automatically switch off hdfs checksum verification.
658     boolean useHBaseChecksum = conf.getBoolean(HConstants.HBASE_CHECKSUM_VERIFICATION, true);
659     FSUtils.setFsDefault(this.conf, FSUtils.getWALRootDir(this.conf));
660     this.walFs = new HFileSystem(this.conf, useHBaseChecksum);
661     this.walRootDir = FSUtils.getWALRootDir(this.conf);
662     // Set 'fs.defaultFS' to match the filesystem on hbase.rootdir else
663     // underlying hadoop hdfs accessors will be going against wrong filesystem
664     // (unless all is set to defaults).
665     FSUtils.setFsDefault(this.conf, FSUtils.getRootDir(this.conf));
666     this.fs = new HFileSystem(this.conf, useHBaseChecksum);
667     this.rootDir = FSUtils.getRootDir(this.conf);
668     this.tableDescriptors = new FSTableDescriptors(
669       this.conf, this.fs, this.rootDir, !canUpdateTableDescriptor(), false);
670   }
671 
672   protected void setInitLatch(CountDownLatch latch) {
673     this.initLatch = latch;
674   }
675 
676   /*
677    * Returns true if configured hostname should be used
678    */
679   protected boolean shouldUseThisHostnameInstead() {
680     return useThisHostnameInstead != null && !useThisHostnameInstead.isEmpty();
681   }
682 
683   protected void login(UserProvider user, String host) throws IOException {
684     user.login("hbase.regionserver.keytab.file",
685       "hbase.regionserver.kerberos.principal", host);
686   }
687 
688   protected void waitForMasterActive(){
689   }
690 
691   protected String getProcessName() {
692     return REGIONSERVER;
693   }
694 
695   protected boolean canCreateBaseZNode() {
696     return false;
697   }
698 
699   protected boolean canUpdateTableDescriptor() {
700     return false;
701   }
702 
703   protected RSRpcServices createRpcServices() throws IOException {
704     return new RSRpcServices(this);
705   }
706 
707   protected void configureInfoServer() {
708     infoServer.addServlet("rs-status", "/rs-status", RSStatusServlet.class);
709     infoServer.setAttribute(REGIONSERVER, this);
710   }
711 
712   protected Class<? extends HttpServlet> getDumpServlet() {
713     return RSDumpServlet.class;
714   }
715 
716   @Override
717   public boolean registerService(Service instance) {
718     /*
719      * No stacking of instances is allowed for a single service name
720      */
721     Descriptors.ServiceDescriptor serviceDesc = instance.getDescriptorForType();
722     String serviceName = CoprocessorRpcUtils.getServiceName(serviceDesc);
723     if (coprocessorServiceHandlers.containsKey(serviceName)) {
724       LOG.error("Coprocessor service " + serviceName
725           + " already registered, rejecting request from " + instance);
726       return false;
727     }
728 
729     coprocessorServiceHandlers.put(serviceName, instance);
730     if (LOG.isDebugEnabled()) {
731       LOG.debug("Registered regionserver coprocessor service: service=" + serviceName);
732     }
733     return true;
734   }
735 
736   /**
737    * Create a 'smarter' HConnection, one that is capable of by-passing RPC if the request is to
738    * the local server. Safe to use going to local or remote server.
739    * Create this instance in a method can be intercepted and mocked in tests.
740    * @throws IOException
741    */
742   @VisibleForTesting
743   protected ClusterConnection createClusterConnection() throws IOException {
744     // Create a cluster connection that when appropriate, can short-circuit and go directly to the
745     // local server if the request is to the local server bypassing RPC. Can be used for both local
746     // and remote invocations.
747     return ConnectionUtils.createShortCircuitConnection(conf, null, userProvider.getCurrent(),
748       serverName, rpcServices, rpcServices);
749   }
750 
751   /**
752    * Run test on configured codecs to make sure supporting libs are in place.
753    * @param c
754    * @throws IOException
755    */
756   private static void checkCodecs(final Configuration c) throws IOException {
757     // check to see if the codec list is available:
758     String [] codecs = c.getStrings("hbase.regionserver.codecs", (String[])null);
759     if (codecs == null) return;
760     for (String codec : codecs) {
761       if (!CompressionTest.testCompression(codec)) {
762         throw new IOException("Compression codec " + codec +
763           " not supported, aborting RS construction");
764       }
765     }
766   }
767 
768   public String getClusterId() {
769     return this.clusterId;
770   }
771 
772   /**
773    * Setup our cluster connection if not already initialized.
774    * @throws IOException
775    */
776   protected synchronized void setupClusterConnection() throws IOException {
777     if (clusterConnection == null) {
778       clusterConnection = createClusterConnection();
779       metaTableLocator = new MetaTableLocator();
780     }
781   }
782 
783   /**
784    * All initialization needed before we go register with Master.
785    *
786    * @throws IOException
787    * @throws InterruptedException
788    */
789   private void preRegistrationInitialization(){
790     try {
791       setupClusterConnection();
792 
793       // Health checker thread.
794       if (isHealthCheckerConfigured()) {
795         int sleepTime = this.conf.getInt(HConstants.HEALTH_CHORE_WAKE_FREQ,
796           HConstants.DEFAULT_THREAD_WAKE_FREQUENCY);
797         healthCheckChore = new HealthCheckChore(sleepTime, this, getConfiguration());
798       }
799 
800       initializeZooKeeper();
801       if (!isStopped() && !isAborted()) {
802         initializeThreads();
803       }
804     } catch (Throwable t) {
805       // Call stop if error or process will stick around for ever since server
806       // puts up non-daemon threads.
807       this.rpcServices.stop();
808       abort("Initialization of RS failed.  Hence aborting RS.", t);
809     }
810   }
811 
812   /**
813    * Bring up connection to zk ensemble and then wait until a master for this
814    * cluster and then after that, wait until cluster 'up' flag has been set.
815    * This is the order in which master does things.
816    * Finally open long-living server short-circuit connection.
817    * @throws IOException
818    * @throws InterruptedException
819    */
820   @edu.umd.cs.findbugs.annotations.SuppressWarnings(
821     value={"RV_RETURN_VALUE_IGNORED_BAD_PRACTICE", "RV_RETURN_VALUE_IGNORED"},
822     justification="cluster Id znode read would give us correct response")
823   private void initializeZooKeeper() throws IOException, InterruptedException {
824     // Create the master address tracker, register with zk, and start it.  Then
825     // block until a master is available.  No point in starting up if no master
826     // running.
827     blockAndCheckIfStopped(this.masterAddressTracker);
828 
829     // Wait on cluster being up.  Master will set this flag up in zookeeper
830     // when ready.
831     blockAndCheckIfStopped(this.clusterStatusTracker);
832 
833     if (this.initLatch != null) {
834       this.initLatch.await(20, TimeUnit.SECONDS);
835     }
836     // Retrieve clusterId
837     // Since cluster status is now up
838     // ID should have already been set by HMaster
839     try {
840       clusterId = ZKClusterId.readClusterIdZNode(this.zooKeeper);
841       if (clusterId == null) {
842         this.abort("Cluster ID has not been set");
843       }
844       LOG.info("ClusterId : "+clusterId);
845     } catch (KeeperException e) {
846       this.abort("Failed to retrieve Cluster ID",e);
847     }
848 
849     // In case colocated master, wait here till it's active.
850     // So backup masters won't start as regionservers.
851     // This is to avoid showing backup masters as regionservers
852     // in master web UI, or assigning any region to them.
853     waitForMasterActive();
854     if (isStopped() || isAborted()) {
855       return; // No need for further initialization
856     }
857 
858     // watch for snapshots and other procedures
859     try {
860       rspmHost = new RegionServerProcedureManagerHost();
861       rspmHost.loadProcedures(conf);
862       rspmHost.initialize(this);
863     } catch (KeeperException e) {
864       this.abort("Failed to reach zk cluster when creating procedure handler.", e);
865     }
866     // register watcher for recovering regions
867     this.recoveringRegionWatcher = new RecoveringRegionWatcher(this.zooKeeper, this);
868   }
869 
870   /**
871    * Utilty method to wait indefinitely on a znode availability while checking
872    * if the region server is shut down
873    * @param tracker znode tracker to use
874    * @throws IOException any IO exception, plus if the RS is stopped
875    * @throws InterruptedException
876    */
877   private void blockAndCheckIfStopped(ZooKeeperNodeTracker tracker)
878       throws IOException, InterruptedException {
879     while (tracker.blockUntilAvailable(this.msgInterval, false) == null) {
880       if (this.stopped) {
881         throw new IOException("Received the shutdown message while waiting.");
882       }
883     }
884   }
885 
886   /**
887    * @return False if cluster shutdown in progress
888    */
889   private boolean isClusterUp() {
890     return clusterStatusTracker != null && clusterStatusTracker.isClusterUp();
891   }
892 
893   private void initializeThreads() throws IOException {
894     // Cache flushing thread.
895     this.cacheFlusher = new MemStoreFlusher(conf, this);
896 
897     // Compaction thread
898     this.compactSplitThread = new CompactSplitThread(this);
899 
900     // Background thread to check for compactions; needed if region has not gotten updates
901     // in a while. It will take care of not checking too frequently on store-by-store basis.
902     this.compactionChecker = new CompactionChecker(this, this.threadWakeFrequency, this);
903     this.periodicFlusher = new PeriodicMemstoreFlusher(this.threadWakeFrequency, this);
904     this.leases = new Leases(this.threadWakeFrequency);
905 
906     // Create the thread to clean the moved regions list
907     movedRegionsCleaner = MovedRegionsCleaner.create(this);
908 
909     if (this.nonceManager != null) {
910       // Create the scheduled chore that cleans up nonces.
911       nonceManagerChore = this.nonceManager.createCleanupScheduledChore(this);
912     }
913 
914     // Setup the Quota Manager
915     rsQuotaManager = new RegionServerQuotaManager(this);
916 
917     // Setup RPC client for master communication
918     rpcClient = RpcClientFactory.createClient(conf, clusterId, new InetSocketAddress(
919         rpcServices.isa.getAddress(), 0), clusterConnection.getConnectionMetrics());
920 
921     boolean onlyMetaRefresh = false;
922     int storefileRefreshPeriod = conf.getInt(
923         StorefileRefresherChore.REGIONSERVER_STOREFILE_REFRESH_PERIOD
924       , StorefileRefresherChore.DEFAULT_REGIONSERVER_STOREFILE_REFRESH_PERIOD);
925     if (storefileRefreshPeriod == 0) {
926       storefileRefreshPeriod = conf.getInt(
927           StorefileRefresherChore.REGIONSERVER_META_STOREFILE_REFRESH_PERIOD,
928           StorefileRefresherChore.DEFAULT_REGIONSERVER_STOREFILE_REFRESH_PERIOD);
929       onlyMetaRefresh = true;
930     }
931     if (storefileRefreshPeriod > 0) {
932       this.storefileRefresher = new StorefileRefresherChore(storefileRefreshPeriod,
933           onlyMetaRefresh, this, this);
934     }
935     registerConfigurationObservers();
936   }
937 
938   private void registerConfigurationObservers() {
939     // Registering the compactSplitThread object with the ConfigurationManager.
940     configurationManager.registerObserver(this.compactSplitThread);
941     configurationManager.registerObserver(this.rpcServices);
942     configurationManager.registerObserver(this);
943   }
944 
945   /**
946    * The HRegionServer sticks in this loop until closed.
947    */
948   @Override
949   public void run() {
950     try {
951       // Do pre-registration initializations; zookeeper, lease threads, etc.
952       preRegistrationInitialization();
953     } catch (Throwable e) {
954       abort("Fatal exception during initialization", e);
955     }
956 
957     try {
958       if (!isStopped() && !isAborted()) {
959         ShutdownHook.install(conf, fs, this, Thread.currentThread());
960         // Initialize the RegionServerCoprocessorHost now that our ephemeral
961         // node was created, in case any coprocessors want to use ZooKeeper
962         this.rsHost = new RegionServerCoprocessorHost(this, this.conf);
963       }
964 
965       // Try and register with the Master; tell it we are here.  Break if
966       // server is stopped or the clusterup flag is down or hdfs went wacky.
967       while (keepLooping()) {
968         RegionServerStartupResponse w = reportForDuty();
969         if (w == null) {
970           LOG.warn("reportForDuty failed; sleeping and then retrying.");
971           this.sleeper.sleep();
972         } else {
973           handleReportForDutyResponse(w);
974           break;
975         }
976       }
977 
978       if (!isStopped() && isHealthy()){
979         // start the snapshot handler and other procedure handlers,
980         // since the server is ready to run
981         rspmHost.start();
982       }
983 
984       // Start the Quota Manager
985       if (this.rsQuotaManager != null) {
986         rsQuotaManager.start(getRpcServer().getScheduler());
987       }
988 
989       // We registered with the Master.  Go into run mode.
990       long lastMsg = System.currentTimeMillis();
991       long oldRequestCount = -1;
992       // The main run loop.
993       while (!isStopped() && isHealthy()) {
994         if (!isClusterUp()) {
995           if (isOnlineRegionsEmpty()) {
996             stop("Exiting; cluster shutdown set and not carrying any regions");
997           } else if (!this.stopping) {
998             this.stopping = true;
999             LOG.info("Closing user regions");
1000             closeUserRegions(this.abortRequested);
1001           } else if (this.stopping) {
1002             boolean allUserRegionsOffline = areAllUserRegionsOffline();
1003             if (allUserRegionsOffline) {
1004               // Set stopped if no more write requests tp meta tables
1005               // since last time we went around the loop.  Any open
1006               // meta regions will be closed on our way out.
1007               if (oldRequestCount == getWriteRequestCount()) {
1008                 stop("Stopped; only catalog regions remaining online");
1009                 break;
1010               }
1011               oldRequestCount = getWriteRequestCount();
1012             } else {
1013               // Make sure all regions have been closed -- some regions may
1014               // have not got it because we were splitting at the time of
1015               // the call to closeUserRegions.
1016               closeUserRegions(this.abortRequested);
1017             }
1018             LOG.debug("Waiting on " + getOnlineRegionsAsPrintableString());
1019           }
1020         }
1021         long now = System.currentTimeMillis();
1022         if ((now - lastMsg) >= msgInterval) {
1023           tryRegionServerReport(lastMsg, now);
1024           lastMsg = System.currentTimeMillis();
1025         }
1026         if (!isStopped() && !isAborted()) {
1027           this.sleeper.sleep();
1028         }
1029       } // for
1030     } catch (Throwable t) {
1031       if (!rpcServices.checkOOME(t)) {
1032         String prefix = t instanceof YouAreDeadException? "": "Unhandled: ";
1033         abort(prefix + t.getMessage(), t);
1034       }
1035     }
1036     // Run shutdown.
1037     if (mxBean != null) {
1038       MBeanUtil.unregisterMBean(mxBean);
1039       mxBean = null;
1040     }
1041     if (this.leases != null) this.leases.closeAfterLeasesExpire();
1042     if (this.splitLogWorker != null) {
1043       splitLogWorker.stop();
1044     }
1045     if (this.infoServer != null) {
1046       LOG.info("Stopping infoServer");
1047       try {
1048         this.infoServer.stop();
1049       } catch (Exception e) {
1050         LOG.error("Failed to stop infoServer", e);
1051       }
1052     }
1053     // Send cache a shutdown.
1054     if (cacheConfig != null && cacheConfig.isBlockCacheEnabled()) {
1055       cacheConfig.getBlockCache().shutdown();
1056     }
1057 
1058     if (movedRegionsCleaner != null) {
1059       movedRegionsCleaner.stop("Region Server stopping");
1060     }
1061 
1062     // Send interrupts to wake up threads if sleeping so they notice shutdown.
1063     // TODO: Should we check they are alive? If OOME could have exited already
1064     if (this.hMemManager != null) this.hMemManager.stop();
1065     if (this.cacheFlusher != null) this.cacheFlusher.interruptIfNecessary();
1066     if (this.compactSplitThread != null) this.compactSplitThread.interruptIfNecessary();
1067     sendShutdownInterrupt();
1068 
1069     // Stop the quota manager
1070     if (rsQuotaManager != null) {
1071       rsQuotaManager.stop();
1072     }
1073 
1074     // Stop the snapshot and other procedure handlers, forcefully killing all running tasks
1075     if (rspmHost != null) {
1076       rspmHost.stop(this.abortRequested || this.killed);
1077     }
1078 
1079     if (this.killed) {
1080       // Just skip out w/o closing regions.  Used when testing.
1081     } else if (abortRequested) {
1082       if (this.fsOk) {
1083         closeUserRegions(abortRequested); // Don't leave any open file handles
1084       }
1085       LOG.info("aborting server " + this.serverName);
1086     } else {
1087       closeUserRegions(abortRequested);
1088       LOG.info("stopping server " + this.serverName);
1089     }
1090 
1091     // so callers waiting for meta without timeout can stop
1092     if (this.metaTableLocator != null) this.metaTableLocator.stop();
1093     if (this.clusterConnection != null && !clusterConnection.isClosed()) {
1094       try {
1095         this.clusterConnection.close();
1096       } catch (IOException e) {
1097         // Although the {@link Closeable} interface throws an {@link
1098         // IOException}, in reality, the implementation would never do that.
1099         LOG.warn("Attempt to close server's short circuit HConnection failed.", e);
1100       }
1101     }
1102 
1103     // Closing the compactSplit thread before closing meta regions
1104     if (!this.killed && containsMetaTableRegions()) {
1105       if (!abortRequested || this.fsOk) {
1106         if (this.compactSplitThread != null) {
1107           this.compactSplitThread.join();
1108           this.compactSplitThread = null;
1109         }
1110         closeMetaTableRegions(abortRequested);
1111       }
1112     }
1113 
1114     if (!this.killed && this.fsOk) {
1115       waitOnAllRegionsToClose(abortRequested);
1116       LOG.info("stopping server " + this.serverName +
1117         "; all regions closed.");
1118     }
1119 
1120     //fsOk flag may be changed when closing regions throws exception.
1121     if (this.fsOk) {
1122       shutdownWAL(!abortRequested);
1123     }
1124 
1125     // Make sure the proxy is down.
1126     if (this.rssStub != null) {
1127       this.rssStub = null;
1128     }
1129     if (this.rpcClient != null) {
1130       this.rpcClient.close();
1131     }
1132     if (this.leases != null) {
1133       this.leases.close();
1134     }
1135     if (this.pauseMonitor != null) {
1136       this.pauseMonitor.stop();
1137     }
1138 
1139     if (!killed) {
1140       stopServiceThreads();
1141     }
1142 
1143     if (this.rpcServices != null) {
1144       this.rpcServices.stop();
1145     }
1146 
1147     try {
1148       deleteMyEphemeralNode();
1149     } catch (KeeperException.NoNodeException nn) {
1150     } catch (KeeperException e) {
1151       LOG.warn("Failed deleting my ephemeral node", e);
1152     }
1153     // We may have failed to delete the znode at the previous step, but
1154     //  we delete the file anyway: a second attempt to delete the znode is likely to fail again.
1155     ZNodeClearer.deleteMyEphemeralNodeOnDisk();
1156 
1157     if (this.zooKeeper != null) {
1158       this.zooKeeper.close();
1159     }
1160     LOG.info("stopping server " + this.serverName +
1161       "; zookeeper connection closed.");
1162 
1163     LOG.info(Thread.currentThread().getName() + " exiting");
1164   }
1165 
1166   private boolean containsMetaTableRegions() {
1167     return onlineRegions.containsKey(HRegionInfo.FIRST_META_REGIONINFO.getEncodedName());
1168   }
1169 
1170   private boolean areAllUserRegionsOffline() {
1171     if (getNumberOfOnlineRegions() > 2) return false;
1172     boolean allUserRegionsOffline = true;
1173     for (Map.Entry<String, Region> e: this.onlineRegions.entrySet()) {
1174       if (!e.getValue().getRegionInfo().isMetaTable()) {
1175         allUserRegionsOffline = false;
1176         break;
1177       }
1178     }
1179     return allUserRegionsOffline;
1180   }
1181 
1182   /**
1183    * @return Current write count for all online regions.
1184    */
1185   private long getWriteRequestCount() {
1186     long writeCount = 0;
1187     for (Map.Entry<String, Region> e: this.onlineRegions.entrySet()) {
1188       writeCount += e.getValue().getWriteRequestsCount();
1189     }
1190     return writeCount;
1191   }
1192 
1193   @VisibleForTesting
1194   protected void tryRegionServerReport(long reportStartTime, long reportEndTime)
1195   throws IOException {
1196     RegionServerStatusService.BlockingInterface rss = rssStub;
1197     if (rss == null) {
1198       // the current server could be stopping.
1199       return;
1200     }
1201     ClusterStatusProtos.ServerLoad sl = buildServerLoad(reportStartTime, reportEndTime);
1202     try {
1203       RegionServerReportRequest.Builder request = RegionServerReportRequest.newBuilder();
1204       ServerName sn = ServerName.parseVersionedServerName(
1205         this.serverName.getVersionedBytes());
1206       request.setServer(ProtobufUtil.toServerName(sn));
1207       request.setLoad(sl);
1208       rss.regionServerReport(null, request.build());
1209     } catch (ServiceException se) {
1210       IOException ioe = ProtobufUtil.getRemoteException(se);
1211       if (ioe instanceof YouAreDeadException) {
1212         // This will be caught and handled as a fatal error in run()
1213         throw ioe;
1214       }
1215       if (rssStub == rss) {
1216         rssStub = null;
1217       }
1218       // Couldn't connect to the master, get location from zk and reconnect
1219       // Method blocks until new master is found or we are stopped
1220       createRegionServerStatusStub(true);
1221     }
1222   }
1223 
1224   ClusterStatusProtos.ServerLoad buildServerLoad(long reportStartTime, long reportEndTime)
1225       throws IOException {
1226     // We're getting the MetricsRegionServerWrapper here because the wrapper computes requests
1227     // per second, and other metrics  As long as metrics are part of ServerLoad it's best to use
1228     // the wrapper to compute those numbers in one place.
1229     // In the long term most of these should be moved off of ServerLoad and the heart beat.
1230     // Instead they should be stored in an HBase table so that external visibility into HBase is
1231     // improved; Additionally the load balancer will be able to take advantage of a more complete
1232     // history.
1233     MetricsRegionServerWrapper regionServerWrapper = metricsRegionServer.getRegionServerWrapper();
1234     Collection<Region> regions = getOnlineRegionsLocalContext();
1235     long usedMemory = -1L;
1236     long maxMemory = -1L;
1237     final MemoryUsage usage = HeapMemorySizeUtil.safeGetHeapMemoryUsage();
1238     if (usage != null) {
1239       usedMemory = usage.getUsed();
1240       maxMemory = usage.getMax();
1241     }
1242 
1243     ClusterStatusProtos.ServerLoad.Builder serverLoad =
1244       ClusterStatusProtos.ServerLoad.newBuilder();
1245     serverLoad.setNumberOfRequests((int) regionServerWrapper.getRequestsPerSecond());
1246     serverLoad.setTotalNumberOfRequests((int) regionServerWrapper.getTotalRequestCount());
1247     serverLoad.setUsedHeapMB((int)(usedMemory / 1024 / 1024));
1248     serverLoad.setMaxHeapMB((int) (maxMemory / 1024 / 1024));
1249     Set<String> coprocessors = getWAL(null).getCoprocessorHost().getCoprocessors();
1250     Builder coprocessorBuilder = Coprocessor.newBuilder();
1251     for (String coprocessor : coprocessors) {
1252       serverLoad.addCoprocessors(coprocessorBuilder.setName(coprocessor).build());
1253     }
1254     RegionLoad.Builder regionLoadBldr = RegionLoad.newBuilder();
1255     RegionSpecifier.Builder regionSpecifier = RegionSpecifier.newBuilder();
1256     for (Region region : regions) {
1257       if (region.getCoprocessorHost() != null) {
1258         Set<String> regionCoprocessors = region.getCoprocessorHost().getCoprocessors();
1259         Iterator<String> iterator = regionCoprocessors.iterator();
1260         while (iterator.hasNext()) {
1261           serverLoad.addCoprocessors(coprocessorBuilder.setName(iterator.next()).build());
1262         }
1263       }
1264       serverLoad.addRegionLoads(createRegionLoad(region, regionLoadBldr, regionSpecifier));
1265       for (String coprocessor : getWAL(region.getRegionInfo()).getCoprocessorHost()
1266           .getCoprocessors()) {
1267         serverLoad.addCoprocessors(coprocessorBuilder.setName(coprocessor).build());
1268       }
1269     }
1270     serverLoad.setReportStartTime(reportStartTime);
1271     serverLoad.setReportEndTime(reportEndTime);
1272     if (this.infoServer != null) {
1273       serverLoad.setInfoServerPort(this.infoServer.getPort());
1274     } else {
1275       serverLoad.setInfoServerPort(-1);
1276     }
1277 
1278     // for the replicationLoad purpose. Only need to get from one service
1279     // either source or sink will get the same info
1280     ReplicationSourceService rsources = getReplicationSourceService();
1281 
1282     if (rsources != null) {
1283       // always refresh first to get the latest value
1284       ReplicationLoad rLoad = rsources.refreshAndGetReplicationLoad();
1285       if (rLoad != null) {
1286         serverLoad.setReplLoadSink(rLoad.getReplicationLoadSink());
1287         for (ClusterStatusProtos.ReplicationLoadSource rLS : rLoad.getReplicationLoadSourceList()) {
1288           serverLoad.addReplLoadSource(rLS);
1289         }
1290       }
1291     }
1292 
1293     return serverLoad.build();
1294   }
1295 
1296   String getOnlineRegionsAsPrintableString() {
1297     StringBuilder sb = new StringBuilder();
1298     for (Region r: this.onlineRegions.values()) {
1299       if (sb.length() > 0) sb.append(", ");
1300       sb.append(r.getRegionInfo().getEncodedName());
1301     }
1302     return sb.toString();
1303   }
1304 
1305   /**
1306    * Wait on regions close.
1307    */
1308   private void waitOnAllRegionsToClose(final boolean abort) {
1309     // Wait till all regions are closed before going out.
1310     int lastCount = -1;
1311     long previousLogTime = 0;
1312     Set<String> closedRegions = new HashSet<String>();
1313     boolean interrupted = false;
1314     try {
1315       while (!isOnlineRegionsEmpty()) {
1316         int count = getNumberOfOnlineRegions();
1317         // Only print a message if the count of regions has changed.
1318         if (count != lastCount) {
1319           // Log every second at most
1320           if (System.currentTimeMillis() > (previousLogTime + 1000)) {
1321             previousLogTime = System.currentTimeMillis();
1322             lastCount = count;
1323             LOG.info("Waiting on " + count + " regions to close");
1324             // Only print out regions still closing if a small number else will
1325             // swamp the log.
1326             if (count < 10 && LOG.isDebugEnabled()) {
1327               LOG.debug(this.onlineRegions);
1328             }
1329           }
1330         }
1331         // Ensure all user regions have been sent a close. Use this to
1332         // protect against the case where an open comes in after we start the
1333         // iterator of onlineRegions to close all user regions.
1334         for (Map.Entry<String, Region> e : this.onlineRegions.entrySet()) {
1335           HRegionInfo hri = e.getValue().getRegionInfo();
1336           if (!this.regionsInTransitionInRS.containsKey(hri.getEncodedNameAsBytes())
1337               && !closedRegions.contains(hri.getEncodedName())) {
1338             closedRegions.add(hri.getEncodedName());
1339             // Don't update zk with this close transition; pass false.
1340             closeRegionIgnoreErrors(hri, abort);
1341               }
1342         }
1343         // No regions in RIT, we could stop waiting now.
1344         if (this.regionsInTransitionInRS.isEmpty()) {
1345           if (!isOnlineRegionsEmpty()) {
1346             LOG.info("We were exiting though online regions are not empty," +
1347                 " because some regions failed closing");
1348           }
1349           break;
1350         }
1351         if (sleep(200)) {
1352           interrupted = true;
1353         }
1354       }
1355     } finally {
1356       if (interrupted) {
1357         Thread.currentThread().interrupt();
1358       }
1359     }
1360   }
1361 
1362   private boolean sleep(long millis) {
1363     boolean interrupted = false;
1364     try {
1365       Thread.sleep(millis);
1366     } catch (InterruptedException e) {
1367       LOG.warn("Interrupted while sleeping");
1368       interrupted = true;
1369     }
1370     return interrupted;
1371   }
1372 
1373   private void shutdownWAL(final boolean close) {
1374     if (this.walFactory != null) {
1375       try {
1376         if (close) {
1377           walFactory.close();
1378         } else {
1379           walFactory.shutdown();
1380         }
1381       } catch (Throwable e) {
1382         e = RemoteExceptionHandler.checkThrowable(e);
1383         LOG.error("Shutdown / close of WAL failed: " + e);
1384         LOG.debug("Shutdown / close exception details:", e);
1385       }
1386     }
1387   }
1388 
1389   /*
1390    * Run init. Sets up wal and starts up all server threads.
1391    *
1392    * @param c Extra configuration.
1393    */
1394   protected void handleReportForDutyResponse(final RegionServerStartupResponse c)
1395   throws IOException {
1396     try {
1397       boolean updateRootDir = false;
1398       for (NameStringPair e : c.getMapEntriesList()) {
1399         String key = e.getName();
1400         // The hostname the master sees us as.
1401         if (key.equals(HConstants.KEY_FOR_HOSTNAME_SEEN_BY_MASTER)) {
1402           String hostnameFromMasterPOV = e.getValue();
1403           this.serverName = ServerName.valueOf(hostnameFromMasterPOV,
1404             rpcServices.isa.getPort(), this.startcode);
1405           if (shouldUseThisHostnameInstead() &&
1406               !hostnameFromMasterPOV.equals(useThisHostnameInstead)) {
1407             String msg = "Master passed us a different hostname to use; was=" +
1408                 this.useThisHostnameInstead + ", but now=" + hostnameFromMasterPOV;
1409             LOG.error(msg);
1410             throw new IOException(msg);
1411           }
1412           if (!shouldUseThisHostnameInstead() &&
1413               !hostnameFromMasterPOV.equals(rpcServices.isa.getHostName())) {
1414             String msg = "Master passed us a different hostname to use; was=" +
1415                 rpcServices.isa.getHostName() + ", but now=" + hostnameFromMasterPOV;
1416             LOG.error(msg);
1417           }
1418           continue;
1419         }
1420         String value = e.getValue();
1421         if (key.equals(HConstants.HBASE_DIR)) {
1422           if (value != null && !value.equals(conf.get(HConstants.HBASE_DIR))) {
1423             updateRootDir = true;
1424           }
1425         }
1426         if (LOG.isDebugEnabled()) {
1427           LOG.info("Config from master: " + key + "=" + value);
1428         }
1429         this.conf.set(key, value);
1430       }
1431       // Set our ephemeral znode up in zookeeper now we have a name.
1432       createMyEphemeralNode();
1433 
1434       if (updateRootDir) {
1435         // initialize file system by the config fs.defaultFS and hbase.rootdir from master
1436         initializeFileSystem();
1437       }
1438 
1439       // hack! Maps DFSClient => RegionServer for logs.  HDFS made this
1440       // config param for task trackers, but we can piggyback off of it.
1441       if (this.conf.get("mapreduce.task.attempt.id") == null) {
1442         this.conf.set("mapreduce.task.attempt.id", "hb_rs_" +
1443           this.serverName.toString());
1444       }
1445 
1446       // Save it in a file, this will allow to see if we crash
1447       ZNodeClearer.writeMyEphemeralNodeOnDisk(getMyEphemeralNodePath());
1448 
1449       this.cacheConfig = new CacheConfig(conf);
1450       this.walFactory = setupWALAndReplication();
1451       // Init in here rather than in constructor after thread name has been set
1452       this.metricsRegionServer = new MetricsRegionServer(
1453           new MetricsRegionServerWrapperImpl(this), conf);
1454       this.metricsTable = new MetricsTable(new MetricsTableWrapperAggregateImpl(this));
1455       // Now that we have a metrics source, start the pause monitor
1456       this.pauseMonitor = new JvmPauseMonitor(conf, getMetrics().getMetricsSource());
1457       pauseMonitor.start();
1458 
1459       startServiceThreads();
1460       startHeapMemoryManager();
1461       LOG.info("Serving as " + this.serverName +
1462         ", RpcServer on " + rpcServices.isa +
1463         ", sessionid=0x" +
1464         Long.toHexString(this.zooKeeper.getRecoverableZooKeeper().getSessionId()));
1465 
1466       // Wake up anyone waiting for this server to online
1467       synchronized (online) {
1468         online.set(true);
1469         online.notifyAll();
1470       }
1471     } catch (Throwable e) {
1472       stop("Failed initialization");
1473       throw convertThrowableToIOE(cleanup(e, "Failed init"),
1474           "Region server startup failed");
1475     } finally {
1476       sleeper.skipSleepCycle();
1477     }
1478   }
1479 
1480   private void startHeapMemoryManager() {
1481     this.hMemManager = HeapMemoryManager.create(this.conf, this.cacheFlusher,
1482         this, this.regionServerAccounting);
1483     if (this.hMemManager != null) {
1484       this.hMemManager.start(getChoreService());
1485     }
1486   }
1487 
1488   private void createMyEphemeralNode() throws KeeperException, IOException {
1489     RegionServerInfo.Builder rsInfo = RegionServerInfo.newBuilder();
1490     rsInfo.setInfoPort(infoServer != null ? infoServer.getPort() : -1);
1491     rsInfo.setVersionInfo(ProtobufUtil.getVersionInfo());
1492     byte[] data = ProtobufUtil.prependPBMagic(rsInfo.build().toByteArray());
1493     ZKUtil.createEphemeralNodeAndWatch(this.zooKeeper,
1494       getMyEphemeralNodePath(), data);
1495   }
1496 
1497   private void deleteMyEphemeralNode() throws KeeperException {
1498     ZKUtil.deleteNode(this.zooKeeper, getMyEphemeralNodePath());
1499   }
1500 
1501   @Override
1502   public RegionServerAccounting getRegionServerAccounting() {
1503     return regionServerAccounting;
1504   }
1505 
1506   @Override
1507   public TableLockManager getTableLockManager() {
1508     return tableLockManager;
1509   }
1510 
1511   /*
1512    * @param r Region to get RegionLoad for.
1513    * @param regionLoadBldr the RegionLoad.Builder, can be null
1514    * @param regionSpecifier the RegionSpecifier.Builder, can be null
1515    * @return RegionLoad instance.
1516    *
1517    * @throws IOException
1518    */
1519   private RegionLoad createRegionLoad(final Region r, RegionLoad.Builder regionLoadBldr,
1520       RegionSpecifier.Builder regionSpecifier) throws IOException {
1521     byte[] name = r.getRegionInfo().getRegionName();
1522     int stores = 0;
1523     int storefiles = 0;
1524     int storeUncompressedSizeMB = 0;
1525     int storefileSizeMB = 0;
1526     int memstoreSizeMB = (int) (r.getMemstoreSize() / 1024 / 1024);
1527     int storefileIndexSizeMB = 0;
1528     int rootIndexSizeKB = 0;
1529     int totalStaticIndexSizeKB = 0;
1530     int totalStaticBloomSizeKB = 0;
1531     long totalCompactingKVs = 0;
1532     long currentCompactedKVs = 0;
1533     List<Store> storeList = r.getStores();
1534     stores += storeList.size();
1535     for (Store store : storeList) {
1536       storefiles += store.getStorefilesCount();
1537       storeUncompressedSizeMB += (int) (store.getStoreSizeUncompressed() / 1024 / 1024);
1538       storefileSizeMB += (int) (store.getStorefilesSize() / 1024 / 1024);
1539       storefileIndexSizeMB += (int) (store.getStorefilesIndexSize() / 1024 / 1024);
1540       CompactionProgress progress = store.getCompactionProgress();
1541       if (progress != null) {
1542         totalCompactingKVs += progress.totalCompactingKVs;
1543         currentCompactedKVs += progress.currentCompactedKVs;
1544       }
1545       rootIndexSizeKB += (int) (store.getStorefilesIndexSize() / 1024);
1546       totalStaticIndexSizeKB += (int) (store.getTotalStaticIndexSize() / 1024);
1547       totalStaticBloomSizeKB += (int) (store.getTotalStaticBloomSize() / 1024);
1548     }
1549 
1550     float dataLocality =
1551         r.getHDFSBlocksDistribution().getBlockLocalityIndex(serverName.getHostname());
1552     if (regionLoadBldr == null) {
1553       regionLoadBldr = RegionLoad.newBuilder();
1554     }
1555     if (regionSpecifier == null) {
1556       regionSpecifier = RegionSpecifier.newBuilder();
1557     }
1558     regionSpecifier.setType(RegionSpecifierType.REGION_NAME);
1559     regionSpecifier.setValue(ByteStringer.wrap(name));
1560     regionLoadBldr.setRegionSpecifier(regionSpecifier.build())
1561       .setStores(stores)
1562       .setStorefiles(storefiles)
1563       .setStoreUncompressedSizeMB(storeUncompressedSizeMB)
1564       .setStorefileSizeMB(storefileSizeMB)
1565       .setMemstoreSizeMB(memstoreSizeMB)
1566       .setStorefileIndexSizeMB(storefileIndexSizeMB)
1567       .setRootIndexSizeKB(rootIndexSizeKB)
1568       .setTotalStaticIndexSizeKB(totalStaticIndexSizeKB)
1569       .setTotalStaticBloomSizeKB(totalStaticBloomSizeKB)
1570       .setReadRequestsCount(r.getReadRequestsCount())
1571       .setWriteRequestsCount(r.getWriteRequestsCount())
1572       .setTotalCompactingKVs(totalCompactingKVs)
1573       .setCurrentCompactedKVs(currentCompactedKVs)
1574       .setDataLocality(dataLocality)
1575       .setLastMajorCompactionTs(r.getOldestHfileTs(true));
1576     ((HRegion)r).setCompleteSequenceId(regionLoadBldr);
1577 
1578     return regionLoadBldr.build();
1579   }
1580 
1581   /**
1582    * @param encodedRegionName
1583    * @return An instance of RegionLoad.
1584    */
1585   public RegionLoad createRegionLoad(final String encodedRegionName) throws IOException {
1586     Region r = onlineRegions.get(encodedRegionName);
1587     return r != null ? createRegionLoad(r, null, null) : null;
1588   }
1589 
1590   /*
1591    * Inner class that runs on a long period checking if regions need compaction.
1592    */
1593   private static class CompactionChecker extends ScheduledChore {
1594     private final HRegionServer instance;
1595     private final int majorCompactPriority;
1596     private final static int DEFAULT_PRIORITY = Integer.MAX_VALUE;
1597     //Iteration is 1-based rather than 0-based so we don't check for compaction
1598     // immediately upon region server startup
1599     private long iteration = 1;
1600 
1601     CompactionChecker(final HRegionServer h, final int sleepTime,
1602         final Stoppable stopper) {
1603       super("CompactionChecker", stopper, sleepTime);
1604       this.instance = h;
1605       LOG.info(this.getName() + " runs every " + StringUtils.formatTime(sleepTime));
1606 
1607       /* MajorCompactPriority is configurable.
1608        * If not set, the compaction will use default priority.
1609        */
1610       this.majorCompactPriority = this.instance.conf.
1611         getInt("hbase.regionserver.compactionChecker.majorCompactPriority",
1612         DEFAULT_PRIORITY);
1613     }
1614 
1615     @Override
1616     protected void chore() {
1617       for (Region r : this.instance.onlineRegions.values()) {
1618         if (r == null)
1619           continue;
1620         for (Store s : r.getStores()) {
1621           try {
1622             long multiplier = s.getCompactionCheckMultiplier();
1623             assert multiplier > 0;
1624             if (iteration % multiplier != 0) continue;
1625             if (s.needsCompaction()) {
1626               // Queue a compaction. Will recognize if major is needed.
1627               this.instance.compactSplitThread.requestSystemCompaction(r, s, getName()
1628                   + " requests compaction");
1629             } else if (s.isMajorCompaction()) {
1630               s.triggerMajorCompaction();
1631               if (majorCompactPriority == DEFAULT_PRIORITY
1632                   || majorCompactPriority > ((HRegion)r).getCompactPriority()) {
1633                 this.instance.compactSplitThread.requestCompaction(r, s, getName()
1634                     + " requests major compaction; use default priority", null);
1635               } else {
1636                 this.instance.compactSplitThread.requestCompaction(r, s, getName()
1637                     + " requests major compaction; use configured priority",
1638                   this.majorCompactPriority, null, null);
1639               }
1640             }
1641           } catch (IOException e) {
1642             LOG.warn("Failed major compaction check on " + r, e);
1643           }
1644         }
1645       }
1646       iteration = (iteration == Long.MAX_VALUE) ? 0 : (iteration + 1);
1647     }
1648   }
1649 
1650   static class PeriodicMemstoreFlusher extends ScheduledChore {
1651     final HRegionServer server;
1652     final static int RANGE_OF_DELAY = 5 * 60 * 1000; // 5 min in milliseconds
1653     final static int MIN_DELAY_TIME = 0; // millisec
1654     public PeriodicMemstoreFlusher(int cacheFlushInterval, final HRegionServer server) {
1655       super(server.getServerName() + "-MemstoreFlusherChore", server, cacheFlushInterval);
1656       this.server = server;
1657     }
1658 
1659     @Override
1660     protected void chore() {
1661       final StringBuffer whyFlush = new StringBuffer();
1662       for (Region r : this.server.onlineRegions.values()) {
1663         if (r == null) continue;
1664         if (((HRegion)r).shouldFlush(whyFlush)) {
1665           FlushRequester requester = server.getFlushRequester();
1666           if (requester != null) {
1667             long randomDelay = (long) RandomUtils.nextInt(RANGE_OF_DELAY) + MIN_DELAY_TIME;
1668             LOG.info(getName() + " requesting flush of " +
1669               r.getRegionInfo().getRegionNameAsString() + " because " +
1670               whyFlush.toString() +
1671               " after random delay " + randomDelay + "ms");
1672             //Throttle the flushes by putting a delay. If we don't throttle, and there
1673             //is a balanced write-load on the regions in a table, we might end up
1674             //overwhelming the filesystem with too many flushes at once.
1675             requester.requestDelayedFlush(r, randomDelay, false);
1676           }
1677         }
1678       }
1679     }
1680   }
1681 
1682   /**
1683    * Report the status of the server. A server is online once all the startup is
1684    * completed (setting up filesystem, starting service threads, etc.). This
1685    * method is designed mostly to be useful in tests.
1686    *
1687    * @return true if online, false if not.
1688    */
1689   public boolean isOnline() {
1690     return online.get();
1691   }
1692 
1693   /**
1694    * Setup WAL log and replication if enabled.
1695    * Replication setup is done in here because it wants to be hooked up to WAL.
1696    * @return A WAL instance.
1697    * @throws IOException
1698    */
1699   private WALFactory setupWALAndReplication() throws IOException {
1700     // TODO Replication make assumptions here based on the default filesystem impl
1701     final Path oldLogDir = new Path(walRootDir, HConstants.HREGION_OLDLOGDIR_NAME);
1702     final String logName = DefaultWALProvider.getWALDirectoryName(this.serverName.toString());
1703 
1704     Path logDir = new Path(walRootDir, logName);
1705     if (LOG.isDebugEnabled()) LOG.debug("logDir=" + logDir);
1706     if (this.walFs.exists(logDir)) {
1707       throw new RegionServerRunningException("Region server has already " +
1708         "created directory at " + this.serverName.toString());
1709     }
1710 
1711     // Instantiate replication manager if replication enabled.  Pass it the
1712     // log directories.
1713     createNewReplicationInstance(conf, this, this.walFs, logDir, oldLogDir);
1714 
1715     // listeners the wal factory will add to wals it creates.
1716     final List<WALActionsListener> listeners = new ArrayList<WALActionsListener>();
1717     listeners.add(new MetricsWAL());
1718     if (this.replicationSourceHandler != null &&
1719         this.replicationSourceHandler.getWALActionsListener() != null) {
1720       // Replication handler is an implementation of WALActionsListener.
1721       listeners.add(this.replicationSourceHandler.getWALActionsListener());
1722     }
1723 
1724     return new WALFactory(conf, listeners, serverName.toString());
1725   }
1726 
1727   /**
1728    * We initialize the roller for the wal that handles meta lazily
1729    * since we don't know if this regionserver will handle it. All calls to
1730    * this method return a reference to the that same roller. As newly referenced
1731    * meta regions are brought online, they will be offered to the roller for maintenance.
1732    * As a part of that registration process, the roller will add itself as a
1733    * listener on the wal.
1734    */
1735   protected LogRoller ensureMetaWALRoller() {
1736     // Using a tmp log roller to ensure metaLogRoller is alive once it is not
1737     // null
1738     LogRoller roller = metawalRoller.get();
1739     if (null == roller) {
1740       LogRoller tmpLogRoller = new LogRoller(this, this);
1741       String n = Thread.currentThread().getName();
1742       Threads.setDaemonThreadRunning(tmpLogRoller.getThread(),
1743           n + "-MetaLogRoller", uncaughtExceptionHandler);
1744       if (metawalRoller.compareAndSet(null, tmpLogRoller)) {
1745         roller = tmpLogRoller;
1746       } else {
1747         // Another thread won starting the roller
1748         Threads.shutdown(tmpLogRoller.getThread());
1749         roller = metawalRoller.get();
1750       }
1751     }
1752     return roller;
1753   }
1754 
1755   public MetricsRegionServer getRegionServerMetrics() {
1756     return this.metricsRegionServer;
1757   }
1758 
1759   /**
1760    * @return Master address tracker instance.
1761    */
1762   public MasterAddressTracker getMasterAddressTracker() {
1763     return this.masterAddressTracker;
1764   }
1765 
1766   /*
1767    * Start maintenance Threads, Server, Worker and lease checker threads.
1768    * Install an UncaughtExceptionHandler that calls abort of RegionServer if we
1769    * get an unhandled exception. We cannot set the handler on all threads.
1770    * Server's internal Listener thread is off limits. For Server, if an OOME, it
1771    * waits a while then retries. Meantime, a flush or a compaction that tries to
1772    * run should trigger same critical condition and the shutdown will run. On
1773    * its way out, this server will shut down Server. Leases are sort of
1774    * inbetween. It has an internal thread that while it inherits from Chore, it
1775    * keeps its own internal stop mechanism so needs to be stopped by this
1776    * hosting server. Worker logs the exception and exits.
1777    */
1778   private void startServiceThreads() throws IOException {
1779     // Start executor services
1780     this.service.startExecutorService(ExecutorType.RS_OPEN_REGION,
1781       conf.getInt("hbase.regionserver.executor.openregion.threads", 3));
1782     this.service.startExecutorService(ExecutorType.RS_OPEN_META,
1783       conf.getInt("hbase.regionserver.executor.openmeta.threads", 1));
1784     this.service.startExecutorService(ExecutorType.RS_OPEN_PRIORITY_REGION,
1785       conf.getInt("hbase.regionserver.executor.openpriorityregion.threads", 3));
1786     this.service.startExecutorService(ExecutorType.RS_CLOSE_REGION,
1787       conf.getInt("hbase.regionserver.executor.closeregion.threads", 3));
1788     this.service.startExecutorService(ExecutorType.RS_CLOSE_META,
1789       conf.getInt("hbase.regionserver.executor.closemeta.threads", 1));
1790     if (conf.getBoolean(StoreScanner.STORESCANNER_PARALLEL_SEEK_ENABLE, false)) {
1791       this.service.startExecutorService(ExecutorType.RS_PARALLEL_SEEK,
1792         conf.getInt("hbase.storescanner.parallel.seek.threads", 10));
1793     }
1794     this.service.startExecutorService(ExecutorType.RS_LOG_REPLAY_OPS, conf.getInt(
1795        "hbase.regionserver.wal.max.splitters", SplitLogWorkerCoordination.DEFAULT_MAX_SPLITTERS));
1796     // Start the threads for compacted files discharger
1797     this.service.startExecutorService(ExecutorType.RS_COMPACTED_FILES_DISCHARGER,
1798       conf.getInt(CompactionConfiguration.HBASE_HFILE_COMPACTION_DISCHARGER_THREAD_COUNT, 10));
1799     if (ServerRegionReplicaUtil.isRegionReplicaWaitForPrimaryFlushEnabled(conf)) {
1800       this.service.startExecutorService(ExecutorType.RS_REGION_REPLICA_FLUSH_OPS,
1801         conf.getInt("hbase.regionserver.region.replica.flusher.threads",
1802           conf.getInt("hbase.regionserver.executor.openregion.threads", 3)));
1803     }
1804 
1805     Threads.setDaemonThreadRunning(this.walRoller.getThread(), getName() + ".logRoller",
1806         uncaughtExceptionHandler);
1807     this.cacheFlusher.start(uncaughtExceptionHandler);
1808 
1809     if (this.compactionChecker != null) choreService.scheduleChore(compactionChecker);
1810     if (this.periodicFlusher != null) choreService.scheduleChore(periodicFlusher);
1811     if (this.healthCheckChore != null) choreService.scheduleChore(healthCheckChore);
1812     if (this.nonceManagerChore != null) choreService.scheduleChore(nonceManagerChore);
1813     if (this.storefileRefresher != null) choreService.scheduleChore(storefileRefresher);
1814     if (this.movedRegionsCleaner != null) choreService.scheduleChore(movedRegionsCleaner);
1815 
1816     // Leases is not a Thread. Internally it runs a daemon thread. If it gets
1817     // an unhandled exception, it will just exit.
1818     Threads.setDaemonThreadRunning(this.leases.getThread(), getName() + ".leaseChecker",
1819       uncaughtExceptionHandler);
1820 
1821     if (this.replicationSourceHandler == this.replicationSinkHandler &&
1822         this.replicationSourceHandler != null) {
1823       this.replicationSourceHandler.startReplicationService();
1824     } else {
1825       if (this.replicationSourceHandler != null) {
1826         this.replicationSourceHandler.startReplicationService();
1827       }
1828       if (this.replicationSinkHandler != null) {
1829         this.replicationSinkHandler.startReplicationService();
1830       }
1831     }
1832 
1833     // Create the log splitting worker and start it
1834     // set a smaller retries to fast fail otherwise splitlogworker could be blocked for
1835     // quite a while inside HConnection layer. The worker won't be available for other
1836     // tasks even after current task is preempted after a split task times out.
1837     Configuration sinkConf = HBaseConfiguration.create(conf);
1838     sinkConf.setInt(HConstants.HBASE_CLIENT_RETRIES_NUMBER,
1839       conf.getInt("hbase.log.replay.retries.number", 8)); // 8 retries take about 23 seconds
1840     sinkConf.setInt(HConstants.HBASE_RPC_TIMEOUT_KEY,
1841       conf.getInt("hbase.log.replay.rpc.timeout", 30000)); // default 30 seconds
1842     sinkConf.setInt("hbase.client.serverside.retries.multiplier", 1);
1843     this.splitLogWorker = new SplitLogWorker(this, sinkConf, this, this, walFactory);
1844     splitLogWorker.start();
1845   }
1846 
1847   /**
1848    * Puts up the webui.
1849    * @return Returns final port -- maybe different from what we started with.
1850    * @throws IOException
1851    */
1852   private int putUpWebUI() throws IOException {
1853     int port = this.conf.getInt(HConstants.REGIONSERVER_INFO_PORT,
1854       HConstants.DEFAULT_REGIONSERVER_INFOPORT);
1855     String addr = this.conf.get("hbase.regionserver.info.bindAddress", "0.0.0.0");
1856 
1857     if(this instanceof HMaster) {
1858       port = conf.getInt(HConstants.MASTER_INFO_PORT,
1859           HConstants.DEFAULT_MASTER_INFOPORT);
1860       addr = this.conf.get("hbase.master.info.bindAddress", "0.0.0.0");
1861     }
1862     // -1 is for disabling info server
1863     if (port < 0) return port;
1864 
1865     if (!Addressing.isLocalAddress(InetAddress.getByName(addr))) {
1866       String msg =
1867           "Failed to start http info server. Address " + addr
1868               + " does not belong to this host. Correct configuration parameter: "
1869               + "hbase.regionserver.info.bindAddress";
1870       LOG.error(msg);
1871       throw new IOException(msg);
1872     }
1873     // check if auto port bind enabled
1874     boolean auto = this.conf.getBoolean(HConstants.REGIONSERVER_INFO_PORT_AUTO,
1875         false);
1876     while (true) {
1877       try {
1878         this.infoServer = new InfoServer(getProcessName(), addr, port, false, this.conf);
1879         infoServer.addServlet("dump", "/dump", getDumpServlet());
1880         configureInfoServer();
1881         this.infoServer.start();
1882         break;
1883       } catch (BindException e) {
1884         if (!auto) {
1885           // auto bind disabled throw BindException
1886           LOG.error("Failed binding http info server to port: " + port);
1887           throw e;
1888         }
1889         // auto bind enabled, try to use another port
1890         LOG.info("Failed binding http info server to port: " + port);
1891         port++;
1892       }
1893     }
1894     port = this.infoServer.getPort();
1895     conf.setInt(HConstants.REGIONSERVER_INFO_PORT, port);
1896     int masterInfoPort = conf.getInt(HConstants.MASTER_INFO_PORT,
1897       HConstants.DEFAULT_MASTER_INFOPORT);
1898     conf.setInt("hbase.master.info.port.orig", masterInfoPort);
1899     conf.setInt(HConstants.MASTER_INFO_PORT, port);
1900     return port;
1901   }
1902 
1903   /*
1904    * Verify that server is healthy
1905    */
1906   private boolean isHealthy() {
1907     if (!fsOk) {
1908       // File system problem
1909       return false;
1910     }
1911     // Verify that all threads are alive
1912     if (!(leases.isAlive()
1913         && cacheFlusher.isAlive() && walRoller.isAlive()
1914         && this.compactionChecker.isScheduled()
1915         && this.periodicFlusher.isScheduled())) {
1916       stop("One or more threads are no longer alive -- stop");
1917       return false;
1918     }
1919     final LogRoller metawalRoller = this.metawalRoller.get();
1920     if (metawalRoller != null && !metawalRoller.isAlive()) {
1921       stop("Meta WAL roller thread is no longer alive -- stop");
1922       return false;
1923     }
1924     return true;
1925   }
1926 
1927   private static final byte[] UNSPECIFIED_REGION = new byte[]{};
1928 
1929   public List<WAL> getWALs() throws IOException {
1930     return walFactory.getWALs();
1931   }
1932 
1933   @Override
1934   public WAL getWAL(HRegionInfo regionInfo) throws IOException {
1935     WAL wal;
1936     LogRoller roller = walRoller;
1937     //_ROOT_ and hbase:meta regions have separate WAL.
1938     if (regionInfo != null && regionInfo.isMetaTable() &&
1939         regionInfo.getReplicaId() == HRegionInfo.DEFAULT_REPLICA_ID) {
1940       roller = ensureMetaWALRoller();
1941       wal = walFactory.getMetaWAL(regionInfo.getEncodedNameAsBytes());
1942     } else if (regionInfo == null) {
1943       wal = walFactory.getWAL(UNSPECIFIED_REGION, null);
1944     } else {
1945       byte[] namespace = regionInfo.getTable().getNamespace();
1946       wal = walFactory.getWAL(regionInfo.getEncodedNameAsBytes(), namespace);
1947     }
1948     roller.addWAL(wal);
1949     return wal;
1950   }
1951 
1952   @Override
1953   public ClusterConnection getConnection() {
1954     return this.clusterConnection;
1955   }
1956 
1957   @Override
1958   public MetaTableLocator getMetaTableLocator() {
1959     return this.metaTableLocator;
1960   }
1961 
1962   @Override
1963   public void stop(final String msg) {
1964     stop(msg, false);
1965   }
1966 
1967   /**
1968    * Stops the regionserver.
1969    * @param msg Status message
1970    * @param force True if this is a regionserver abort
1971    */
1972   public void stop(final String msg, final boolean force) {
1973     if (!this.stopped) {
1974       if (this.rsHost != null) {
1975         // when forced via abort don't allow CPs to override
1976         try {
1977           this.rsHost.preStop(msg);
1978         } catch (IOException ioe) {
1979           if (!force) {
1980             LOG.warn("The region server did not stop", ioe);
1981             return;
1982           }
1983           LOG.warn("Skipping coprocessor exception on preStop() due to forced shutdown", ioe);
1984         }
1985       }
1986       this.stopped = true;
1987       LOG.info("STOPPED: " + msg);
1988       // Wakes run() if it is sleeping
1989       sleeper.skipSleepCycle();
1990     }
1991   }
1992 
1993   public void waitForServerOnline(){
1994     while (!isStopped() && !isOnline()) {
1995       synchronized (online) {
1996         try {
1997           online.wait(msgInterval);
1998         } catch (InterruptedException ie) {
1999           Thread.currentThread().interrupt();
2000           break;
2001         }
2002       }
2003     }
2004   }
2005 
2006   @Override
2007   public void postOpenDeployTasks(final Region r) throws KeeperException, IOException {
2008     postOpenDeployTasks(new PostOpenDeployContext(r, -1));
2009   }
2010 
2011   @Override
2012   public void postOpenDeployTasks(final PostOpenDeployContext context)
2013       throws KeeperException, IOException {
2014     Region r = context.getRegion();
2015     long masterSystemTime = context.getMasterSystemTime();
2016     Preconditions.checkArgument(r instanceof HRegion, "r must be an HRegion");
2017     rpcServices.checkOpen();
2018     LOG.info("Post open deploy tasks for " + r.getRegionInfo().getRegionNameAsString());
2019     // Do checks to see if we need to compact (references or too many files)
2020     for (Store s : r.getStores()) {
2021       if (s.hasReferences() || s.needsCompaction()) {
2022        this.compactSplitThread.requestSystemCompaction(r, s, "Opening Region");
2023       }
2024     }
2025     long openSeqNum = r.getOpenSeqNum();
2026     if (openSeqNum == HConstants.NO_SEQNUM) {
2027       // If we opened a region, we should have read some sequence number from it.
2028       LOG.error("No sequence number found when opening " +
2029         r.getRegionInfo().getRegionNameAsString());
2030       openSeqNum = 0;
2031     }
2032 
2033     // Update flushed sequence id of a recovering region in ZK
2034     updateRecoveringRegionLastFlushedSequenceId(r);
2035 
2036     // Update ZK, or META
2037     if (r.getRegionInfo().isMetaRegion()) {
2038       MetaTableLocator.setMetaLocation(getZooKeeper(), serverName, r.getRegionInfo().getReplicaId(),
2039          State.OPEN);
2040     } else if (useZKForAssignment) {
2041       MetaTableAccessor.updateRegionLocation(getConnection(), r.getRegionInfo(),
2042         this.serverName, openSeqNum, masterSystemTime);
2043     }
2044     if (!useZKForAssignment && !reportRegionStateTransition(new RegionStateTransitionContext(
2045         TransitionCode.OPENED, openSeqNum, masterSystemTime, r.getRegionInfo()))) {
2046       throw new IOException("Failed to report opened region to master: "
2047         + r.getRegionInfo().getRegionNameAsString());
2048     }
2049 
2050     triggerFlushInPrimaryRegion((HRegion)r);
2051 
2052     LOG.debug("Finished post open deploy task for " + r.getRegionInfo().getRegionNameAsString());
2053   }
2054 
2055   @Override
2056   public boolean reportRegionStateTransition(TransitionCode code, HRegionInfo... hris) {
2057     return reportRegionStateTransition(code, HConstants.NO_SEQNUM, hris);
2058   }
2059 
2060   @Override
2061   public boolean reportRegionStateTransition(
2062       TransitionCode code, long openSeqNum, HRegionInfo... hris) {
2063     return reportRegionStateTransition(
2064       new RegionStateTransitionContext(code, HConstants.NO_SEQNUM, -1, hris));
2065   }
2066 
2067   @Override
2068   public boolean reportRegionStateTransition(final RegionStateTransitionContext context) {
2069     TransitionCode code = context.getCode();
2070     long openSeqNum = context.getOpenSeqNum();
2071     HRegionInfo[] hris = context.getHris();
2072 
2073     ReportRegionStateTransitionRequest.Builder builder =
2074       ReportRegionStateTransitionRequest.newBuilder();
2075     builder.setServer(ProtobufUtil.toServerName(serverName));
2076     RegionStateTransition.Builder transition = builder.addTransitionBuilder();
2077     transition.setTransitionCode(code);
2078     if (code == TransitionCode.OPENED && openSeqNum >= 0) {
2079       transition.setOpenSeqNum(openSeqNum);
2080     }
2081     for (HRegionInfo hri: hris) {
2082       transition.addRegionInfo(HRegionInfo.convert(hri));
2083     }
2084     ReportRegionStateTransitionRequest request = builder.build();
2085     while (keepLooping()) {
2086       RegionServerStatusService.BlockingInterface rss = rssStub;
2087       try {
2088         if (rss == null) {
2089           createRegionServerStatusStub();
2090           continue;
2091         }
2092         ReportRegionStateTransitionResponse response =
2093           rss.reportRegionStateTransition(null, request);
2094         if (response.hasErrorMessage()) {
2095           LOG.info("Failed to transition " + hris[0]
2096             + " to " + code + ": " + response.getErrorMessage());
2097           return false;
2098         }
2099         return true;
2100       } catch (ServiceException se) {
2101         IOException ioe = ProtobufUtil.getRemoteException(se);
2102         LOG.info("Failed to report region transition, will retry", ioe);
2103         if (rssStub == rss) {
2104           rssStub = null;
2105         }
2106       }
2107     }
2108     return false;
2109   }
2110 
2111   /**
2112    * Trigger a flush in the primary region replica if this region is a secondary replica. Does not
2113    * block this thread. See RegionReplicaFlushHandler for details.
2114    */
2115   void triggerFlushInPrimaryRegion(final HRegion region) {
2116     if (ServerRegionReplicaUtil.isDefaultReplica(region.getRegionInfo())) {
2117       return;
2118     }
2119     if (!ServerRegionReplicaUtil.isRegionReplicaReplicationEnabled(region.conf) ||
2120         !ServerRegionReplicaUtil.isRegionReplicaWaitForPrimaryFlushEnabled(
2121           region.conf)) {
2122       region.setReadsEnabled(true);
2123       return;
2124     }
2125 
2126     region.setReadsEnabled(false); // disable reads before marking the region as opened.
2127     // RegionReplicaFlushHandler might reset this.
2128 
2129     // submit it to be handled by one of the handlers so that we do not block OpenRegionHandler
2130     this.service.submit(
2131       new RegionReplicaFlushHandler(this, clusterConnection,
2132         rpcRetryingCallerFactory, rpcControllerFactory, operationTimeout, region));
2133   }
2134 
2135   @Override
2136   public RpcServerInterface getRpcServer() {
2137     return rpcServices.rpcServer;
2138   }
2139 
2140   @VisibleForTesting
2141   public RSRpcServices getRSRpcServices() {
2142     return rpcServices;
2143   }
2144 
2145   /**
2146    * Cause the server to exit without closing the regions it is serving, the log
2147    * it is using and without notifying the master. Used unit testing and on
2148    * catastrophic events such as HDFS is yanked out from under hbase or we OOME.
2149    *
2150    * @param reason
2151    *          the reason we are aborting
2152    * @param cause
2153    *          the exception that caused the abort, or null
2154    */
2155   @Override
2156   public void abort(final String reason, Throwable cause) {
2157     String msg = "ABORTING region server " + this + ": " + reason;
2158     if (cause != null) {
2159       LOG.fatal(msg, cause);
2160     } else {
2161       LOG.fatal(msg);
2162     }
2163     this.abortRequested = true;
2164     // HBASE-4014: show list of coprocessors that were loaded to help debug
2165     // regionserver crashes.Note that we're implicitly using
2166     // java.util.HashSet's toString() method to print the coprocessor names.
2167     LOG.fatal("RegionServer abort: loaded coprocessors are: " +
2168         CoprocessorHost.getLoadedCoprocessors());
2169     // Try and dump metrics if abort -- might give clue as to how fatal came about....
2170     try {
2171       LOG.info("Dump of metrics as JSON on abort: " + JSONBean.dumpRegionServerMetrics());
2172     } catch (MalformedObjectNameException | IOException e) {
2173       LOG.warn("Failed dumping metrics", e);
2174     }
2175 
2176     // Do our best to report our abort to the master, but this may not work
2177     try {
2178       if (cause != null) {
2179         msg += "\nCause:\n" + StringUtils.stringifyException(cause);
2180       }
2181       // Report to the master but only if we have already registered with the master.
2182       if (rssStub != null && this.serverName != null) {
2183         ReportRSFatalErrorRequest.Builder builder =
2184           ReportRSFatalErrorRequest.newBuilder();
2185         ServerName sn =
2186           ServerName.parseVersionedServerName(this.serverName.getVersionedBytes());
2187         builder.setServer(ProtobufUtil.toServerName(sn));
2188         builder.setErrorMessage(msg);
2189         rssStub.reportRSFatalError(null, builder.build());
2190       }
2191     } catch (Throwable t) {
2192       LOG.warn("Unable to report fatal error to master", t);
2193     }
2194     // shutdown should be run as the internal user
2195     if (User.isHBaseSecurityEnabled(conf)) {
2196       try {
2197         User.runAsLoginUser(new PrivilegedExceptionAction<Object>() {
2198           @Override
2199           public Object run() throws Exception {
2200             stop(reason, true);
2201             return null;
2202           }
2203         });
2204       } catch (IOException neverThrown) {
2205       }
2206     } else {
2207       stop(reason, true);
2208     }
2209   }
2210 
2211   /**
2212    * @see HRegionServer#abort(String, Throwable)
2213    */
2214   public void abort(String reason) {
2215     abort(reason, null);
2216   }
2217 
2218   @Override
2219   public boolean isAborted() {
2220     return this.abortRequested;
2221   }
2222 
2223   /*
2224    * Simulate a kill -9 of this server. Exits w/o closing regions or cleaninup
2225    * logs but it does close socket in case want to bring up server on old
2226    * hostname+port immediately.
2227    */
2228   @VisibleForTesting
2229   protected void kill() {
2230     this.killed = true;
2231     abort("Simulated kill");
2232   }
2233 
2234   /**
2235    * Called on stop/abort before closing the cluster connection and meta locator.
2236    */
2237   protected void sendShutdownInterrupt() {
2238   }
2239 
2240   /**
2241    * Wait on all threads to finish. Presumption is that all closes and stops
2242    * have already been called.
2243    */
2244   protected void stopServiceThreads() {
2245     // clean up the scheduled chores
2246     if (this.choreService != null) {
2247       choreService.cancelChore(nonceManagerChore);
2248       choreService.cancelChore(compactionChecker);
2249       choreService.cancelChore(periodicFlusher);
2250       choreService.cancelChore(healthCheckChore);
2251       choreService.cancelChore(storefileRefresher);
2252       choreService.cancelChore(movedRegionsCleaner);
2253       // clean up the remaining scheduled chores (in case we missed out any)
2254       choreService.shutdown();
2255     }
2256 
2257     if (this.cacheFlusher != null) {
2258       this.cacheFlusher.join();
2259     }
2260 
2261     if (this.spanReceiverHost != null) {
2262       this.spanReceiverHost.closeReceivers();
2263     }
2264     if (this.walRoller != null) {
2265       Threads.shutdown(this.walRoller.getThread());
2266     }
2267     final LogRoller metawalRoller = this.metawalRoller.get();
2268     if (metawalRoller != null) {
2269       Threads.shutdown(metawalRoller.getThread());
2270     }
2271     if (this.compactSplitThread != null) {
2272       this.compactSplitThread.join();
2273     }
2274     if (this.service != null) this.service.shutdown();
2275     if (this.replicationSourceHandler != null &&
2276         this.replicationSourceHandler == this.replicationSinkHandler) {
2277       this.replicationSourceHandler.stopReplicationService();
2278     } else {
2279       if (this.replicationSourceHandler != null) {
2280         this.replicationSourceHandler.stopReplicationService();
2281       }
2282       if (this.replicationSinkHandler != null) {
2283         this.replicationSinkHandler.stopReplicationService();
2284       }
2285     }
2286   }
2287 
2288   /**
2289    * @return Return the object that implements the replication
2290    * source service.
2291    */
2292   public ReplicationSourceService getReplicationSourceService() {
2293     return replicationSourceHandler;
2294   }
2295 
2296   /**
2297    * @return Return the object that implements the replication
2298    * sink service.
2299    */
2300   ReplicationSinkService getReplicationSinkService() {
2301     return replicationSinkHandler;
2302   }
2303 
2304   /**
2305    * Get the current master from ZooKeeper and open the RPC connection to it.
2306    * To get a fresh connection, the current rssStub must be null.
2307    * Method will block until a master is available. You can break from this
2308    * block by requesting the server stop.
2309    *
2310    * @return master + port, or null if server has been stopped
2311    */
2312   @VisibleForTesting
2313   protected synchronized ServerName createRegionServerStatusStub() {
2314     // Create RS stub without refreshing the master node from ZK, use cached data
2315     return createRegionServerStatusStub(false);
2316   }
2317 
2318   /**
2319    * Get the current master from ZooKeeper and open the RPC connection to it. To get a fresh
2320    * connection, the current rssStub must be null. Method will block until a master is available.
2321    * You can break from this block by requesting the server stop.
2322    * @param refresh If true then master address will be read from ZK, otherwise use cached data
2323    * @return master + port, or null if server has been stopped
2324    */
2325   @VisibleForTesting
2326   protected synchronized ServerName createRegionServerStatusStub(boolean refresh) {
2327     if (rssStub != null) {
2328       return masterAddressTracker.getMasterAddress();
2329     }
2330     ServerName sn = null;
2331     long previousLogTime = 0;
2332     RegionServerStatusService.BlockingInterface intf = null;
2333     boolean interrupted = false;
2334     try {
2335       while (keepLooping()) {
2336         sn = this.masterAddressTracker.getMasterAddress(refresh);
2337         if (sn == null) {
2338           if (!keepLooping()) {
2339             // give up with no connection.
2340             LOG.debug("No master found and cluster is stopped; bailing out");
2341             return null;
2342           }
2343           if (System.currentTimeMillis() > (previousLogTime + 1000)) {
2344             LOG.debug("No master found; retry");
2345             previousLogTime = System.currentTimeMillis();
2346           }
2347           refresh = true; // let's try pull it from ZK directly
2348           if (sleep(200)) {
2349             interrupted = true;
2350           }
2351           continue;
2352         }
2353 
2354         // If we are on the active master, use the shortcut
2355         if (this instanceof HMaster && sn.equals(getServerName())) {
2356           intf = ((HMaster)this).getMasterRpcServices();
2357           break;
2358         }
2359         try {
2360           BlockingRpcChannel channel =
2361             this.rpcClient.createBlockingRpcChannel(sn, userProvider.getCurrent(),
2362               shortOperationTimeout);
2363           intf = RegionServerStatusService.newBlockingStub(channel);
2364           break;
2365         } catch (IOException e) {
2366           if (System.currentTimeMillis() > (previousLogTime + 1000)) {
2367             e = e instanceof RemoteException ?
2368               ((RemoteException)e).unwrapRemoteException() : e;
2369             if (e instanceof ServerNotRunningYetException) {
2370               LOG.info("Master isn't available yet, retrying");
2371             } else {
2372               LOG.warn("Unable to connect to master. Retrying. Error was:", e);
2373             }
2374             previousLogTime = System.currentTimeMillis();
2375           }
2376           if (sleep(200)) {
2377             interrupted = true;
2378           }
2379         }
2380       }
2381     } finally {
2382       if (interrupted) {
2383         Thread.currentThread().interrupt();
2384       }
2385     }
2386     rssStub = intf;
2387     return sn;
2388   }
2389 
2390   /**
2391    * @return True if we should break loop because cluster is going down or
2392    * this server has been stopped or hdfs has gone bad.
2393    */
2394   private boolean keepLooping() {
2395     return !this.stopped && isClusterUp();
2396   }
2397 
2398   /*
2399    * Let the master know we're here Run initialization using parameters passed
2400    * us by the master.
2401    * @return A Map of key/value configurations we got from the Master else
2402    * null if we failed to register.
2403    * @throws IOException
2404    */
2405   private RegionServerStartupResponse reportForDuty() throws IOException {
2406     ServerName masterServerName = createRegionServerStatusStub(true);
2407     if (masterServerName == null) return null;
2408     RegionServerStartupResponse result = null;
2409     try {
2410       rpcServices.requestCount.set(0);
2411       rpcServices.rpcGetRequestCount.set(0);
2412       rpcServices.rpcScanRequestCount.set(0);
2413       rpcServices.rpcMultiRequestCount.set(0);
2414       rpcServices.rpcMutateRequestCount.set(0);
2415       LOG.info("reportForDuty to master=" + masterServerName + " with port="
2416         + rpcServices.isa.getPort() + ", startcode=" + this.startcode);
2417       long now = EnvironmentEdgeManager.currentTime();
2418       int port = rpcServices.isa.getPort();
2419       RegionServerStartupRequest.Builder request = RegionServerStartupRequest.newBuilder();
2420       if (shouldUseThisHostnameInstead()) {
2421         request.setUseThisHostnameInstead(useThisHostnameInstead);
2422       }
2423       request.setPort(port);
2424       request.setServerStartCode(this.startcode);
2425       request.setServerCurrentTime(now);
2426       result = this.rssStub.regionServerStartup(null, request.build());
2427     } catch (ServiceException se) {
2428       IOException ioe = ProtobufUtil.getRemoteException(se);
2429       if (ioe instanceof ClockOutOfSyncException) {
2430         LOG.fatal("Master rejected startup because clock is out of sync", ioe);
2431         // Re-throw IOE will cause RS to abort
2432         throw ioe;
2433       } else if (ioe instanceof ServerNotRunningYetException) {
2434         LOG.debug("Master is not running yet");
2435       } else {
2436         LOG.warn("error telling master we are up", se);
2437       }
2438       rssStub = null;
2439     }
2440     return result;
2441   }
2442 
2443   @Override
2444   public RegionStoreSequenceIds getLastSequenceId(byte[] encodedRegionName) {
2445     try {
2446       GetLastFlushedSequenceIdRequest req =
2447           RequestConverter.buildGetLastFlushedSequenceIdRequest(encodedRegionName);
2448       RegionServerStatusService.BlockingInterface rss = rssStub;
2449       if (rss == null) { // Try to connect one more time
2450         createRegionServerStatusStub();
2451         rss = rssStub;
2452         if (rss == null) {
2453           // Still no luck, we tried
2454           LOG.warn("Unable to connect to the master to check " + "the last flushed sequence id");
2455           return RegionStoreSequenceIds.newBuilder().setLastFlushedSequenceId(HConstants.NO_SEQNUM)
2456               .build();
2457         }
2458       }
2459       GetLastFlushedSequenceIdResponse resp = rss.getLastFlushedSequenceId(null, req);
2460       return RegionStoreSequenceIds.newBuilder()
2461           .setLastFlushedSequenceId(resp.getLastFlushedSequenceId())
2462           .addAllStoreSequenceId(resp.getStoreLastFlushedSequenceIdList()).build();
2463     } catch (ServiceException e) {
2464       LOG.warn("Unable to connect to the master to check the last flushed sequence id", e);
2465       return RegionStoreSequenceIds.newBuilder().setLastFlushedSequenceId(HConstants.NO_SEQNUM)
2466           .build();
2467     }
2468   }
2469 
2470   /**
2471    * Closes all regions.  Called on our way out.
2472    * Assumes that its not possible for new regions to be added to onlineRegions
2473    * while this method runs.
2474    */
2475   protected void closeAllRegions(final boolean abort) {
2476     closeUserRegions(abort);
2477     closeMetaTableRegions(abort);
2478   }
2479 
2480   /**
2481    * Close meta region if we carry it
2482    * @param abort Whether we're running an abort.
2483    */
2484   void closeMetaTableRegions(final boolean abort) {
2485     Region meta = null;
2486     this.lock.writeLock().lock();
2487     try {
2488       for (Map.Entry<String, Region> e: onlineRegions.entrySet()) {
2489         HRegionInfo hri = e.getValue().getRegionInfo();
2490         if (hri.isMetaRegion()) {
2491           meta = e.getValue();
2492         }
2493         if (meta != null) break;
2494       }
2495     } finally {
2496       this.lock.writeLock().unlock();
2497     }
2498     if (meta != null) closeRegionIgnoreErrors(meta.getRegionInfo(), abort);
2499   }
2500 
2501   /**
2502    * Schedule closes on all user regions.
2503    * Should be safe calling multiple times because it wont' close regions
2504    * that are already closed or that are closing.
2505    * @param abort Whether we're running an abort.
2506    */
2507   void closeUserRegions(final boolean abort) {
2508     this.lock.writeLock().lock();
2509     try {
2510       for (Map.Entry<String, Region> e: this.onlineRegions.entrySet()) {
2511         Region r = e.getValue();
2512         if (!r.getRegionInfo().isMetaTable() && r.isAvailable()) {
2513           // Don't update zk with this close transition; pass false.
2514           closeRegionIgnoreErrors(r.getRegionInfo(), abort);
2515         }
2516       }
2517     } finally {
2518       this.lock.writeLock().unlock();
2519     }
2520   }
2521 
2522   /** @return the info server */
2523   public InfoServer getInfoServer() {
2524     return infoServer;
2525   }
2526 
2527   /**
2528    * @return true if a stop has been requested.
2529    */
2530   @Override
2531   public boolean isStopped() {
2532     return this.stopped;
2533   }
2534 
2535   @Override
2536   public boolean isStopping() {
2537     return this.stopping;
2538   }
2539 
2540   @Override
2541   public Map<String, Region> getRecoveringRegions() {
2542     return this.recoveringRegions;
2543   }
2544 
2545   /**
2546    *
2547    * @return the configuration
2548    */
2549   @Override
2550   public Configuration getConfiguration() {
2551     return conf;
2552   }
2553 
2554   /** @return the write lock for the server */
2555   ReentrantReadWriteLock.WriteLock getWriteLock() {
2556     return lock.writeLock();
2557   }
2558 
2559   public int getNumberOfOnlineRegions() {
2560     return this.onlineRegions.size();
2561   }
2562 
2563   boolean isOnlineRegionsEmpty() {
2564     return this.onlineRegions.isEmpty();
2565   }
2566 
2567   /**
2568    * For tests, web ui and metrics.
2569    * This method will only work if HRegionServer is in the same JVM as client;
2570    * HRegion cannot be serialized to cross an rpc.
2571    */
2572   public Collection<Region> getOnlineRegionsLocalContext() {
2573     Collection<Region> regions = this.onlineRegions.values();
2574     return Collections.unmodifiableCollection(regions);
2575   }
2576 
2577   @Override
2578   public void addToOnlineRegions(Region region) {
2579     this.onlineRegions.put(region.getRegionInfo().getEncodedName(), region);
2580     configurationManager.registerObserver(region);
2581   }
2582 
2583   /**
2584    * @return A new Map of online regions sorted by region size with the first entry being the
2585    * biggest.  If two regions are the same size, then the last one found wins; i.e. this method
2586    * may NOT return all regions.
2587    */
2588   SortedMap<Long, Region> getCopyOfOnlineRegionsSortedBySize() {
2589     // we'll sort the regions in reverse
2590     SortedMap<Long, Region> sortedRegions = new TreeMap<Long, Region>(
2591         new Comparator<Long>() {
2592           @Override
2593           public int compare(Long a, Long b) {
2594             return -1 * a.compareTo(b);
2595           }
2596         });
2597     // Copy over all regions. Regions are sorted by size with biggest first.
2598     for (Region region : this.onlineRegions.values()) {
2599       sortedRegions.put(region.getMemstoreSize(), region);
2600     }
2601     return sortedRegions;
2602   }
2603 
2604   /**
2605    * @return time stamp in millis of when this region server was started
2606    */
2607   public long getStartcode() {
2608     return this.startcode;
2609   }
2610 
2611   /** @return reference to FlushRequester */
2612   @Override
2613   public FlushRequester getFlushRequester() {
2614     return this.cacheFlusher;
2615   }
2616 
2617   /**
2618    * Get the top N most loaded regions this server is serving so we can tell the
2619    * master which regions it can reallocate if we're overloaded. TODO: actually
2620    * calculate which regions are most loaded. (Right now, we're just grabbing
2621    * the first N regions being served regardless of load.)
2622    */
2623   protected HRegionInfo[] getMostLoadedRegions() {
2624     ArrayList<HRegionInfo> regions = new ArrayList<HRegionInfo>();
2625     for (Region r : onlineRegions.values()) {
2626       if (!r.isAvailable()) {
2627         continue;
2628       }
2629       if (regions.size() < numRegionsToReport) {
2630         regions.add(r.getRegionInfo());
2631       } else {
2632         break;
2633       }
2634     }
2635     return regions.toArray(new HRegionInfo[regions.size()]);
2636   }
2637 
2638   @Override
2639   public Leases getLeases() {
2640     return leases;
2641   }
2642 
2643   /**
2644    * @return Return the rootDir.
2645    */
2646   protected Path getRootDir() {
2647     return rootDir;
2648   }
2649 
2650   /**
2651    * @return Return the fs.
2652    */
2653   @Override
2654   public FileSystem getFileSystem() {
2655     return fs;
2656   }
2657 
2658   /**
2659    * @return Return the walRootDir.
2660    */
2661   protected Path getWALRootDir() {
2662     return walRootDir;
2663   }
2664 
2665   /**
2666    * @return Return the walFs.
2667    */
2668   protected FileSystem getWALFileSystem() {
2669     return walFs;
2670   }
2671 
2672   @Override
2673   public String toString() {
2674     return getServerName().toString();
2675   }
2676 
2677   /**
2678    * Interval at which threads should run
2679    *
2680    * @return the interval
2681    */
2682   public int getThreadWakeFrequency() {
2683     return threadWakeFrequency;
2684   }
2685 
2686   @Override
2687   public ZooKeeperWatcher getZooKeeper() {
2688     return zooKeeper;
2689   }
2690 
2691   @Override
2692   public BaseCoordinatedStateManager getCoordinatedStateManager() {
2693     return csm;
2694   }
2695 
2696   @Override
2697   public ServerName getServerName() {
2698     return serverName;
2699   }
2700 
2701   @Override
2702   public CompactionRequestor getCompactionRequester() {
2703     return this.compactSplitThread;
2704   }
2705 
2706   public RegionServerCoprocessorHost getRegionServerCoprocessorHost(){
2707     return this.rsHost;
2708   }
2709 
2710   @Override
2711   public ConcurrentMap<byte[], Boolean> getRegionsInTransitionInRS() {
2712     return this.regionsInTransitionInRS;
2713   }
2714 
2715   @Override
2716   public ExecutorService getExecutorService() {
2717     return service;
2718   }
2719 
2720   @Override
2721   public ChoreService getChoreService() {
2722     return choreService;
2723   }
2724 
2725   @Override
2726   public RegionServerQuotaManager getRegionServerQuotaManager() {
2727     return rsQuotaManager;
2728   }
2729 
2730   //
2731   // Main program and support routines
2732   //
2733 
2734   /**
2735    * Load the replication service objects, if any
2736    */
2737   static private void createNewReplicationInstance(Configuration conf,
2738     HRegionServer server, FileSystem walFs, Path walDir, Path oldWALDir) throws IOException{
2739 
2740     // If replication is not enabled, then return immediately.
2741     if (!conf.getBoolean(HConstants.REPLICATION_ENABLE_KEY,
2742         HConstants.REPLICATION_ENABLE_DEFAULT)) {
2743       return;
2744     }
2745 
2746     if ((server instanceof HMaster) &&
2747         (!BaseLoadBalancer.userTablesOnMaster(conf))) {
2748       return;
2749     }
2750 
2751     // read in the name of the source replication class from the config file.
2752     String sourceClassname = conf.get(HConstants.REPLICATION_SOURCE_SERVICE_CLASSNAME,
2753                                HConstants.REPLICATION_SERVICE_CLASSNAME_DEFAULT);
2754 
2755     // read in the name of the sink replication class from the config file.
2756     String sinkClassname = conf.get(HConstants.REPLICATION_SINK_SERVICE_CLASSNAME,
2757                              HConstants.REPLICATION_SERVICE_CLASSNAME_DEFAULT);
2758 
2759     // If both the sink and the source class names are the same, then instantiate
2760     // only one object.
2761     if (sourceClassname.equals(sinkClassname)) {
2762       server.replicationSourceHandler = (ReplicationSourceService)
2763                                          newReplicationInstance(sourceClassname,
2764                                          conf, server, walFs, walDir, oldWALDir);
2765       server.replicationSinkHandler = (ReplicationSinkService)
2766                                          server.replicationSourceHandler;
2767     } else {
2768       server.replicationSourceHandler = (ReplicationSourceService)
2769                                          newReplicationInstance(sourceClassname,
2770                                          conf, server, walFs, walDir, oldWALDir);
2771       server.replicationSinkHandler = (ReplicationSinkService)
2772                                          newReplicationInstance(sinkClassname,
2773                                          conf, server, walFs, walDir, oldWALDir);
2774     }
2775   }
2776 
2777   static private ReplicationService newReplicationInstance(String classname,
2778     Configuration conf, HRegionServer server, FileSystem walFs, Path walDir,
2779     Path oldLogDir) throws IOException{
2780 
2781     Class<?> clazz = null;
2782     try {
2783       ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
2784       clazz = Class.forName(classname, true, classLoader);
2785     } catch (java.lang.ClassNotFoundException nfe) {
2786       throw new IOException("Could not find class for " + classname);
2787     }
2788 
2789     // create an instance of the replication object.
2790     ReplicationService service = (ReplicationService)
2791                               ReflectionUtils.newInstance(clazz, conf);
2792     service.initialize(server, walFs, walDir, oldLogDir);
2793     return service;
2794   }
2795 
2796   /**
2797    * Utility for constructing an instance of the passed HRegionServer class.
2798    *
2799    * @param regionServerClass
2800    * @param conf2
2801    * @return HRegionServer instance.
2802    */
2803   public static HRegionServer constructRegionServer(
2804       Class<? extends HRegionServer> regionServerClass,
2805       final Configuration conf2, CoordinatedStateManager cp) {
2806     try {
2807       Constructor<? extends HRegionServer> c = regionServerClass
2808           .getConstructor(Configuration.class, CoordinatedStateManager.class);
2809       return c.newInstance(conf2, cp);
2810     } catch (Exception e) {
2811       throw new RuntimeException("Failed construction of " + "Regionserver: "
2812           + regionServerClass.toString(), e);
2813     }
2814   }
2815 
2816   /**
2817    * @see org.apache.hadoop.hbase.regionserver.HRegionServerCommandLine
2818    */
2819   public static void main(String[] args) throws Exception {
2820     VersionInfo.logVersion();
2821     Configuration conf = HBaseConfiguration.create();
2822     @SuppressWarnings("unchecked")
2823     Class<? extends HRegionServer> regionServerClass = (Class<? extends HRegionServer>) conf
2824         .getClass(HConstants.REGION_SERVER_IMPL, HRegionServer.class);
2825 
2826     new HRegionServerCommandLine(regionServerClass).doMain(args);
2827   }
2828 
2829   /**
2830    * Gets the online regions of the specified table.
2831    * This method looks at the in-memory onlineRegions.  It does not go to <code>hbase:meta</code>.
2832    * Only returns <em>online</em> regions.  If a region on this table has been
2833    * closed during a disable, etc., it will not be included in the returned list.
2834    * So, the returned list may not necessarily be ALL regions in this table, its
2835    * all the ONLINE regions in the table.
2836    * @param tableName
2837    * @return Online regions from <code>tableName</code>
2838    */
2839   @Override
2840   public List<Region> getOnlineRegions(TableName tableName) {
2841      List<Region> tableRegions = new ArrayList<Region>();
2842      synchronized (this.onlineRegions) {
2843        for (Region region: this.onlineRegions.values()) {
2844          HRegionInfo regionInfo = region.getRegionInfo();
2845          if(regionInfo.getTable().equals(tableName)) {
2846            tableRegions.add(region);
2847          }
2848        }
2849      }
2850      return tableRegions;
2851    }
2852 
2853   /**
2854    * Gets the online tables in this RS.
2855    * This method looks at the in-memory onlineRegions.
2856    * @return all the online tables in this RS
2857    */
2858   @Override
2859   public Set<TableName> getOnlineTables() {
2860     Set<TableName> tables = new HashSet<TableName>();
2861     synchronized (this.onlineRegions) {
2862       for (Region region: this.onlineRegions.values()) {
2863         tables.add(region.getTableDesc().getTableName());
2864       }
2865     }
2866     return tables;
2867   }
2868 
2869   // used by org/apache/hbase/tmpl/regionserver/RSStatusTmpl.jamon (HBASE-4070).
2870   public String[] getRegionServerCoprocessors() {
2871     TreeSet<String> coprocessors = new TreeSet<String>();
2872     try {
2873       coprocessors.addAll(getWAL(null).getCoprocessorHost().getCoprocessors());
2874     } catch (IOException exception) {
2875       LOG.warn("Exception attempting to fetch wal coprocessor information for the common wal; " +
2876           "skipping.");
2877       LOG.debug("Exception details for failure to fetch wal coprocessor information.", exception);
2878     }
2879     Collection<Region> regions = getOnlineRegionsLocalContext();
2880     for (Region region: regions) {
2881       coprocessors.addAll(region.getCoprocessorHost().getCoprocessors());
2882       try {
2883         coprocessors.addAll(getWAL(region.getRegionInfo()).getCoprocessorHost().getCoprocessors());
2884       } catch (IOException exception) {
2885         LOG.warn("Exception attempting to fetch wal coprocessor information for region " + region +
2886             "; skipping.");
2887         LOG.debug("Exception details for failure to fetch wal coprocessor information.", exception);
2888       }
2889     }
2890     coprocessors.addAll(rsHost.getCoprocessors());
2891     return coprocessors.toArray(new String[coprocessors.size()]);
2892   }
2893 
2894   @Override
2895   public List<Region> getOnlineRegions() {
2896     List<Region> allRegions = new ArrayList<Region>();
2897     synchronized (this.onlineRegions) {
2898       // Return a clone copy of the onlineRegions
2899       allRegions.addAll(onlineRegions.values());
2900     }
2901     return allRegions;
2902   }
2903   /**
2904    * Try to close the region, logs a warning on failure but continues.
2905    * @param region Region to close
2906    */
2907   private void closeRegionIgnoreErrors(HRegionInfo region, final boolean abort) {
2908     try {
2909       CloseRegionCoordination.CloseRegionDetails details =
2910         csm.getCloseRegionCoordination().getDetaultDetails();
2911       if (!closeRegion(region.getEncodedName(), abort, details, null)) {
2912         LOG.warn("Failed to close " + region.getRegionNameAsString() +
2913             " - ignoring and continuing");
2914       }
2915     } catch (IOException e) {
2916       LOG.warn("Failed to close " + region.getRegionNameAsString() +
2917           " - ignoring and continuing", e);
2918     }
2919   }
2920 
2921   /**
2922    * Close asynchronously a region, can be called from the master or internally by the regionserver
2923    * when stopping. If called from the master, the region will update the znode status.
2924    *
2925    * <p>
2926    * If an opening was in progress, this method will cancel it, but will not start a new close. The
2927    * coprocessors are not called in this case. A NotServingRegionException exception is thrown.
2928    * </p>
2929 
2930    * <p>
2931    *   If a close was in progress, this new request will be ignored, and an exception thrown.
2932    * </p>
2933    *
2934    * @param encodedName Region to close
2935    * @param abort True if we are aborting
2936    * @param crd details about closing region coordination-coordinated task
2937    * @return True if closed a region.
2938    * @throws NotServingRegionException if the region is not online
2939    * @throws RegionAlreadyInTransitionException if the region is already closing
2940    */
2941   protected boolean closeRegion(String encodedName, final boolean abort,
2942       CloseRegionCoordination.CloseRegionDetails crd, final ServerName sn)
2943       throws NotServingRegionException, RegionAlreadyInTransitionException {
2944     //Check for permissions to close.
2945     Region actualRegion = this.getFromOnlineRegions(encodedName);
2946     // Can be null if we're calling close on a region that's not online
2947     if ((actualRegion != null) && (actualRegion.getCoprocessorHost() != null)) {
2948       try {
2949         actualRegion.getCoprocessorHost().preClose(false);
2950       } catch (IOException exp) {
2951         LOG.warn("Unable to close region: the coprocessor launched an error ", exp);
2952         return false;
2953       }
2954     }
2955 
2956     final Boolean previous = this.regionsInTransitionInRS
2957       .putIfAbsent(Bytes.toBytes(encodedName), Boolean.FALSE);
2958 
2959     if (Boolean.TRUE.equals(previous)) {
2960       LOG.info("Received CLOSE for the region:" + encodedName + " , which we are already " +
2961           "trying to OPEN. Cancelling OPENING.");
2962       if (!regionsInTransitionInRS.replace(Bytes.toBytes(encodedName), previous, Boolean.FALSE)) {
2963         // The replace failed. That should be an exceptional case, but theoretically it can happen.
2964         // We're going to try to do a standard close then.
2965         LOG.warn("The opening for region " + encodedName + " was done before we could cancel it." +
2966             " Doing a standard close now");
2967         return closeRegion(encodedName, abort, crd, sn);
2968       }
2969       // Let's get the region from the online region list again
2970       actualRegion = this.getFromOnlineRegions(encodedName);
2971       if (actualRegion == null) { // If already online, we still need to close it.
2972         LOG.info("The opening previously in progress has been cancelled by a CLOSE request.");
2973         // The master deletes the znode when it receives this exception.
2974         throw new RegionAlreadyInTransitionException("The region " + encodedName +
2975           " was opening but not yet served. Opening is cancelled.");
2976       }
2977     } else if (Boolean.FALSE.equals(previous)) {
2978       LOG.info("Received CLOSE for the region: " + encodedName +
2979         ", which we are already trying to CLOSE, but not completed yet");
2980       // The master will retry till the region is closed. We need to do this since
2981       // the region could fail to close somehow. If we mark the region closed in master
2982       // while it is not, there could be data loss.
2983       // If the region stuck in closing for a while, and master runs out of retries,
2984       // master will move the region to failed_to_close. Later on, if the region
2985       // is indeed closed, master can properly re-assign it.
2986       throw new RegionAlreadyInTransitionException("The region " + encodedName +
2987         " was already closing. New CLOSE request is ignored.");
2988     }
2989 
2990     if (actualRegion == null) {
2991       LOG.error("Received CLOSE for a region which is not online, and we're not opening.");
2992       this.regionsInTransitionInRS.remove(Bytes.toBytes(encodedName));
2993       // The master deletes the znode when it receives this exception.
2994       throw new NotServingRegionException("The region " + encodedName +
2995           " is not online, and is not opening.");
2996     }
2997 
2998     CloseRegionHandler crh;
2999     final HRegionInfo hri = actualRegion.getRegionInfo();
3000     if (hri.isMetaRegion()) {
3001       crh = new CloseMetaHandler(this, this, hri, abort,
3002         csm.getCloseRegionCoordination(), crd);
3003     } else {
3004       crh = new CloseRegionHandler(this, this, hri, abort,
3005         csm.getCloseRegionCoordination(), crd, sn);
3006     }
3007     this.service.submit(crh);
3008     return true;
3009   }
3010 
3011    /**
3012    * @param regionName
3013    * @return HRegion for the passed binary <code>regionName</code> or null if
3014    *         named region is not member of the online regions.
3015    */
3016   public Region getOnlineRegion(final byte[] regionName) {
3017     String encodedRegionName = HRegionInfo.encodeRegionName(regionName);
3018     return this.onlineRegions.get(encodedRegionName);
3019   }
3020 
3021   public InetSocketAddress[] getRegionBlockLocations(final String encodedRegionName) {
3022     return this.regionFavoredNodesMap.get(encodedRegionName);
3023   }
3024 
3025   @Override
3026   public Region getFromOnlineRegions(final String encodedRegionName) {
3027     return this.onlineRegions.get(encodedRegionName);
3028   }
3029 
3030 
3031   @Override
3032   public boolean removeFromOnlineRegions(final Region r, ServerName destination) {
3033     Region toReturn = this.onlineRegions.remove(r.getRegionInfo().getEncodedName());
3034     if (destination != null) {
3035       long closeSeqNum = r.getMaxFlushedSeqId();
3036       if (closeSeqNum == HConstants.NO_SEQNUM) {
3037         // No edits in WAL for this region; get the sequence number when the region was opened.
3038         closeSeqNum = r.getOpenSeqNum();
3039         if (closeSeqNum == HConstants.NO_SEQNUM) closeSeqNum = 0;
3040       }
3041       addToMovedRegions(r.getRegionInfo().getEncodedName(), destination, closeSeqNum);
3042     }
3043     this.regionFavoredNodesMap.remove(r.getRegionInfo().getEncodedName());
3044     return toReturn != null;
3045   }
3046 
3047   /**
3048    * Protected utility method for safely obtaining an HRegion handle.
3049    *
3050    * @param regionName
3051    *          Name of online {@link Region} to return
3052    * @return {@link Region} for <code>regionName</code>
3053    * @throws NotServingRegionException
3054    */
3055   protected Region getRegion(final byte[] regionName)
3056       throws NotServingRegionException {
3057     String encodedRegionName = HRegionInfo.encodeRegionName(regionName);
3058     return getRegionByEncodedName(regionName, encodedRegionName);
3059   }
3060 
3061   public Region getRegionByEncodedName(String encodedRegionName)
3062       throws NotServingRegionException {
3063     return getRegionByEncodedName(null, encodedRegionName);
3064   }
3065 
3066   protected Region getRegionByEncodedName(byte[] regionName, String encodedRegionName)
3067     throws NotServingRegionException {
3068     Region region = this.onlineRegions.get(encodedRegionName);
3069     if (region == null) {
3070       MovedRegionInfo moveInfo = getMovedRegion(encodedRegionName);
3071       if (moveInfo != null) {
3072         throw new RegionMovedException(moveInfo.getServerName(), moveInfo.getSeqNum());
3073       }
3074       Boolean isOpening = this.regionsInTransitionInRS.get(Bytes.toBytes(encodedRegionName));
3075       String regionNameStr = regionName == null?
3076         encodedRegionName: Bytes.toStringBinary(regionName);
3077       if (isOpening != null && isOpening.booleanValue()) {
3078         throw new RegionOpeningException("Region " + regionNameStr +
3079           " is opening on " + this.serverName);
3080       }
3081       throw new NotServingRegionException("Region " + regionNameStr +
3082         " is not online on " + this.serverName);
3083     }
3084     return region;
3085   }
3086 
3087   /*
3088    * Cleanup after Throwable caught invoking method. Converts <code>t</code> to
3089    * IOE if it isn't already.
3090    *
3091    * @param t Throwable
3092    *
3093    * @param msg Message to log in error. Can be null.
3094    *
3095    * @return Throwable converted to an IOE; methods can only let out IOEs.
3096    */
3097   private Throwable cleanup(final Throwable t, final String msg) {
3098     // Don't log as error if NSRE; NSRE is 'normal' operation.
3099     if (t instanceof NotServingRegionException) {
3100       LOG.debug("NotServingRegionException; " + t.getMessage());
3101       return t;
3102     }
3103     if (msg == null) {
3104       LOG.error("", RemoteExceptionHandler.checkThrowable(t));
3105     } else {
3106       LOG.error(msg, RemoteExceptionHandler.checkThrowable(t));
3107     }
3108     if (!rpcServices.checkOOME(t)) {
3109       checkFileSystem();
3110     }
3111     return t;
3112   }
3113 
3114   /*
3115    * @param t
3116    *
3117    * @param msg Message to put in new IOE if passed <code>t</code> is not an IOE
3118    *
3119    * @return Make <code>t</code> an IOE if it isn't already.
3120    */
3121   protected IOException convertThrowableToIOE(final Throwable t, final String msg) {
3122     return (t instanceof IOException ? (IOException) t : msg == null
3123         || msg.length() == 0 ? new IOException(t) : new IOException(msg, t));
3124   }
3125 
3126   /**
3127    * Checks to see if the file system is still accessible. If not, sets
3128    * abortRequested and stopRequested
3129    *
3130    * @return false if file system is not available
3131    */
3132   public boolean checkFileSystem() {
3133     if (this.fsOk && this.fs != null) {
3134       try {
3135         FSUtils.checkFileSystemAvailable(this.fs);
3136       } catch (IOException e) {
3137         abort("File System not available", e);
3138         this.fsOk = false;
3139       }
3140     }
3141     return this.fsOk;
3142   }
3143 
3144   @Override
3145   public void updateRegionFavoredNodesMapping(String encodedRegionName,
3146       List<org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.ServerName> favoredNodes) {
3147     InetSocketAddress[] addr = new InetSocketAddress[favoredNodes.size()];
3148     // Refer to the comment on the declaration of regionFavoredNodesMap on why
3149     // it is a map of region name to InetSocketAddress[]
3150     for (int i = 0; i < favoredNodes.size(); i++) {
3151       addr[i] = InetSocketAddress.createUnresolved(favoredNodes.get(i).getHostName(),
3152           favoredNodes.get(i).getPort());
3153     }
3154     regionFavoredNodesMap.put(encodedRegionName, addr);
3155   }
3156 
3157   /**
3158    * Return the favored nodes for a region given its encoded name. Look at the
3159    * comment around {@link #regionFavoredNodesMap} on why it is InetSocketAddress[]
3160    * @param encodedRegionName
3161    * @return array of favored locations
3162    */
3163   @Override
3164   public InetSocketAddress[] getFavoredNodesForRegion(String encodedRegionName) {
3165     return regionFavoredNodesMap.get(encodedRegionName);
3166   }
3167 
3168   @Override
3169   public ServerNonceManager getNonceManager() {
3170     return this.nonceManager;
3171   }
3172 
3173   private static class MovedRegionInfo {
3174     private final ServerName serverName;
3175     private final long seqNum;
3176     private final long ts;
3177 
3178     public MovedRegionInfo(ServerName serverName, long closeSeqNum) {
3179       this.serverName = serverName;
3180       this.seqNum = closeSeqNum;
3181       ts = EnvironmentEdgeManager.currentTime();
3182      }
3183 
3184     public ServerName getServerName() {
3185       return serverName;
3186     }
3187 
3188     public long getSeqNum() {
3189       return seqNum;
3190     }
3191 
3192     public long getMoveTime() {
3193       return ts;
3194     }
3195   }
3196 
3197   // This map will contains all the regions that we closed for a move.
3198   //  We add the time it was moved as we don't want to keep too old information
3199   protected Map<String, MovedRegionInfo> movedRegions =
3200       new ConcurrentHashMap<String, MovedRegionInfo>(3000);
3201 
3202   // We need a timeout. If not there is a risk of giving a wrong information: this would double
3203   //  the number of network calls instead of reducing them.
3204   private static final int TIMEOUT_REGION_MOVED = (2 * 60 * 1000);
3205 
3206   protected void addToMovedRegions(String encodedName, ServerName destination, long closeSeqNum) {
3207     if (ServerName.isSameHostnameAndPort(destination, this.getServerName())) {
3208       LOG.warn("Not adding moved region record: " + encodedName + " to self.");
3209       return;
3210     }
3211     LOG.info("Adding moved region record: "
3212       + encodedName + " to " + destination + " as of " + closeSeqNum);
3213     movedRegions.put(encodedName, new MovedRegionInfo(destination, closeSeqNum));
3214   }
3215 
3216   void removeFromMovedRegions(String encodedName) {
3217     movedRegions.remove(encodedName);
3218   }
3219 
3220   private MovedRegionInfo getMovedRegion(final String encodedRegionName) {
3221     MovedRegionInfo dest = movedRegions.get(encodedRegionName);
3222 
3223     long now = EnvironmentEdgeManager.currentTime();
3224     if (dest != null) {
3225       if (dest.getMoveTime() > (now - TIMEOUT_REGION_MOVED)) {
3226         return dest;
3227       } else {
3228         movedRegions.remove(encodedRegionName);
3229       }
3230     }
3231 
3232     return null;
3233   }
3234 
3235   /**
3236    * Remove the expired entries from the moved regions list.
3237    */
3238   protected void cleanMovedRegions() {
3239     final long cutOff = System.currentTimeMillis() - TIMEOUT_REGION_MOVED;
3240     Iterator<Entry<String, MovedRegionInfo>> it = movedRegions.entrySet().iterator();
3241 
3242     while (it.hasNext()){
3243       Map.Entry<String, MovedRegionInfo> e = it.next();
3244       if (e.getValue().getMoveTime() < cutOff) {
3245         it.remove();
3246       }
3247     }
3248   }
3249 
3250   /*
3251    * Use this to allow tests to override and schedule more frequently.
3252    */
3253 
3254   protected int movedRegionCleanerPeriod() {
3255         return TIMEOUT_REGION_MOVED;
3256   }
3257 
3258   /**
3259    * Creates a Chore thread to clean the moved region cache.
3260    */
3261 
3262   protected final static class MovedRegionsCleaner extends ScheduledChore implements Stoppable {
3263     private HRegionServer regionServer;
3264     Stoppable stoppable;
3265 
3266     private MovedRegionsCleaner(
3267       HRegionServer regionServer, Stoppable stoppable){
3268       super("MovedRegionsCleaner for region " + regionServer, stoppable,
3269           regionServer.movedRegionCleanerPeriod());
3270       this.regionServer = regionServer;
3271       this.stoppable = stoppable;
3272     }
3273 
3274     static MovedRegionsCleaner create(HRegionServer rs){
3275       Stoppable stoppable = new Stoppable() {
3276         private volatile boolean isStopped = false;
3277         @Override public void stop(String why) { isStopped = true;}
3278         @Override public boolean isStopped() {return isStopped;}
3279       };
3280 
3281       return new MovedRegionsCleaner(rs, stoppable);
3282     }
3283 
3284     @Override
3285     protected void chore() {
3286       regionServer.cleanMovedRegions();
3287     }
3288 
3289     @Override
3290     public void stop(String why) {
3291       stoppable.stop(why);
3292     }
3293 
3294     @Override
3295     public boolean isStopped() {
3296       return stoppable.isStopped();
3297     }
3298   }
3299 
3300   private String getMyEphemeralNodePath() {
3301     return ZKUtil.joinZNode(this.zooKeeper.rsZNode, getServerName().toString());
3302   }
3303 
3304   private boolean isHealthCheckerConfigured() {
3305     String healthScriptLocation = this.conf.get(HConstants.HEALTH_SCRIPT_LOC);
3306     return org.apache.commons.lang.StringUtils.isNotBlank(healthScriptLocation);
3307   }
3308 
3309   /**
3310    * @return the underlying {@link CompactSplitThread} for the servers
3311    */
3312   public CompactSplitThread getCompactSplitThread() {
3313     return this.compactSplitThread;
3314   }
3315 
3316   /**
3317    * A helper function to store the last flushed sequence Id with the previous failed RS for a
3318    * recovering region. The Id is used to skip wal edits which are flushed. Since the flushed
3319    * sequence id is only valid for each RS, we associate the Id with corresponding failed RS.
3320    * @throws KeeperException
3321    * @throws IOException
3322    */
3323   private void updateRecoveringRegionLastFlushedSequenceId(Region r) throws KeeperException,
3324       IOException {
3325     if (!r.isRecovering()) {
3326       // return immdiately for non-recovering regions
3327       return;
3328     }
3329 
3330     HRegionInfo regionInfo = r.getRegionInfo();
3331     ZooKeeperWatcher zkw = getZooKeeper();
3332     String previousRSName = this.getLastFailedRSFromZK(regionInfo.getEncodedName());
3333     Map<byte[], Long> maxSeqIdInStores = r.getMaxStoreSeqId();
3334     long minSeqIdForLogReplay = -1;
3335     for (Long storeSeqIdForReplay : maxSeqIdInStores.values()) {
3336       if (minSeqIdForLogReplay == -1 || storeSeqIdForReplay < minSeqIdForLogReplay) {
3337         minSeqIdForLogReplay = storeSeqIdForReplay;
3338       }
3339     }
3340 
3341     try {
3342       long lastRecordedFlushedSequenceId = -1;
3343       String nodePath = ZKUtil.joinZNode(this.zooKeeper.recoveringRegionsZNode,
3344         regionInfo.getEncodedName());
3345       // recovering-region level
3346       byte[] data;
3347       try {
3348         data = ZKUtil.getData(zkw, nodePath);
3349       } catch (InterruptedException e) {
3350         throw new InterruptedIOException();
3351       }
3352       if (data != null) {
3353         lastRecordedFlushedSequenceId = ZKSplitLog.parseLastFlushedSequenceIdFrom(data);
3354       }
3355       if (data == null || lastRecordedFlushedSequenceId < minSeqIdForLogReplay) {
3356         ZKUtil.setData(zkw, nodePath, ZKUtil.positionToByteArray(minSeqIdForLogReplay));
3357       }
3358       if (previousRSName != null) {
3359         // one level deeper for the failed RS
3360         nodePath = ZKUtil.joinZNode(nodePath, previousRSName);
3361         ZKUtil.setData(zkw, nodePath,
3362           ZKUtil.regionSequenceIdsToByteArray(minSeqIdForLogReplay, maxSeqIdInStores));
3363         LOG.debug("Update last flushed sequence id of region " + regionInfo.getEncodedName() +
3364           " for " + previousRSName);
3365       } else {
3366         LOG.warn("Can't find failed region server for recovering region " +
3367             regionInfo.getEncodedName());
3368       }
3369     } catch (NoNodeException ignore) {
3370       LOG.debug("Region " + regionInfo.getEncodedName() +
3371         " must have completed recovery because its recovery znode has been removed", ignore);
3372     }
3373   }
3374 
3375   /**
3376    * Return the last failed RS name under /hbase/recovering-regions/encodedRegionName
3377    * @param encodedRegionName
3378    * @throws KeeperException
3379    */
3380   private String getLastFailedRSFromZK(String encodedRegionName) throws KeeperException {
3381     String result = null;
3382     long maxZxid = 0;
3383     ZooKeeperWatcher zkw = this.getZooKeeper();
3384     String nodePath = ZKUtil.joinZNode(zkw.recoveringRegionsZNode, encodedRegionName);
3385     List<String> failedServers = ZKUtil.listChildrenNoWatch(zkw, nodePath);
3386     if (failedServers == null || failedServers.isEmpty()) {
3387       return result;
3388     }
3389     for (String failedServer : failedServers) {
3390       String rsPath = ZKUtil.joinZNode(nodePath, failedServer);
3391       Stat stat = new Stat();
3392       ZKUtil.getDataNoWatch(zkw, rsPath, stat);
3393       if (maxZxid < stat.getCzxid()) {
3394         maxZxid = stat.getCzxid();
3395         result = failedServer;
3396       }
3397     }
3398     return result;
3399   }
3400 
3401   public CoprocessorServiceResponse execRegionServerService(
3402       @SuppressWarnings("UnusedParameters") final RpcController controller,
3403       final CoprocessorServiceRequest serviceRequest) throws ServiceException {
3404     try {
3405       ServerRpcController serviceController = new ServerRpcController();
3406       CoprocessorServiceCall call = serviceRequest.getCall();
3407       String serviceName = call.getServiceName();
3408       String methodName = call.getMethodName();
3409       if (!coprocessorServiceHandlers.containsKey(serviceName)) {
3410         throw new UnknownProtocolException(null,
3411             "No registered coprocessor service found for name " + serviceName);
3412       }
3413       Service service = coprocessorServiceHandlers.get(serviceName);
3414       Descriptors.ServiceDescriptor serviceDesc = service.getDescriptorForType();
3415       Descriptors.MethodDescriptor methodDesc = serviceDesc.findMethodByName(methodName);
3416       if (methodDesc == null) {
3417         throw new UnknownProtocolException(service.getClass(), "Unknown method " + methodName
3418             + " called on service " + serviceName);
3419       }
3420       Message.Builder builderForType = service.getRequestPrototype(methodDesc).newBuilderForType();
3421       ProtobufUtil.mergeFrom(builderForType, call.getRequest());
3422       Message request = builderForType.build();
3423       final Message.Builder responseBuilder =
3424           service.getResponsePrototype(methodDesc).newBuilderForType();
3425       service.callMethod(methodDesc, serviceController, request, new RpcCallback<Message>() {
3426         @Override
3427         public void run(Message message) {
3428           if (message != null) {
3429             responseBuilder.mergeFrom(message);
3430           }
3431         }
3432       });
3433       IOException exception = ResponseConverter.getControllerException(serviceController);
3434       if (exception != null) {
3435         throw exception;
3436       }
3437       Message execResult = responseBuilder.build();
3438       ClientProtos.CoprocessorServiceResponse.Builder builder =
3439           ClientProtos.CoprocessorServiceResponse.newBuilder();
3440       builder.setRegion(RequestConverter.buildRegionSpecifier(RegionSpecifierType.REGION_NAME,
3441         HConstants.EMPTY_BYTE_ARRAY));
3442       builder.setValue(builder.getValueBuilder().setName(execResult.getClass().getName())
3443           .setValue(execResult.toByteString()));
3444       return builder.build();
3445     } catch (IOException ie) {
3446       throw new ServiceException(ie);
3447     }
3448   }
3449 
3450   /**
3451    * @return The cache config instance used by the regionserver.
3452    */
3453   public CacheConfig getCacheConfig() {
3454     return this.cacheConfig;
3455   }
3456 
3457   /**
3458    * @return : Returns the ConfigurationManager object for testing purposes.
3459    */
3460   protected ConfigurationManager getConfigurationManager() {
3461     return configurationManager;
3462   }
3463 
3464   /**
3465    * @return Return table descriptors implementation.
3466    */
3467   public TableDescriptors getTableDescriptors() {
3468     return this.tableDescriptors;
3469   }
3470 
3471   /**
3472    * Reload the configuration from disk.
3473    */
3474   public void updateConfiguration() {
3475     LOG.info("Reloading the configuration from disk.");
3476     // Reload the configuration from disk.
3477     conf.reloadConfiguration();
3478     configurationManager.notifyAllObservers(conf);
3479   }
3480 
3481   @Override
3482   public HeapMemoryManager getHeapMemoryManager() {
3483     return hMemManager;
3484   }
3485 
3486   @Override
3487   public double getCompactionPressure() {
3488     double max = 0;
3489     for (Region region : onlineRegions.values()) {
3490       for (Store store : region.getStores()) {
3491         double normCount = store.getCompactionPressure();
3492         if (normCount > max) {
3493           max = normCount;
3494         }
3495       }
3496     }
3497     return max;
3498   }
3499 
3500   /**
3501    * For testing
3502    * @return whether all wal roll request finished for this regionserver
3503    */
3504   @VisibleForTesting
3505   public boolean walRollRequestFinished() {
3506     return this.walRoller.walRollFinished();
3507   }
3508 
3509   @Override
3510   public ThroughputController getFlushThroughputController() {
3511     return flushThroughputController;
3512   }
3513 
3514   @Override
3515   public double getFlushPressure() {
3516     if (getRegionServerAccounting() == null || cacheFlusher == null) {
3517       // return 0 during RS initialization
3518       return 0.0;
3519     }
3520     return getRegionServerAccounting().getGlobalMemstoreSize() * 1.0
3521         / cacheFlusher.globalMemStoreLimitLowMark;
3522   }
3523 
3524   @Override
3525   public void onConfigurationChange(Configuration newConf) {
3526     ThroughputController old = this.flushThroughputController;
3527     if (old != null) {
3528       old.stop("configuration change");
3529     }
3530     this.flushThroughputController = FlushThroughputControllerFactory.create(this, newConf);
3531   }
3532 
3533   @Override
3534   public MetricsRegionServer getMetrics() {
3535     return metricsRegionServer;
3536   }
3537 
3538   @Override
3539   public void unassign(byte[] regionName) throws IOException {
3540     clusterConnection.getAdmin().unassign(regionName, false);
3541   }
3542 }