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