1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.hadoop.hbase.master;
20
21 import java.io.IOException;
22 import java.net.InetAddress;
23 import java.util.ArrayList;
24 import java.util.Collections;
25 import java.util.HashMap;
26 import java.util.HashSet;
27 import java.util.Iterator;
28 import java.util.List;
29 import java.util.Map;
30 import java.util.Map.Entry;
31 import java.util.Set;
32 import java.util.concurrent.ConcurrentHashMap;
33 import java.util.concurrent.ConcurrentNavigableMap;
34 import java.util.concurrent.ConcurrentSkipListMap;
35 import java.util.concurrent.CopyOnWriteArrayList;
36
37 import org.apache.commons.logging.Log;
38 import org.apache.commons.logging.LogFactory;
39 import org.apache.hadoop.conf.Configuration;
40 import org.apache.hadoop.hbase.ClockOutOfSyncException;
41 import org.apache.hadoop.hbase.HConstants;
42 import org.apache.hadoop.hbase.HRegionInfo;
43 import org.apache.hadoop.hbase.NotServingRegionException;
44 import org.apache.hadoop.hbase.RegionLoad;
45 import org.apache.hadoop.hbase.Server;
46 import org.apache.hadoop.hbase.ServerLoad;
47 import org.apache.hadoop.hbase.ServerName;
48 import org.apache.hadoop.hbase.YouAreDeadException;
49 import org.apache.hadoop.hbase.ZooKeeperConnectionException;
50 import org.apache.hadoop.hbase.classification.InterfaceAudience;
51 import org.apache.hadoop.hbase.client.ClusterConnection;
52 import org.apache.hadoop.hbase.client.ConnectionFactory;
53 import org.apache.hadoop.hbase.ipc.ServerNotRunningYetException;
54 import org.apache.hadoop.hbase.client.RetriesExhaustedException;
55 import org.apache.hadoop.hbase.master.balancer.BaseLoadBalancer;
56 import org.apache.hadoop.hbase.master.handler.MetaServerShutdownHandler;
57 import org.apache.hadoop.hbase.master.handler.ServerShutdownHandler;
58 import org.apache.hadoop.hbase.monitoring.MonitoredTask;
59 import org.apache.hadoop.hbase.protobuf.ProtobufUtil;
60 import org.apache.hadoop.hbase.protobuf.RequestConverter;
61 import org.apache.hadoop.hbase.protobuf.ResponseConverter;
62 import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.AdminService;
63 import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.OpenRegionRequest;
64 import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.OpenRegionResponse;
65 import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.ServerInfo;
66 import org.apache.hadoop.hbase.protobuf.generated.RegionServerStatusProtos.RegionServerStartupRequest;
67 import org.apache.hadoop.hbase.protobuf.generated.ClusterStatusProtos.RegionStoreSequenceIds;
68 import org.apache.hadoop.hbase.protobuf.generated.ClusterStatusProtos.StoreSequenceId;
69 import org.apache.hadoop.hbase.protobuf.generated.ZooKeeperProtos.SplitLogTask.RecoveryMode;
70 import org.apache.hadoop.hbase.regionserver.HRegionServer;
71 import org.apache.hadoop.hbase.regionserver.RegionOpeningState;
72 import org.apache.hadoop.hbase.regionserver.RegionServerStoppedException;
73 import org.apache.hadoop.hbase.util.Bytes;
74 import org.apache.hadoop.hbase.util.Triple;
75 import org.apache.hadoop.hbase.util.RetryCounter;
76 import org.apache.hadoop.hbase.util.RetryCounterFactory;
77 import org.apache.hadoop.hbase.zookeeper.ZKUtil;
78 import org.apache.hadoop.hbase.zookeeper.ZooKeeperWatcher;
79 import org.apache.zookeeper.KeeperException;
80
81 import com.google.common.annotations.VisibleForTesting;
82 import com.google.protobuf.ByteString;
83 import com.google.protobuf.ServiceException;
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107 @InterfaceAudience.Private
108 public class ServerManager {
109 public static final String WAIT_ON_REGIONSERVERS_MAXTOSTART =
110 "hbase.master.wait.on.regionservers.maxtostart";
111
112 public static final String WAIT_ON_REGIONSERVERS_MINTOSTART =
113 "hbase.master.wait.on.regionservers.mintostart";
114
115 public static final String WAIT_ON_REGIONSERVERS_TIMEOUT =
116 "hbase.master.wait.on.regionservers.timeout";
117
118 public static final String WAIT_ON_REGIONSERVERS_INTERVAL =
119 "hbase.master.wait.on.regionservers.interval";
120
121 private static final Log LOG = LogFactory.getLog(ServerManager.class);
122
123
124 private volatile boolean clusterShutdown = false;
125
126 private final ConcurrentNavigableMap<byte[], Long> flushedSequenceIdByRegion =
127 new ConcurrentSkipListMap<byte[], Long>(Bytes.BYTES_COMPARATOR);
128
129 private final ConcurrentNavigableMap<byte[], ConcurrentNavigableMap<byte[], Long>>
130 storeFlushedSequenceIdsByRegion =
131 new ConcurrentSkipListMap<byte[], ConcurrentNavigableMap<byte[], Long>>(Bytes.BYTES_COMPARATOR);
132
133
134 private final ConcurrentHashMap<ServerName, ServerLoad> onlineServers =
135 new ConcurrentHashMap<ServerName, ServerLoad>();
136
137
138
139
140
141 private final Map<ServerName, AdminService.BlockingInterface> rsAdmins =
142 new HashMap<ServerName, AdminService.BlockingInterface>();
143
144
145
146
147
148 private final ArrayList<ServerName> drainingServers =
149 new ArrayList<ServerName>();
150
151 private final Server master;
152 private final MasterServices services;
153 private final ClusterConnection connection;
154
155 private final DeadServer deadservers = new DeadServer();
156
157 private final long maxSkew;
158 private final long warningSkew;
159
160 private final RetryCounterFactory pingRetryCounterFactory;
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178 private Set<ServerName> queuedDeadServers = new HashSet<ServerName>();
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195 private Map<ServerName, Boolean> requeuedDeadServers
196 = new ConcurrentHashMap<ServerName, Boolean>();
197
198
199 private List<ServerListener> listeners = new CopyOnWriteArrayList<ServerListener>();
200
201
202
203
204
205
206
207 public ServerManager(final Server master, final MasterServices services)
208 throws IOException {
209 this(master, services, true);
210 }
211
212 ServerManager(final Server master, final MasterServices services,
213 final boolean connect) throws IOException {
214 this.master = master;
215 this.services = services;
216 Configuration c = master.getConfiguration();
217 maxSkew = c.getLong("hbase.master.maxclockskew", 30000);
218 warningSkew = c.getLong("hbase.master.warningclockskew", 10000);
219 this.connection = connect ? (ClusterConnection)ConnectionFactory.createConnection(c) : null;
220 int pingMaxAttempts = Math.max(1, master.getConfiguration().getInt(
221 "hbase.master.maximum.ping.server.attempts", 10));
222 int pingSleepInterval = Math.max(1, master.getConfiguration().getInt(
223 "hbase.master.ping.server.retry.sleep.interval", 100));
224 this.pingRetryCounterFactory = new RetryCounterFactory(pingMaxAttempts, pingSleepInterval);
225 }
226
227
228
229
230
231 public void registerListener(final ServerListener listener) {
232 this.listeners.add(listener);
233 }
234
235
236
237
238
239 public boolean unregisterListener(final ServerListener listener) {
240 return this.listeners.remove(listener);
241 }
242
243
244
245
246
247
248
249
250 ServerName regionServerStartup(RegionServerStartupRequest request, InetAddress ia)
251 throws IOException {
252
253
254
255
256
257
258
259
260 final String hostname = request.hasUseThisHostnameInstead() ?
261 request.getUseThisHostnameInstead() :ia.getHostName();
262 ServerName sn = ServerName.valueOf(hostname, request.getPort(),
263 request.getServerStartCode());
264 checkClockSkew(sn, request.getServerCurrentTime());
265 checkIsDead(sn, "STARTUP");
266 if (!checkAndRecordNewServer(sn, ServerLoad.EMPTY_SERVERLOAD)) {
267 LOG.warn("THIS SHOULD NOT HAPPEN, RegionServerStartup"
268 + " could not record the server: " + sn);
269 }
270 return sn;
271 }
272
273 private ConcurrentNavigableMap<byte[], Long> getOrCreateStoreFlushedSequenceId(
274 byte[] regionName) {
275 ConcurrentNavigableMap<byte[], Long> storeFlushedSequenceId =
276 storeFlushedSequenceIdsByRegion.get(regionName);
277 if (storeFlushedSequenceId != null) {
278 return storeFlushedSequenceId;
279 }
280 storeFlushedSequenceId = new ConcurrentSkipListMap<byte[], Long>(Bytes.BYTES_COMPARATOR);
281 ConcurrentNavigableMap<byte[], Long> alreadyPut =
282 storeFlushedSequenceIdsByRegion.putIfAbsent(regionName, storeFlushedSequenceId);
283 return alreadyPut == null ? storeFlushedSequenceId : alreadyPut;
284 }
285
286
287
288
289
290 private void updateLastFlushedSequenceIds(ServerName sn, ServerLoad hsl) {
291 Map<byte[], RegionLoad> regionsLoad = hsl.getRegionsLoad();
292 for (Entry<byte[], RegionLoad> entry : regionsLoad.entrySet()) {
293 byte[] encodedRegionName = Bytes.toBytes(HRegionInfo.encodeRegionName(entry.getKey()));
294 Long existingValue = flushedSequenceIdByRegion.get(encodedRegionName);
295 long l = entry.getValue().getCompleteSequenceId();
296
297 if (existingValue == null || (l != HConstants.NO_SEQNUM && l > existingValue)) {
298 flushedSequenceIdByRegion.put(encodedRegionName, l);
299 } else if (l != HConstants.NO_SEQNUM && l < existingValue) {
300 LOG.warn("RegionServer " + sn + " indicates a last flushed sequence id ("
301 + l + ") that is less than the previous last flushed sequence id ("
302 + existingValue + ") for region " + Bytes.toString(entry.getKey()) + " Ignoring.");
303 }
304 ConcurrentNavigableMap<byte[], Long> storeFlushedSequenceId =
305 getOrCreateStoreFlushedSequenceId(encodedRegionName);
306 for (StoreSequenceId storeSeqId : entry.getValue().getStoreCompleteSequenceId()) {
307 byte[] family = storeSeqId.getFamilyName().toByteArray();
308 existingValue = storeFlushedSequenceId.get(family);
309 l = storeSeqId.getSequenceId();
310
311 if (existingValue == null || (l != HConstants.NO_SEQNUM && l > existingValue.longValue())) {
312 storeFlushedSequenceId.put(family, l);
313 }
314 }
315 }
316 }
317
318 void regionServerReport(ServerName sn,
319 ServerLoad sl) throws YouAreDeadException {
320 checkIsDead(sn, "REPORT");
321 if (null == this.onlineServers.replace(sn, sl)) {
322
323
324
325
326
327
328 if (!checkAndRecordNewServer(sn, sl)) {
329 LOG.info("RegionServerReport ignored, could not record the server: " + sn);
330 return;
331 }
332 }
333 updateLastFlushedSequenceIds(sn, sl);
334 }
335
336
337
338
339
340
341
342
343
344 boolean checkAndRecordNewServer(
345 final ServerName serverName, final ServerLoad sl) {
346 ServerName existingServer = null;
347 synchronized (this.onlineServers) {
348 existingServer = findServerWithSameHostnamePortWithLock(serverName);
349 if (existingServer != null && (existingServer.getStartcode() > serverName.getStartcode())) {
350 LOG.info("Server serverName=" + serverName + " rejected; we already have "
351 + existingServer.toString() + " registered with same hostname and port");
352 return false;
353 }
354 recordNewServerWithLock(serverName, sl);
355 }
356
357
358 if (!this.listeners.isEmpty()) {
359 for (ServerListener listener : this.listeners) {
360 listener.serverAdded(serverName);
361 }
362 }
363
364
365
366 if (existingServer != null && (existingServer.getStartcode() < serverName.getStartcode())) {
367 LOG.info("Triggering server recovery; existingServer " +
368 existingServer + " looks stale, new server:" + serverName);
369 expireServer(existingServer);
370 }
371 return true;
372 }
373
374
375
376
377
378
379
380
381
382 private void checkClockSkew(final ServerName serverName, final long serverCurrentTime)
383 throws ClockOutOfSyncException {
384 long skew = Math.abs(System.currentTimeMillis() - serverCurrentTime);
385 if (skew > maxSkew) {
386 String message = "Server " + serverName + " has been " +
387 "rejected; Reported time is too far out of sync with master. " +
388 "Time difference of " + skew + "ms > max allowed of " + maxSkew + "ms";
389 LOG.warn(message);
390 throw new ClockOutOfSyncException(message);
391 } else if (skew > warningSkew){
392 String message = "Reported time for server " + serverName + " is out of sync with master " +
393 "by " + skew + "ms. (Warning threshold is " + warningSkew + "ms; " +
394 "error threshold is " + maxSkew + "ms)";
395 LOG.warn(message);
396 }
397 }
398
399
400
401
402
403
404
405
406
407 private void checkIsDead(final ServerName serverName, final String what)
408 throws YouAreDeadException {
409 if (this.deadservers.isDeadServer(serverName)) {
410
411
412 String message = "Server " + what + " rejected; currently processing " +
413 serverName + " as dead server";
414 LOG.debug(message);
415 throw new YouAreDeadException(message);
416 }
417
418
419 if ((this.services == null || ((HMaster) this.services).isInitialized())
420 && this.deadservers.cleanPreviousInstance(serverName)) {
421
422
423 LOG.debug(what + ":" + " Server " + serverName + " came back up," +
424 " removed it from the dead servers list");
425 }
426 }
427
428
429
430
431
432 private ServerName findServerWithSameHostnamePortWithLock(
433 final ServerName serverName) {
434 for (ServerName sn: this.onlineServers.keySet()) {
435 if (ServerName.isSameHostnameAndPort(serverName, sn)) return sn;
436 }
437 return null;
438 }
439
440
441
442
443
444
445
446 @VisibleForTesting
447 void recordNewServerWithLock(final ServerName serverName, final ServerLoad sl) {
448 LOG.info("Registering server=" + serverName);
449 this.onlineServers.put(serverName, sl);
450 this.rsAdmins.remove(serverName);
451 }
452
453 public RegionStoreSequenceIds getLastFlushedSequenceId(byte[] encodedRegionName) {
454 RegionStoreSequenceIds.Builder builder = RegionStoreSequenceIds.newBuilder();
455 Long seqId = flushedSequenceIdByRegion.get(encodedRegionName);
456 builder.setLastFlushedSequenceId(seqId != null ? seqId.longValue() : HConstants.NO_SEQNUM);
457 Map<byte[], Long> storeFlushedSequenceId =
458 storeFlushedSequenceIdsByRegion.get(encodedRegionName);
459 if (storeFlushedSequenceId != null) {
460 for (Map.Entry<byte[], Long> entry : storeFlushedSequenceId.entrySet()) {
461 builder.addStoreSequenceId(StoreSequenceId.newBuilder()
462 .setFamilyName(ByteString.copyFrom(entry.getKey()))
463 .setSequenceId(entry.getValue().longValue()).build());
464 }
465 }
466 return builder.build();
467 }
468
469
470
471
472
473 public ServerLoad getLoad(final ServerName serverName) {
474 return this.onlineServers.get(serverName);
475 }
476
477
478
479
480
481
482
483 public double getAverageLoad() {
484 int totalLoad = 0;
485 int numServers = 0;
486 for (ServerLoad sl: this.onlineServers.values()) {
487 numServers++;
488 totalLoad += sl.getNumberOfRegions();
489 }
490 return numServers == 0 ? 0 :
491 (double)totalLoad / (double)numServers;
492 }
493
494
495 public int countOfRegionServers() {
496
497 return this.onlineServers.size();
498 }
499
500
501
502
503 public Map<ServerName, ServerLoad> getOnlineServers() {
504
505 synchronized (this.onlineServers) {
506 return Collections.unmodifiableMap(this.onlineServers);
507 }
508 }
509
510
511 public DeadServer getDeadServers() {
512 return this.deadservers;
513 }
514
515
516
517
518
519 public boolean areDeadServersInProgress() {
520 return this.deadservers.areDeadServersInProgress();
521 }
522
523 void letRegionServersShutdown() {
524 long previousLogTime = 0;
525 ServerName sn = master.getServerName();
526 ZooKeeperWatcher zkw = master.getZooKeeper();
527 int onlineServersCt;
528 while ((onlineServersCt = onlineServers.size()) > 0){
529
530 if (System.currentTimeMillis() > (previousLogTime + 1000)) {
531 Set<ServerName> remainingServers = onlineServers.keySet();
532 synchronized (onlineServers) {
533 if (remainingServers.size() == 1 && remainingServers.contains(sn)) {
534
535 return;
536 }
537 }
538 StringBuilder sb = new StringBuilder();
539
540 for (ServerName key : remainingServers) {
541 if (sb.length() > 0) {
542 sb.append(", ");
543 }
544 sb.append(key);
545 }
546 LOG.info("Waiting on regionserver(s) to go down " + sb.toString());
547 previousLogTime = System.currentTimeMillis();
548 }
549
550 try {
551 List<String> servers = ZKUtil.listChildrenNoWatch(zkw, zkw.rsZNode);
552 if (servers == null || servers.size() == 0 || (servers.size() == 1
553 && servers.contains(sn.toString()))) {
554 LOG.info("ZK shows there is only the master self online, exiting now");
555
556 break;
557 }
558 } catch (KeeperException ke) {
559 LOG.warn("Failed to list regionservers", ke);
560
561 break;
562 }
563 synchronized (onlineServers) {
564 try {
565 if (onlineServersCt == onlineServers.size()) onlineServers.wait(100);
566 } catch (InterruptedException ignored) {
567
568 }
569 }
570 }
571 }
572
573
574
575
576
577 public synchronized void expireServer(final ServerName serverName) {
578 if (serverName.equals(master.getServerName())) {
579 if (!(master.isAborted() || master.isStopped())) {
580 master.stop("We lost our znode?");
581 }
582 return;
583 }
584 if (!services.isServerShutdownHandlerEnabled()) {
585 LOG.info("Master doesn't enable ServerShutdownHandler during initialization, "
586 + "delay expiring server " + serverName);
587 this.queuedDeadServers.add(serverName);
588 return;
589 }
590 if (this.deadservers.isDeadServer(serverName)) {
591
592 LOG.warn("Expiration of " + serverName +
593 " but server shutdown already in progress");
594 return;
595 }
596 synchronized (onlineServers) {
597 if (!this.onlineServers.containsKey(serverName)) {
598 LOG.warn("Expiration of " + serverName + " but server not online");
599 }
600
601
602
603 this.deadservers.add(serverName);
604 this.onlineServers.remove(serverName);
605 onlineServers.notifyAll();
606 }
607 this.rsAdmins.remove(serverName);
608
609
610 if (this.clusterShutdown) {
611 LOG.info("Cluster shutdown set; " + serverName +
612 " expired; onlineServers=" + this.onlineServers.size());
613 if (this.onlineServers.isEmpty()) {
614 master.stop("Cluster shutdown set; onlineServer=0");
615 }
616 return;
617 }
618
619 boolean carryingMeta = services.getAssignmentManager().isCarryingMeta(serverName);
620 if (carryingMeta) {
621 this.services.getExecutorService().submit(new MetaServerShutdownHandler(this.master,
622 this.services, this.deadservers, serverName));
623 } else {
624 this.services.getExecutorService().submit(new ServerShutdownHandler(this.master,
625 this.services, this.deadservers, serverName, true));
626 }
627 LOG.debug("Added=" + serverName +
628 " to dead servers, submitted shutdown handler to be executed meta=" + carryingMeta);
629
630
631 if (!this.listeners.isEmpty()) {
632 for (ServerListener listener : this.listeners) {
633 listener.serverRemoved(serverName);
634 }
635 }
636 }
637
638 public synchronized void processDeadServer(final ServerName serverName) {
639 this.processDeadServer(serverName, false);
640 }
641
642 public synchronized void processDeadServer(final ServerName serverName, boolean shouldSplitWal) {
643
644
645
646
647
648
649
650
651 if (!services.getAssignmentManager().isFailoverCleanupDone()) {
652 requeuedDeadServers.put(serverName, shouldSplitWal);
653 return;
654 }
655
656 this.deadservers.add(serverName);
657 this.services.getExecutorService().submit(
658 new ServerShutdownHandler(this.master, this.services, this.deadservers, serverName,
659 shouldSplitWal));
660 }
661
662
663
664
665
666 synchronized void processQueuedDeadServers() {
667 if (!services.isServerShutdownHandlerEnabled()) {
668 LOG.info("Master hasn't enabled ServerShutdownHandler");
669 }
670 Iterator<ServerName> serverIterator = queuedDeadServers.iterator();
671 while (serverIterator.hasNext()) {
672 ServerName tmpServerName = serverIterator.next();
673 expireServer(tmpServerName);
674 serverIterator.remove();
675 requeuedDeadServers.remove(tmpServerName);
676 }
677
678 if (!services.getAssignmentManager().isFailoverCleanupDone()) {
679 LOG.info("AssignmentManager hasn't finished failover cleanup; waiting");
680 }
681
682 for(ServerName tmpServerName : requeuedDeadServers.keySet()){
683 processDeadServer(tmpServerName, requeuedDeadServers.get(tmpServerName));
684 }
685 requeuedDeadServers.clear();
686 }
687
688
689
690
691 public boolean removeServerFromDrainList(final ServerName sn) {
692
693
694
695 if (!this.isServerOnline(sn)) {
696 LOG.warn("Server " + sn + " is not currently online. " +
697 "Removing from draining list anyway, as requested.");
698 }
699
700 return this.drainingServers.remove(sn);
701 }
702
703
704
705
706 public boolean addServerToDrainList(final ServerName sn) {
707
708
709
710 if (!this.isServerOnline(sn)) {
711 LOG.warn("Server " + sn + " is not currently online. " +
712 "Ignoring request to add it to draining list.");
713 return false;
714 }
715
716
717 if (this.drainingServers.contains(sn)) {
718 LOG.warn("Server " + sn + " is already in the draining server list." +
719 "Ignoring request to add it again.");
720 return false;
721 }
722 return this.drainingServers.add(sn);
723 }
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738 public RegionOpeningState sendRegionOpen(final ServerName server,
739 HRegionInfo region, int versionOfOfflineNode, List<ServerName> favoredNodes)
740 throws IOException {
741 AdminService.BlockingInterface admin = getRsAdmin(server);
742 if (admin == null) {
743 LOG.warn("Attempting to send OPEN RPC to server " + server.toString() +
744 " failed because no RPC connection found to this server");
745 return RegionOpeningState.FAILED_OPENING;
746 }
747 OpenRegionRequest request = RequestConverter.buildOpenRegionRequest(server,
748 region, versionOfOfflineNode, favoredNodes,
749 (RecoveryMode.LOG_REPLAY == this.services.getMasterFileSystem().getLogRecoveryMode()));
750 try {
751 OpenRegionResponse response = admin.openRegion(null, request);
752 return ResponseConverter.getRegionOpeningState(response);
753 } catch (ServiceException se) {
754 throw ProtobufUtil.getRemoteException(se);
755 }
756 }
757
758
759
760
761
762
763
764
765
766
767 public List<RegionOpeningState> sendRegionOpen(ServerName server,
768 List<Triple<HRegionInfo, Integer, List<ServerName>>> regionOpenInfos)
769 throws IOException {
770 AdminService.BlockingInterface admin = getRsAdmin(server);
771 if (admin == null) {
772 LOG.warn("Attempting to send OPEN RPC to server " + server.toString() +
773 " failed because no RPC connection found to this server");
774 return null;
775 }
776
777 OpenRegionRequest request = RequestConverter.buildOpenRegionRequest(server, regionOpenInfos,
778 (RecoveryMode.LOG_REPLAY == this.services.getMasterFileSystem().getLogRecoveryMode()));
779 try {
780 OpenRegionResponse response = admin.openRegion(null, request);
781 return ResponseConverter.getRegionOpeningStateList(response);
782 } catch (ServiceException se) {
783 throw ProtobufUtil.getRemoteException(se);
784 }
785 }
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801 public boolean sendRegionClose(ServerName server, HRegionInfo region,
802 int versionOfClosingNode, ServerName dest, boolean transitionInZK) throws IOException {
803 if (server == null) throw new NullPointerException("Passed server is null");
804 AdminService.BlockingInterface admin = getRsAdmin(server);
805 if (admin == null) {
806 throw new IOException("Attempting to send CLOSE RPC to server " +
807 server.toString() + " for region " +
808 region.getRegionNameAsString() +
809 " failed because no RPC connection found to this server");
810 }
811 return ProtobufUtil.closeRegion(admin, server, region.getRegionName(),
812 versionOfClosingNode, dest, transitionInZK);
813 }
814
815 public boolean sendRegionClose(ServerName server,
816 HRegionInfo region, int versionOfClosingNode) throws IOException {
817 return sendRegionClose(server, region, versionOfClosingNode, null, true);
818 }
819
820
821
822
823
824
825
826
827
828 public void sendRegionWarmup(ServerName server,
829 HRegionInfo region) {
830 if (server == null) return;
831 try {
832 AdminService.BlockingInterface admin = getRsAdmin(server);
833 ProtobufUtil.warmupRegion(admin, region);
834 } catch (IOException e) {
835 LOG.error("Received exception in RPC for warmup server:" +
836 server + "region: " + region +
837 "exception: " + e);
838 }
839 }
840
841
842
843
844
845 public static void closeRegionSilentlyAndWait(ClusterConnection connection,
846 ServerName server, HRegionInfo region, long timeout) throws IOException, InterruptedException {
847 AdminService.BlockingInterface rs = connection.getAdmin(server);
848 try {
849 ProtobufUtil.closeRegion(rs, server, region.getRegionName(), false);
850 } catch (IOException e) {
851 LOG.warn("Exception when closing region: " + region.getRegionNameAsString(), e);
852 }
853 long expiration = timeout + System.currentTimeMillis();
854 while (System.currentTimeMillis() < expiration) {
855 try {
856 HRegionInfo rsRegion =
857 ProtobufUtil.getRegionInfo(rs, region.getRegionName());
858 if (rsRegion == null) return;
859 } catch (IOException ioe) {
860 if (ioe instanceof NotServingRegionException)
861 return;
862 LOG.warn("Exception when retrieving regioninfo from: " + region.getRegionNameAsString(), ioe);
863 }
864 Thread.sleep(1000);
865 }
866 throw new IOException("Region " + region + " failed to close within"
867 + " timeout " + timeout);
868 }
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883 public void sendRegionsMerge(ServerName server, HRegionInfo region_a,
884 HRegionInfo region_b, boolean forcible) throws IOException {
885 if (server == null)
886 throw new NullPointerException("Passed server is null");
887 if (region_a == null || region_b == null)
888 throw new NullPointerException("Passed region is null");
889 AdminService.BlockingInterface admin = getRsAdmin(server);
890 if (admin == null) {
891 throw new IOException("Attempting to send MERGE REGIONS RPC to server "
892 + server.toString() + " for region "
893 + region_a.getRegionNameAsString() + ","
894 + region_b.getRegionNameAsString()
895 + " failed because no RPC connection found to this server");
896 }
897 ProtobufUtil.mergeRegions(admin, region_a, region_b, forcible);
898 }
899
900
901
902
903 public boolean isServerReachable(ServerName server) {
904 if (server == null) throw new NullPointerException("Passed server is null");
905
906 RetryCounter retryCounter = pingRetryCounterFactory.create();
907 while (retryCounter.shouldRetry()) {
908 synchronized (this.onlineServers) {
909 if (this.deadservers.isDeadServer(server)) {
910 return false;
911 }
912 }
913 try {
914 AdminService.BlockingInterface admin = getRsAdmin(server);
915 if (admin != null) {
916 ServerInfo info = ProtobufUtil.getServerInfo(admin);
917 return info != null && info.hasServerName()
918 && server.getStartcode() == info.getServerName().getStartCode();
919 }
920 } catch (RegionServerStoppedException | ServerNotRunningYetException e) {
921 if (LOG.isDebugEnabled()) {
922 LOG.debug("Couldn't reach " + server, e);
923 }
924 break;
925 } catch (IOException ioe) {
926 if (LOG.isDebugEnabled()) {
927 LOG.debug("Couldn't reach " + server + ", try=" + retryCounter.getAttemptTimes() + " of "
928 + retryCounter.getMaxAttempts(), ioe);
929 }
930 try {
931 retryCounter.sleepUntilNextRetry();
932 } catch(InterruptedException ie) {
933 Thread.currentThread().interrupt();
934 break;
935 }
936 }
937 }
938 return false;
939 }
940
941
942
943
944
945
946
947 private AdminService.BlockingInterface getRsAdmin(final ServerName sn)
948 throws IOException {
949 AdminService.BlockingInterface admin = this.rsAdmins.get(sn);
950 if (admin == null) {
951 LOG.debug("New admin connection to " + sn.toString());
952 if (sn.equals(master.getServerName()) && master instanceof HRegionServer) {
953
954 admin = ((HRegionServer)master).getRSRpcServices();
955 } else {
956 admin = this.connection.getAdmin(sn);
957 }
958 this.rsAdmins.put(sn, admin);
959 }
960 return admin;
961 }
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976 public void waitForRegionServers(MonitoredTask status)
977 throws InterruptedException {
978 final long interval = this.master.getConfiguration().
979 getLong(WAIT_ON_REGIONSERVERS_INTERVAL, 1500);
980 final long timeout = this.master.getConfiguration().
981 getLong(WAIT_ON_REGIONSERVERS_TIMEOUT, 4500);
982 int defaultMinToStart = 1;
983 if (BaseLoadBalancer.tablesOnMaster(master.getConfiguration())) {
984
985
986
987
988 defaultMinToStart = 2;
989 }
990 int minToStart = this.master.getConfiguration().
991 getInt(WAIT_ON_REGIONSERVERS_MINTOSTART, defaultMinToStart);
992 if (minToStart < 1) {
993 LOG.warn(String.format(
994 "The value of '%s' (%d) can not be less than 1, ignoring.",
995 WAIT_ON_REGIONSERVERS_MINTOSTART, minToStart));
996 minToStart = 1;
997 }
998 int maxToStart = this.master.getConfiguration().
999 getInt(WAIT_ON_REGIONSERVERS_MAXTOSTART, Integer.MAX_VALUE);
1000 if (maxToStart < minToStart) {
1001 LOG.warn(String.format(
1002 "The value of '%s' (%d) is set less than '%s' (%d), ignoring.",
1003 WAIT_ON_REGIONSERVERS_MAXTOSTART, maxToStart,
1004 WAIT_ON_REGIONSERVERS_MINTOSTART, minToStart));
1005 maxToStart = Integer.MAX_VALUE;
1006 }
1007
1008 long now = System.currentTimeMillis();
1009 final long startTime = now;
1010 long slept = 0;
1011 long lastLogTime = 0;
1012 long lastCountChange = startTime;
1013 int count = countOfRegionServers();
1014 int oldCount = 0;
1015 while (!this.master.isStopped() && count < maxToStart
1016 && (lastCountChange+interval > now || timeout > slept || count < minToStart)) {
1017
1018 if (oldCount != count || lastLogTime+interval < now){
1019 lastLogTime = now;
1020 String msg =
1021 "Waiting for region servers count to settle; currently"+
1022 " checked in " + count + ", slept for " + slept + " ms," +
1023 " expecting minimum of " + minToStart + ", maximum of "+ maxToStart+
1024 ", timeout of "+timeout+" ms, interval of "+interval+" ms.";
1025 LOG.info(msg);
1026 status.setStatus(msg);
1027 }
1028
1029
1030 final long sleepTime = 50;
1031 Thread.sleep(sleepTime);
1032 now = System.currentTimeMillis();
1033 slept = now - startTime;
1034
1035 oldCount = count;
1036 count = countOfRegionServers();
1037 if (count != oldCount) {
1038 lastCountChange = now;
1039 }
1040 }
1041
1042 LOG.info("Finished waiting for region servers count to settle;" +
1043 " checked in " + count + ", slept for " + slept + " ms," +
1044 " expecting minimum of " + minToStart + ", maximum of "+ maxToStart+","+
1045 " master is "+ (this.master.isStopped() ? "stopped.": "running")
1046 );
1047 }
1048
1049
1050
1051
1052 public List<ServerName> getOnlineServersList() {
1053
1054
1055 return new ArrayList<ServerName>(this.onlineServers.keySet());
1056 }
1057
1058
1059
1060
1061 public List<ServerName> getDrainingServersList() {
1062 return new ArrayList<ServerName>(this.drainingServers);
1063 }
1064
1065
1066
1067
1068 Set<ServerName> getDeadNotExpiredServers() {
1069 return new HashSet<ServerName>(this.queuedDeadServers);
1070 }
1071
1072
1073
1074
1075
1076
1077 void removeRequeuedDeadServers() {
1078 requeuedDeadServers.clear();
1079 }
1080
1081
1082
1083
1084
1085 Map<ServerName, Boolean> getRequeuedDeadServers() {
1086 return Collections.unmodifiableMap(this.requeuedDeadServers);
1087 }
1088
1089 public boolean isServerOnline(ServerName serverName) {
1090 return serverName != null && onlineServers.containsKey(serverName);
1091 }
1092
1093
1094
1095
1096
1097
1098
1099 public synchronized boolean isServerDead(ServerName serverName) {
1100 return serverName == null || deadservers.isDeadServer(serverName)
1101 || queuedDeadServers.contains(serverName)
1102 || requeuedDeadServers.containsKey(serverName);
1103 }
1104
1105 public void shutdownCluster() {
1106 this.clusterShutdown = true;
1107 this.master.stop("Cluster shutdown requested");
1108 }
1109
1110 public boolean isClusterShutdown() {
1111 return this.clusterShutdown;
1112 }
1113
1114
1115
1116
1117 public void stop() {
1118 if (connection != null) {
1119 try {
1120 connection.close();
1121 } catch (IOException e) {
1122 LOG.error("Attempt to close connection to master failed", e);
1123 }
1124 }
1125 }
1126
1127
1128
1129
1130
1131
1132 public List<ServerName> createDestinationServersList(final ServerName serverToExclude){
1133 final List<ServerName> destServers = getOnlineServersList();
1134
1135 if (serverToExclude != null){
1136 destServers.remove(serverToExclude);
1137 }
1138
1139
1140 final List<ServerName> drainingServersCopy = getDrainingServersList();
1141 if (!drainingServersCopy.isEmpty()) {
1142 for (final ServerName server: drainingServersCopy) {
1143 destServers.remove(server);
1144 }
1145 }
1146
1147
1148 removeDeadNotExpiredServers(destServers);
1149 return destServers;
1150 }
1151
1152
1153
1154
1155 public List<ServerName> createDestinationServersList(){
1156 return createDestinationServersList(null);
1157 }
1158
1159
1160
1161
1162
1163
1164
1165 void removeDeadNotExpiredServers(List<ServerName> servers) {
1166 Set<ServerName> deadNotExpiredServersCopy = this.getDeadNotExpiredServers();
1167 if (!deadNotExpiredServersCopy.isEmpty()) {
1168 for (ServerName server : deadNotExpiredServersCopy) {
1169 LOG.debug("Removing dead but not expired server: " + server
1170 + " from eligible server pool.");
1171 servers.remove(server);
1172 }
1173 }
1174 }
1175
1176
1177
1178
1179 void clearDeadServersWithSameHostNameAndPortOfOnlineServer() {
1180 for (ServerName serverName : getOnlineServersList()) {
1181 deadservers.cleanAllPreviousInstances(serverName);
1182 }
1183 }
1184 }