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