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