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