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