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