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.io.InterruptedIOException;
23 import java.util.ArrayList;
24 import java.util.Arrays;
25 import java.util.Collection;
26 import java.util.Collections;
27 import java.util.HashMap;
28 import java.util.HashSet;
29 import java.util.Iterator;
30 import java.util.List;
31 import java.util.Map;
32 import java.util.NavigableMap;
33 import java.util.Random;
34 import java.util.Set;
35 import java.util.TreeMap;
36 import java.util.concurrent.Callable;
37 import java.util.concurrent.ConcurrentHashMap;
38 import java.util.concurrent.CopyOnWriteArrayList;
39 import java.util.concurrent.ThreadFactory;
40 import java.util.concurrent.TimeUnit;
41 import java.util.concurrent.atomic.AtomicBoolean;
42 import java.util.concurrent.atomic.AtomicInteger;
43 import java.util.concurrent.locks.Lock;
44 import java.util.concurrent.locks.ReentrantLock;
45
46 import org.apache.commons.logging.Log;
47 import org.apache.commons.logging.LogFactory;
48 import org.apache.hadoop.conf.Configuration;
49 import org.apache.hadoop.fs.FileSystem;
50 import org.apache.hadoop.fs.Path;
51 import org.apache.hadoop.hbase.CoordinatedStateException;
52 import org.apache.hadoop.hbase.HBaseIOException;
53 import org.apache.hadoop.hbase.HConstants;
54 import org.apache.hadoop.hbase.HRegionInfo;
55 import org.apache.hadoop.hbase.HRegionLocation;
56 import org.apache.hadoop.hbase.HTableDescriptor;
57 import org.apache.hadoop.hbase.MetaTableAccessor;
58 import org.apache.hadoop.hbase.NotServingRegionException;
59 import org.apache.hadoop.hbase.RegionLocations;
60 import org.apache.hadoop.hbase.RegionStateListener;
61 import org.apache.hadoop.hbase.RegionTransition;
62 import org.apache.hadoop.hbase.ServerName;
63 import org.apache.hadoop.hbase.TableName;
64 import org.apache.hadoop.hbase.TableNotFoundException;
65 import org.apache.hadoop.hbase.TableStateManager;
66 import org.apache.hadoop.hbase.classification.InterfaceAudience;
67 import org.apache.hadoop.hbase.client.Admin;
68 import org.apache.hadoop.hbase.client.Admin.MasterSwitchType;
69 import org.apache.hadoop.hbase.client.RegionReplicaUtil;
70 import org.apache.hadoop.hbase.client.Result;
71 import org.apache.hadoop.hbase.coordination.BaseCoordinatedStateManager;
72 import org.apache.hadoop.hbase.coordination.OpenRegionCoordination;
73 import org.apache.hadoop.hbase.coordination.RegionMergeCoordination;
74 import org.apache.hadoop.hbase.coordination.SplitTransactionCoordination.SplitTransactionDetails;
75 import org.apache.hadoop.hbase.coordination.ZkOpenRegionCoordination;
76 import org.apache.hadoop.hbase.coordination.ZkRegionMergeCoordination;
77 import org.apache.hadoop.hbase.exceptions.DeserializationException;
78 import org.apache.hadoop.hbase.executor.EventHandler;
79 import org.apache.hadoop.hbase.executor.EventType;
80 import org.apache.hadoop.hbase.executor.ExecutorService;
81 import org.apache.hadoop.hbase.ipc.FailedServerException;
82 import org.apache.hadoop.hbase.ipc.RpcClient;
83 import org.apache.hadoop.hbase.ipc.ServerNotRunningYetException;
84 import org.apache.hadoop.hbase.master.RegionState.State;
85 import org.apache.hadoop.hbase.master.balancer.FavoredNodeAssignmentHelper;
86 import org.apache.hadoop.hbase.master.balancer.FavoredNodeLoadBalancer;
87 import org.apache.hadoop.hbase.master.handler.ClosedRegionHandler;
88 import org.apache.hadoop.hbase.master.handler.DisableTableHandler;
89 import org.apache.hadoop.hbase.master.handler.EnableTableHandler;
90 import org.apache.hadoop.hbase.master.handler.OpenedRegionHandler;
91 import org.apache.hadoop.hbase.protobuf.generated.RegionServerStatusProtos.RegionStateTransition;
92 import org.apache.hadoop.hbase.protobuf.generated.RegionServerStatusProtos.RegionStateTransition.TransitionCode;
93 import org.apache.hadoop.hbase.protobuf.generated.ZooKeeperProtos;
94 import org.apache.hadoop.hbase.regionserver.RegionAlreadyInTransitionException;
95 import org.apache.hadoop.hbase.regionserver.RegionOpeningState;
96 import org.apache.hadoop.hbase.regionserver.RegionServerAbortedException;
97 import org.apache.hadoop.hbase.regionserver.RegionServerStoppedException;
98 import org.apache.hadoop.hbase.util.ConfigUtil;
99 import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
100 import org.apache.hadoop.hbase.util.FSUtils;
101 import org.apache.hadoop.hbase.util.KeyLocker;
102 import org.apache.hadoop.hbase.util.Pair;
103 import org.apache.hadoop.hbase.util.PairOfSameType;
104 import org.apache.hadoop.hbase.util.Threads;
105 import org.apache.hadoop.hbase.util.Triple;
106 import org.apache.hadoop.hbase.wal.DefaultWALProvider;
107 import org.apache.hadoop.hbase.zookeeper.MetaTableLocator;
108 import org.apache.hadoop.hbase.zookeeper.ZKAssign;
109 import org.apache.hadoop.hbase.zookeeper.ZKUtil;
110 import org.apache.hadoop.hbase.zookeeper.ZooKeeperListener;
111 import org.apache.hadoop.ipc.RemoteException;
112 import org.apache.hadoop.util.StringUtils;
113 import org.apache.zookeeper.AsyncCallback;
114 import org.apache.zookeeper.KeeperException;
115 import org.apache.zookeeper.KeeperException.NoNodeException;
116 import org.apache.zookeeper.KeeperException.NodeExistsException;
117 import org.apache.zookeeper.data.Stat;
118
119 import com.google.common.annotations.VisibleForTesting;
120 import com.google.common.collect.LinkedHashMultimap;
121
122
123
124
125
126
127
128
129 @InterfaceAudience.Private
130 public class AssignmentManager extends ZooKeeperListener {
131 private static final Log LOG = LogFactory.getLog(AssignmentManager.class);
132
133 public static final ServerName HBCK_CODE_SERVERNAME = ServerName.valueOf(HConstants.HBCK_CODE_NAME,
134 -1, -1L);
135
136 static final String ALREADY_IN_TRANSITION_WAITTIME
137 = "hbase.assignment.already.intransition.waittime";
138 static final int DEFAULT_ALREADY_IN_TRANSITION_WAITTIME = 60000;
139
140 protected final MasterServices server;
141
142 private ServerManager serverManager;
143
144 private boolean shouldAssignRegionsWithFavoredNodes;
145
146 private LoadBalancer balancer;
147
148 private final MetricsAssignmentManager metricsAssignmentManager;
149
150 private final TableLockManager tableLockManager;
151
152 private AtomicInteger numRegionsOpened = new AtomicInteger(0);
153
154 final private KeyLocker<String> locker = new KeyLocker<String>();
155
156 Set<HRegionInfo> replicasToClose = Collections.synchronizedSet(new HashSet<HRegionInfo>());
157
158
159
160
161
162 private final Map <String, HRegionInfo> regionsToReopen;
163
164
165
166
167
168 private final int maximumAttempts;
169
170
171
172
173 private final Map<String, PairOfSameType<HRegionInfo>> mergingRegions
174 = new HashMap<String, PairOfSameType<HRegionInfo>>();
175
176 private final Map<HRegionInfo, PairOfSameType<HRegionInfo>> splitRegions
177 = new HashMap<HRegionInfo, PairOfSameType<HRegionInfo>>();
178
179
180
181
182
183 private final long sleepTimeBeforeRetryingMetaAssignment;
184
185
186
187
188
189 final NavigableMap<String, RegionPlan> regionPlans =
190 new TreeMap<String, RegionPlan>();
191
192 private final TableStateManager tableStateManager;
193
194 private final ExecutorService executorService;
195
196
197 private Map<HRegionInfo, AtomicBoolean> closedRegionHandlerCalled = null;
198
199
200 private Map<HRegionInfo, AtomicBoolean> openedRegionHandlerCalled = null;
201
202
203 private java.util.concurrent.ExecutorService threadPoolExecutorService;
204
205
206 private final java.util.concurrent.ExecutorService zkEventWorkers;
207
208 private List<EventType> ignoreStatesRSOffline = Arrays.asList(
209 EventType.RS_ZK_REGION_FAILED_OPEN, EventType.RS_ZK_REGION_CLOSED);
210
211 private final RegionStates regionStates;
212
213
214
215
216
217 private final int bulkAssignThresholdRegions;
218 private final int bulkAssignThresholdServers;
219 private final int bulkPerRegionOpenTimeGuesstimate;
220
221
222
223
224 private final boolean bulkAssignWaitTillAllAssigned;
225
226
227
228
229
230
231
232
233
234 protected final AtomicBoolean failoverCleanupDone = new AtomicBoolean(false);
235
236
237
238
239
240
241
242
243 private final ConcurrentHashMap<String, AtomicInteger>
244 failedOpenTracker = new ConcurrentHashMap<String, AtomicInteger>();
245
246
247 private final boolean useZKForAssignment;
248
249
250
251 private final RegionStateStore regionStateStore;
252
253
254
255
256 private static boolean TEST_SKIP_SPLIT_HANDLING = false;
257 private static boolean TEST_SKIP_MERGE_HANDLING = false;
258
259
260 private List<AssignmentListener> listeners = new CopyOnWriteArrayList<AssignmentListener>();
261
262 private RegionStateListener regionStateListener;
263
264 public enum ServerHostRegion {
265 NOT_HOSTING_REGION, HOSTING_REGION, UNKNOWN,
266 }
267
268
269
270
271
272
273
274
275
276
277
278
279
280 public AssignmentManager(MasterServices server, ServerManager serverManager,
281 final LoadBalancer balancer,
282 final ExecutorService service, MetricsMaster metricsMaster,
283 final TableLockManager tableLockManager) throws KeeperException,
284 IOException, CoordinatedStateException {
285 super(server.getZooKeeper());
286 this.server = server;
287 this.serverManager = serverManager;
288 this.executorService = service;
289 this.regionStateStore = new RegionStateStore(server);
290 this.regionsToReopen = Collections.synchronizedMap
291 (new HashMap<String, HRegionInfo> ());
292 Configuration conf = server.getConfiguration();
293
294 this.shouldAssignRegionsWithFavoredNodes = conf.getClass(
295 HConstants.HBASE_MASTER_LOADBALANCER_CLASS, Object.class).equals(
296 FavoredNodeLoadBalancer.class);
297 try {
298 if (server.getCoordinatedStateManager() != null) {
299 this.tableStateManager = server.getCoordinatedStateManager().getTableStateManager();
300 } else {
301 this.tableStateManager = null;
302 }
303 } catch (InterruptedException e) {
304 throw new InterruptedIOException();
305 }
306
307 this.maximumAttempts = Math.max(1,
308 this.server.getConfiguration().getInt("hbase.assignment.maximum.attempts", 10));
309 this.sleepTimeBeforeRetryingMetaAssignment = this.server.getConfiguration().getLong(
310 "hbase.meta.assignment.retry.sleeptime", 1000l);
311 this.balancer = balancer;
312 int maxThreads = conf.getInt("hbase.assignment.threads.max", 30);
313 this.threadPoolExecutorService = Threads.getBoundedCachedThreadPool(
314 maxThreads, 60L, TimeUnit.SECONDS, Threads.newDaemonThreadFactory("AM."));
315 this.regionStates = new RegionStates(
316 server, tableStateManager, serverManager, regionStateStore);
317
318 this.bulkAssignWaitTillAllAssigned =
319 conf.getBoolean("hbase.bulk.assignment.waittillallassigned", false);
320 this.bulkAssignThresholdRegions = conf.getInt("hbase.bulk.assignment.threshold.regions", 7);
321 this.bulkAssignThresholdServers = conf.getInt("hbase.bulk.assignment.threshold.servers", 3);
322 this.bulkPerRegionOpenTimeGuesstimate =
323 conf.getInt("hbase.bulk.assignment.perregion.open.time", 10000);
324
325 int workers = conf.getInt("hbase.assignment.zkevent.workers", 20);
326 ThreadFactory threadFactory = Threads.newDaemonThreadFactory("AM.ZK.Worker");
327 zkEventWorkers = Threads.getBoundedCachedThreadPool(workers, 60L,
328 TimeUnit.SECONDS, threadFactory);
329 this.tableLockManager = tableLockManager;
330
331 this.metricsAssignmentManager = new MetricsAssignmentManager();
332 useZKForAssignment = ConfigUtil.useZKForAssignment(conf);
333 }
334
335 MetricsAssignmentManager getAssignmentManagerMetrics() {
336 return this.metricsAssignmentManager;
337 }
338
339
340
341
342
343 public void registerListener(final AssignmentListener listener) {
344 this.listeners.add(listener);
345 }
346
347
348
349
350
351 public boolean unregisterListener(final AssignmentListener listener) {
352 return this.listeners.remove(listener);
353 }
354
355
356
357
358 public TableStateManager getTableStateManager() {
359
360
361 return this.tableStateManager;
362 }
363
364
365
366
367
368
369
370 public RegionStates getRegionStates() {
371 return regionStates;
372 }
373
374
375
376
377 @VisibleForTesting
378 RegionStateStore getRegionStateStore() {
379 return regionStateStore;
380 }
381
382 public RegionPlan getRegionReopenPlan(HRegionInfo hri) {
383 return new RegionPlan(hri, null, regionStates.getRegionServerOfRegion(hri));
384 }
385
386
387
388
389
390
391 public void addPlan(String encodedName, RegionPlan plan) {
392 synchronized (regionPlans) {
393 regionPlans.put(encodedName, plan);
394 }
395 }
396
397
398
399
400 public void addPlans(Map<String, RegionPlan> plans) {
401 synchronized (regionPlans) {
402 regionPlans.putAll(plans);
403 }
404 }
405
406
407
408
409
410
411
412
413 public void setRegionsToReopen(List <HRegionInfo> regions) {
414 for(HRegionInfo hri : regions) {
415 regionsToReopen.put(hri.getEncodedName(), hri);
416 }
417 }
418
419
420
421
422
423
424
425
426 public Pair<Integer, Integer> getReopenStatus(TableName tableName)
427 throws IOException {
428 List<HRegionInfo> hris;
429 if (TableName.META_TABLE_NAME.equals(tableName)) {
430 hris = new MetaTableLocator().getMetaRegions(server.getZooKeeper());
431 } else {
432 hris = MetaTableAccessor.getTableRegions(server.getZooKeeper(),
433 server.getConnection(), tableName, true);
434 }
435
436 Integer pending = 0;
437 for (HRegionInfo hri : hris) {
438 String name = hri.getEncodedName();
439
440 if (regionsToReopen.containsKey(name)
441 || regionStates.isRegionInTransition(name)) {
442 pending++;
443 }
444 }
445 return new Pair<Integer, Integer>(pending, hris.size());
446 }
447
448
449
450
451
452
453 public boolean isFailoverCleanupDone() {
454 return failoverCleanupDone.get();
455 }
456
457
458
459
460
461 public Lock acquireRegionLock(final String encodedName) {
462 return locker.acquireLock(encodedName);
463 }
464
465
466
467
468
469 void failoverCleanupDone() {
470 failoverCleanupDone.set(true);
471 serverManager.processQueuedDeadServers();
472 }
473
474
475
476
477
478
479
480
481
482 void joinCluster() throws IOException,
483 KeeperException, InterruptedException, CoordinatedStateException {
484 long startTime = System.currentTimeMillis();
485
486
487
488
489
490
491
492
493
494
495
496 Set<ServerName> deadServers = rebuildUserRegions();
497
498
499
500 boolean failover = processDeadServersAndRegionsInTransition(deadServers);
501
502 if (!useZKForAssignment) {
503
504 ZKUtil.deleteNodeRecursively(watcher, watcher.assignmentZNode);
505 }
506 recoverTableInDisablingState();
507 recoverTableInEnablingState();
508 LOG.info("Joined the cluster in " + (System.currentTimeMillis()
509 - startTime) + "ms, failover=" + failover);
510 }
511
512
513
514
515
516
517
518
519
520
521
522
523 boolean processDeadServersAndRegionsInTransition(final Set<ServerName> deadServers)
524 throws KeeperException, IOException, InterruptedException, CoordinatedStateException {
525 List<String> nodes = ZKUtil.listChildrenNoWatch(watcher, watcher.assignmentZNode);
526
527 if (useZKForAssignment && nodes == null) {
528 String errorMessage = "Failed to get the children from ZK";
529 server.abort(errorMessage, new IOException(errorMessage));
530 return true;
531 }
532
533 boolean failover = !serverManager.getDeadServers().isEmpty();
534 if (failover) {
535
536 if (LOG.isDebugEnabled()) {
537 LOG.debug("Found dead servers out on cluster " + serverManager.getDeadServers());
538 }
539 } else {
540
541 Set<ServerName> onlineServers = serverManager.getOnlineServers().keySet();
542 for (Map.Entry<HRegionInfo, ServerName> en:
543 regionStates.getRegionAssignments().entrySet()) {
544 HRegionInfo hri = en.getKey();
545 if (!hri.isMetaTable()
546 && onlineServers.contains(en.getValue())) {
547 LOG.debug("Found " + hri + " out on cluster");
548 failover = true;
549 break;
550 }
551 }
552 if (!failover && nodes != null) {
553
554 for (String encodedName: nodes) {
555 RegionState regionState = regionStates.getRegionState(encodedName);
556 if (regionState != null && !regionState.getRegion().isMetaRegion()) {
557 LOG.debug("Found " + regionState + " in RITs");
558 failover = true;
559 break;
560 }
561 }
562 }
563 }
564 if (!failover && !useZKForAssignment) {
565
566 Map<String, RegionState> regionsInTransition = regionStates.getRegionsInTransition();
567 if (!regionsInTransition.isEmpty()) {
568 Set<ServerName> onlineServers = serverManager.getOnlineServers().keySet();
569 for (RegionState regionState: regionsInTransition.values()) {
570 ServerName serverName = regionState.getServerName();
571 if (!regionState.getRegion().isMetaRegion()
572 && serverName != null && onlineServers.contains(serverName)) {
573 LOG.debug("Found " + regionState + " in RITs");
574 failover = true;
575 break;
576 }
577 }
578 }
579 }
580 if (!failover) {
581
582
583
584
585 Set<ServerName> queuedDeadServers = serverManager.getRequeuedDeadServers().keySet();
586 if (!queuedDeadServers.isEmpty()) {
587 Configuration conf = server.getConfiguration();
588 Path walRootDir = FSUtils.getWALRootDir(conf);
589 FileSystem walFs = FSUtils.getWALFileSystem(conf);
590 for (ServerName serverName: queuedDeadServers) {
591
592
593 Path walDir = new Path(walRootDir,
594 DefaultWALProvider.getWALDirectoryName(serverName.toString()));
595 Path splitDir = walDir.suffix(DefaultWALProvider.SPLITTING_EXT);
596 if (walFs.exists(walDir) || walFs.exists(splitDir)) {
597 LOG.debug("Found queued dead server " + serverName);
598 failover = true;
599 break;
600 }
601 }
602 if (!failover) {
603
604
605 LOG.info("AM figured that it's not a failover and cleaned up "
606 + queuedDeadServers.size() + " queued dead servers");
607 serverManager.removeRequeuedDeadServers();
608 }
609 }
610 }
611
612 Map<HRegionInfo, ServerName> allRegions = null;
613 if (!failover) {
614
615 allRegions = getUserRegionsToAssign();
616 }
617
618
619 regionStateStore.start();
620
621
622 if (failover) {
623 LOG.info("Found regions out on cluster or in RIT; presuming failover");
624
625
626 processDeadServersAndRecoverLostRegions(deadServers);
627
628
629
630
631 if (!MetaTableAccessor.infoServerExists(server.getConnection())) {
632
633
634 assignRegionsOnSSHCompletion();
635 }
636 }
637
638 if (!failover && useZKForAssignment) {
639
640 ZKAssign.deleteAllNodes(watcher);
641 ZKUtil.listChildrenAndWatchForNewChildren(this.watcher,
642 this.watcher.assignmentZNode);
643 }
644
645
646
647
648
649 failoverCleanupDone();
650 if (!failover) {
651
652 LOG.info("Clean cluster startup. Assigning user regions");
653 assignAllUserRegions(allRegions);
654 }
655
656
657
658 for (HRegionInfo h : replicasToClose) {
659 unassign(h);
660 }
661 replicasToClose.clear();
662 return failover;
663 }
664
665
666
667
668
669
670 private Map<HRegionInfo, ServerName> getUserRegionsToAssign()
671 throws InterruptedIOException, CoordinatedStateException {
672 Set<TableName> disabledOrDisablingOrEnabling =
673 tableStateManager.getTablesInStates(ZooKeeperProtos.Table.State.DISABLED,
674 ZooKeeperProtos.Table.State.DISABLING, ZooKeeperProtos.Table.State.ENABLING);
675
676
677 return regionStates.closeAllUserRegions(disabledOrDisablingOrEnabling);
678 }
679
680
681
682
683
684 private void assignRegionsOnSSHCompletion() {
685 LOG.info("Meta is rebuild by OfflineMetaRepair tool, assigning all user regions.");
686 Thread regionAssignerThread = new Thread("RegionAssignerOnMetaRebuild") {
687 public void run() {
688
689 while (serverManager.areDeadServersInProgress()) {
690 try {
691 Thread.sleep(100);
692 } catch (InterruptedException e) {
693 LOG.warn("RegionAssignerOnMetaRebuild got interrupted.", e);
694 Thread.currentThread().interrupt();
695 return;
696 }
697 }
698 LOG.info("SSH has been completed for all dead servers, assigning user regions.");
699 try {
700
701 assignAllUserRegions(getUserRegionsToAssign());
702 } catch (CoordinatedStateException | IOException | InterruptedException e) {
703 LOG.error("Exception occured while assigning user regions.", e);
704 }
705 };
706 };
707 regionAssignerThread.setDaemon(true);
708 regionAssignerThread.start();
709 }
710
711
712
713
714
715
716
717
718
719
720
721
722 boolean processRegionInTransitionAndBlockUntilAssigned(final HRegionInfo hri)
723 throws InterruptedException, KeeperException, IOException {
724 String encodedRegionName = hri.getEncodedName();
725 if (!processRegionInTransition(encodedRegionName, hri)) {
726 return false;
727 }
728 LOG.debug("Waiting on " + HRegionInfo.prettyPrint(encodedRegionName));
729 while (!this.server.isStopped() &&
730 this.regionStates.isRegionInTransition(encodedRegionName)) {
731 RegionState state = this.regionStates.getRegionTransitionState(encodedRegionName);
732 if (state == null || !serverManager.isServerOnline(state.getServerName())) {
733
734
735
736 break;
737 }
738 this.regionStates.waitForUpdate(100);
739 }
740 return true;
741 }
742
743
744
745
746
747
748
749
750
751
752 boolean processRegionInTransition(final String encodedRegionName,
753 final HRegionInfo regionInfo) throws KeeperException, IOException {
754
755
756
757
758 Lock lock = locker.acquireLock(encodedRegionName);
759 try {
760 Stat stat = new Stat();
761 byte [] data = ZKAssign.getDataAndWatch(watcher, encodedRegionName, stat);
762 if (data == null) return false;
763 RegionTransition rt;
764 try {
765 rt = RegionTransition.parseFrom(data);
766 } catch (DeserializationException e) {
767 LOG.warn("Failed parse znode data", e);
768 return false;
769 }
770 HRegionInfo hri = regionInfo;
771 if (hri == null) {
772
773
774
775
776
777 hri = regionStates.getRegionInfo(rt.getRegionName());
778 EventType et = rt.getEventType();
779 if (hri == null && et != EventType.RS_ZK_REGION_MERGING
780 && et != EventType.RS_ZK_REQUEST_REGION_MERGE) {
781 LOG.warn("Couldn't find the region in recovering " + rt);
782 return false;
783 }
784 }
785
786
787
788 BaseCoordinatedStateManager cp =
789 (BaseCoordinatedStateManager) this.server.getCoordinatedStateManager();
790 OpenRegionCoordination openRegionCoordination = cp.getOpenRegionCoordination();
791
792 ZkOpenRegionCoordination.ZkOpenRegionDetails zkOrd =
793 new ZkOpenRegionCoordination.ZkOpenRegionDetails();
794 zkOrd.setVersion(stat.getVersion());
795 zkOrd.setServerName(cp.getServer().getServerName());
796
797 return processRegionsInTransition(
798 rt, hri, openRegionCoordination, zkOrd);
799 } finally {
800 lock.unlock();
801 }
802 }
803
804
805
806
807
808
809
810
811
812 boolean processRegionsInTransition(
813 final RegionTransition rt, final HRegionInfo regionInfo,
814 OpenRegionCoordination coordination,
815 final OpenRegionCoordination.OpenRegionDetails ord) throws KeeperException {
816 EventType et = rt.getEventType();
817
818 final ServerName sn = rt.getServerName();
819 final byte[] regionName = rt.getRegionName();
820 final String encodedName = HRegionInfo.encodeRegionName(regionName);
821 final String prettyPrintedRegionName = HRegionInfo.prettyPrint(encodedName);
822 LOG.info("Processing " + prettyPrintedRegionName + " in state: " + et);
823
824 if (regionStates.isRegionInTransition(encodedName)
825 && (regionInfo.isMetaRegion() || !useZKForAssignment)) {
826 LOG.info("Processed region " + prettyPrintedRegionName + " in state: "
827 + et + ", does nothing since the region is already in transition "
828 + regionStates.getRegionTransitionState(encodedName));
829
830 return true;
831 }
832 if (!serverManager.isServerOnline(sn)) {
833
834
835
836 LOG.debug("RIT " + encodedName + " in state=" + rt.getEventType() +
837 " was on deadserver; forcing offline");
838 if (regionStates.isRegionOnline(regionInfo)) {
839
840
841
842 regionStates.regionOffline(regionInfo);
843 sendRegionClosedNotification(regionInfo);
844 }
845
846 regionStates.updateRegionState(regionInfo, State.OFFLINE, sn);
847
848 if (regionInfo.isMetaRegion()) {
849
850
851 MetaTableLocator.setMetaLocation(watcher, sn, State.OPEN);
852 } else {
853
854
855 regionStates.setLastRegionServerOfRegion(sn, encodedName);
856
857 if (!serverManager.isServerDead(sn)) {
858 serverManager.expireServer(sn);
859 }
860 }
861 return false;
862 }
863 switch (et) {
864 case M_ZK_REGION_CLOSING:
865
866
867 final RegionState rsClosing = regionStates.updateRegionState(rt, State.CLOSING);
868 this.executorService.submit(
869 new EventHandler(server, EventType.M_MASTER_RECOVERY) {
870 @Override
871 public void process() throws IOException {
872 ReentrantLock lock = locker.acquireLock(regionInfo.getEncodedName());
873 try {
874 final int expectedVersion = ((ZkOpenRegionCoordination.ZkOpenRegionDetails) ord)
875 .getVersion();
876 unassign(regionInfo, rsClosing, expectedVersion, null, useZKForAssignment, null);
877 if (regionStates.isRegionOffline(regionInfo)) {
878 assign(regionInfo, true);
879 }
880 } finally {
881 lock.unlock();
882 }
883 }
884 });
885 break;
886
887 case RS_ZK_REGION_CLOSED:
888 case RS_ZK_REGION_FAILED_OPEN:
889
890 regionStates.setRegionStateTOCLOSED(regionInfo, sn);
891 if (!replicasToClose.contains(regionInfo)) {
892 invokeAssign(regionInfo);
893 } else {
894 offlineDisabledRegion(regionInfo);
895 }
896 break;
897
898 case M_ZK_REGION_OFFLINE:
899
900 regionStates.updateRegionState(rt, State.OFFLINE);
901 final RegionState rsOffline = regionStates.getRegionState(regionInfo);
902 this.executorService.submit(
903 new EventHandler(server, EventType.M_MASTER_RECOVERY) {
904 @Override
905 public void process() throws IOException {
906 ReentrantLock lock = locker.acquireLock(regionInfo.getEncodedName());
907 try {
908 RegionPlan plan = new RegionPlan(regionInfo, null, sn);
909 addPlan(encodedName, plan);
910 assign(rsOffline, true, false);
911 } finally {
912 lock.unlock();
913 }
914 }
915 });
916 break;
917
918 case RS_ZK_REGION_OPENING:
919 regionStates.updateRegionState(rt, State.OPENING);
920 break;
921
922 case RS_ZK_REGION_OPENED:
923
924
925
926 regionStates.updateRegionState(rt, State.OPEN);
927 new OpenedRegionHandler(server, this, regionInfo, coordination, ord).process();
928 break;
929 case RS_ZK_REQUEST_REGION_SPLIT:
930 case RS_ZK_REGION_SPLITTING:
931 case RS_ZK_REGION_SPLIT:
932
933
934
935 regionStates.regionOnline(regionInfo, sn);
936 regionStates.updateRegionState(rt, State.SPLITTING);
937 if (!handleRegionSplitting(
938 rt, encodedName, prettyPrintedRegionName, sn)) {
939 deleteSplittingNode(encodedName, sn);
940 }
941 break;
942 case RS_ZK_REQUEST_REGION_MERGE:
943 case RS_ZK_REGION_MERGING:
944 case RS_ZK_REGION_MERGED:
945 if (!handleRegionMerging(
946 rt, encodedName, prettyPrintedRegionName, sn)) {
947 deleteMergingNode(encodedName, sn);
948 }
949 break;
950 default:
951 throw new IllegalStateException("Received region in state:" + et + " is not valid.");
952 }
953 LOG.info("Processed region " + prettyPrintedRegionName + " in state "
954 + et + ", on " + (serverManager.isServerOnline(sn) ? "" : "dead ")
955 + "server: " + sn);
956 return true;
957 }
958
959
960
961
962
963 public void removeClosedRegion(HRegionInfo hri) {
964 if (regionsToReopen.remove(hri.getEncodedName()) != null) {
965 LOG.debug("Removed region from reopening regions because it was closed");
966 }
967 }
968
969
970
971
972
973
974
975
976
977
978
979
980 @edu.umd.cs.findbugs.annotations.SuppressWarnings(
981 value="AT_OPERATION_SEQUENCE_ON_CONCURRENT_ABSTRACTION",
982 justification="Needs work; says access to ConcurrentHashMaps not ATOMIC!!!")
983 void handleRegion(final RegionTransition rt, OpenRegionCoordination coordination,
984 OpenRegionCoordination.OpenRegionDetails ord) {
985 if (rt == null) {
986 LOG.warn("Unexpected NULL input for RegionTransition rt");
987 return;
988 }
989 final ServerName sn = rt.getServerName();
990
991 if (sn.equals(HBCK_CODE_SERVERNAME)) {
992 handleHBCK(rt);
993 return;
994 }
995 final long createTime = rt.getCreateTime();
996 final byte[] regionName = rt.getRegionName();
997 String encodedName = HRegionInfo.encodeRegionName(regionName);
998 String prettyPrintedRegionName = HRegionInfo.prettyPrint(encodedName);
999
1000 if (!serverManager.isServerOnline(sn)
1001 && !ignoreStatesRSOffline.contains(rt.getEventType())) {
1002 LOG.warn("Attempted to handle region transition for server but " +
1003 "it is not online: " + prettyPrintedRegionName + ", " + rt);
1004 return;
1005 }
1006
1007 RegionState regionState =
1008 regionStates.getRegionState(encodedName);
1009 long startTime = System.currentTimeMillis();
1010 if (LOG.isDebugEnabled()) {
1011 boolean lateEvent = createTime < (startTime - 15000);
1012 LOG.debug("Handling " + rt.getEventType() +
1013 ", server=" + sn + ", region=" +
1014 (prettyPrintedRegionName == null ? "null" : prettyPrintedRegionName) +
1015 (lateEvent ? ", which is more than 15 seconds late" : "") +
1016 ", current_state=" + regionState);
1017 }
1018
1019
1020 if (rt.getEventType() == EventType.M_ZK_REGION_OFFLINE) {
1021 return;
1022 }
1023
1024
1025 Lock lock = locker.acquireLock(encodedName);
1026 try {
1027 RegionState latestState =
1028 regionStates.getRegionState(encodedName);
1029 if ((regionState == null && latestState != null)
1030 || (regionState != null && latestState == null)
1031 || (regionState != null && latestState != null
1032 && latestState.getState() != regionState.getState())) {
1033 LOG.warn("Region state changed from " + regionState + " to "
1034 + latestState + ", while acquiring lock");
1035 }
1036 long waitedTime = System.currentTimeMillis() - startTime;
1037 if (waitedTime > 5000) {
1038 LOG.warn("Took " + waitedTime + "ms to acquire the lock");
1039 }
1040 regionState = latestState;
1041 switch (rt.getEventType()) {
1042 case RS_ZK_REQUEST_REGION_SPLIT:
1043 case RS_ZK_REGION_SPLITTING:
1044 case RS_ZK_REGION_SPLIT:
1045
1046
1047 if ((!isRegionSplitOrMergeEnabled(rt, prettyPrintedRegionName, MasterSwitchType.SPLIT)
1048 && rt.getEventType() == EventType.RS_ZK_REQUEST_REGION_SPLIT)
1049 || !handleRegionSplitting(rt, encodedName, prettyPrintedRegionName, sn)) {
1050 deleteSplittingNode(encodedName, sn);
1051 }
1052 break;
1053
1054 case RS_ZK_REQUEST_REGION_MERGE:
1055 case RS_ZK_REGION_MERGING:
1056 case RS_ZK_REGION_MERGED:
1057
1058
1059
1060
1061 if ((!isRegionSplitOrMergeEnabled(rt, prettyPrintedRegionName, MasterSwitchType.MERGE)
1062 && rt.getEventType() == EventType.RS_ZK_REQUEST_REGION_MERGE)
1063 || !handleRegionMerging(rt, encodedName, prettyPrintedRegionName, sn)) {
1064 deleteMergingNode(encodedName, sn);
1065 }
1066 break;
1067
1068 case M_ZK_REGION_CLOSING:
1069
1070
1071 if (regionState == null
1072 || !regionState.isPendingCloseOrClosingOnServer(sn)) {
1073 LOG.warn("Received CLOSING for " + prettyPrintedRegionName
1074 + " from " + sn + " but the region isn't PENDING_CLOSE/CLOSING here: "
1075 + regionStates.getRegionState(encodedName));
1076 return;
1077 }
1078
1079 regionStates.updateRegionState(rt, State.CLOSING);
1080 break;
1081
1082 case RS_ZK_REGION_CLOSED:
1083
1084 if (regionState == null
1085 || !regionState.isPendingCloseOrClosingOnServer(sn)) {
1086 LOG.warn("Received CLOSED for " + prettyPrintedRegionName
1087 + " from " + sn + " but the region isn't PENDING_CLOSE/CLOSING here: "
1088 + regionStates.getRegionState(encodedName));
1089 return;
1090 }
1091
1092
1093
1094 new ClosedRegionHandler(server, this, regionState.getRegion()).process();
1095 updateClosedRegionHandlerTracker(regionState.getRegion());
1096 break;
1097
1098 case RS_ZK_REGION_FAILED_OPEN:
1099 if (regionState == null
1100 || !regionState.isPendingOpenOrOpeningOnServer(sn)) {
1101 LOG.warn("Received FAILED_OPEN for " + prettyPrintedRegionName
1102 + " from " + sn + " but the region isn't PENDING_OPEN/OPENING here: "
1103 + regionStates.getRegionState(encodedName));
1104 return;
1105 }
1106 AtomicInteger failedOpenCount = failedOpenTracker.get(encodedName);
1107 if (failedOpenCount == null) {
1108 failedOpenCount = new AtomicInteger();
1109
1110
1111
1112
1113 failedOpenTracker.put(encodedName, failedOpenCount);
1114 }
1115 if (failedOpenCount.incrementAndGet() >= maximumAttempts) {
1116
1117 regionStates.updateRegionState(rt, State.FAILED_OPEN);
1118
1119
1120 failedOpenTracker.remove(encodedName);
1121 } else {
1122
1123 regionState = regionStates.setRegionStateTOCLOSED(rt.getRegionName(), sn);
1124 if (regionState != null) {
1125
1126
1127 try {
1128 getRegionPlan(regionState.getRegion(), sn, true);
1129 new ClosedRegionHandler(server, this, regionState.getRegion()).process();
1130 } catch (HBaseIOException e) {
1131 LOG.warn("Failed to get region plan", e);
1132 }
1133 }
1134 }
1135 break;
1136
1137 case RS_ZK_REGION_OPENING:
1138
1139
1140 if (regionState == null
1141 || !regionState.isPendingOpenOrOpeningOnServer(sn)) {
1142 LOG.warn("Received OPENING for " + prettyPrintedRegionName
1143 + " from " + sn + " but the region isn't PENDING_OPEN/OPENING here: "
1144 + regionStates.getRegionState(encodedName));
1145 return;
1146 }
1147
1148 regionStates.updateRegionState(rt, State.OPENING);
1149 break;
1150
1151 case RS_ZK_REGION_OPENED:
1152
1153 if (regionState == null
1154 || !regionState.isPendingOpenOrOpeningOnServer(sn)) {
1155 LOG.warn("Received OPENED for " + prettyPrintedRegionName
1156 + " from " + sn + " but the region isn't PENDING_OPEN/OPENING here: "
1157 + regionStates.getRegionState(encodedName));
1158
1159 if (regionState != null) {
1160 if(regionState.isOpened() && regionState.getServerName().equals(sn)) {
1161
1162
1163 failedOpenTracker.remove(encodedName);
1164 new OpenedRegionHandler(
1165 server, this, regionState.getRegion(), coordination, ord).process();
1166 updateOpenedRegionHandlerTracker(regionState.getRegion());
1167 } else {
1168
1169
1170
1171 unassign(regionState.getRegion(), null, -1, null, false, sn);
1172 }
1173 }
1174 return;
1175 }
1176
1177 regionState =
1178 regionStates.transitionOpenFromPendingOpenOrOpeningOnServer(rt,regionState, sn);
1179 if (regionState != null) {
1180 failedOpenTracker.remove(encodedName);
1181 new OpenedRegionHandler(
1182 server, this, regionState.getRegion(), coordination, ord).process();
1183 updateOpenedRegionHandlerTracker(regionState.getRegion());
1184 }
1185 break;
1186
1187 default:
1188 throw new IllegalStateException("Received event is not valid.");
1189 }
1190 } finally {
1191 lock.unlock();
1192 }
1193 }
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203 private boolean isRegionSplitOrMergeEnabled(RegionTransition rt, String prettyPrintedRegionName,
1204 MasterSwitchType switchType) {
1205 if (!((HMaster) server).getSplitOrMergeTracker().isSplitOrMergeEnabled(switchType)) {
1206 LOG.warn("Region " + switchType + " not enabled, skipping " + rt.getEventType()
1207 + " of reigon " + prettyPrintedRegionName);
1208 return false;
1209 }
1210 return true;
1211 }
1212
1213
1214 boolean wasClosedHandlerCalled(HRegionInfo hri) {
1215 AtomicBoolean b = closedRegionHandlerCalled.get(hri);
1216
1217
1218
1219 return b == null ? false : b.compareAndSet(true, false);
1220 }
1221
1222
1223 boolean wasOpenedHandlerCalled(HRegionInfo hri) {
1224 AtomicBoolean b = openedRegionHandlerCalled.get(hri);
1225
1226
1227
1228 return b == null ? false : b.compareAndSet(true, false);
1229 }
1230
1231
1232 void initializeHandlerTrackers() {
1233 closedRegionHandlerCalled = new HashMap<HRegionInfo, AtomicBoolean>();
1234 openedRegionHandlerCalled = new HashMap<HRegionInfo, AtomicBoolean>();
1235 }
1236
1237 void updateClosedRegionHandlerTracker(HRegionInfo hri) {
1238 if (closedRegionHandlerCalled != null) {
1239 closedRegionHandlerCalled.put(hri, new AtomicBoolean(true));
1240 }
1241 }
1242
1243 void updateOpenedRegionHandlerTracker(HRegionInfo hri) {
1244 if (openedRegionHandlerCalled != null) {
1245 openedRegionHandlerCalled.put(hri, new AtomicBoolean(true));
1246 }
1247 }
1248
1249
1250
1251
1252
1253
1254 void processFavoredNodes(List<HRegionInfo> regions) throws IOException {
1255 if (!shouldAssignRegionsWithFavoredNodes) return;
1256
1257
1258 Map<HRegionInfo, List<ServerName>> regionToFavoredNodes =
1259 new HashMap<HRegionInfo, List<ServerName>>();
1260 for (HRegionInfo region : regions) {
1261 regionToFavoredNodes.put(region,
1262 ((FavoredNodeLoadBalancer)this.balancer).getFavoredNodes(region));
1263 }
1264 FavoredNodeAssignmentHelper.updateMetaWithFavoredNodesInfo(regionToFavoredNodes,
1265 this.server.getConnection());
1266 }
1267
1268
1269
1270
1271
1272
1273
1274 @SuppressWarnings("deprecation")
1275 private void handleHBCK(RegionTransition rt) {
1276 String encodedName = HRegionInfo.encodeRegionName(rt.getRegionName());
1277 LOG.info("Handling HBCK triggered transition=" + rt.getEventType() +
1278 ", server=" + rt.getServerName() + ", region=" +
1279 HRegionInfo.prettyPrint(encodedName));
1280 RegionState regionState = regionStates.getRegionTransitionState(encodedName);
1281 switch (rt.getEventType()) {
1282 case M_ZK_REGION_OFFLINE:
1283 HRegionInfo regionInfo;
1284 if (regionState != null) {
1285 regionInfo = regionState.getRegion();
1286 } else {
1287 try {
1288 byte [] name = rt.getRegionName();
1289 Pair<HRegionInfo, ServerName> p = MetaTableAccessor.getRegion(
1290 this.server.getConnection(), name);
1291 regionInfo = p.getFirst();
1292 } catch (IOException e) {
1293 LOG.info("Exception reading hbase:meta doing HBCK repair operation", e);
1294 return;
1295 }
1296 }
1297 LOG.info("HBCK repair is triggering assignment of region=" +
1298 regionInfo.getRegionNameAsString());
1299
1300 assign(regionInfo, false);
1301 break;
1302
1303 default:
1304 LOG.warn("Received unexpected region state from HBCK: " + rt.toString());
1305 break;
1306 }
1307
1308 }
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324 @Override
1325 public void nodeCreated(String path) {
1326 handleAssignmentEvent(path);
1327 }
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341 @Override
1342 public void nodeDataChanged(String path) {
1343 handleAssignmentEvent(path);
1344 }
1345
1346
1347
1348
1349
1350 private final Set<String> regionsInProgress = new HashSet<String>();
1351
1352
1353 private final LinkedHashMultimap <String, RegionRunnable>
1354 zkEventWorkerWaitingList = LinkedHashMultimap.create();
1355
1356
1357
1358
1359 private interface RegionRunnable extends Runnable{
1360
1361
1362
1363 String getRegionName();
1364 }
1365
1366
1367
1368
1369
1370 protected void zkEventWorkersSubmit(final RegionRunnable regRunnable) {
1371
1372 synchronized (regionsInProgress) {
1373
1374
1375 if (regionsInProgress.contains(regRunnable.getRegionName())) {
1376 synchronized (zkEventWorkerWaitingList){
1377 zkEventWorkerWaitingList.put(regRunnable.getRegionName(), regRunnable);
1378 }
1379 return;
1380 }
1381
1382
1383 regionsInProgress.add(regRunnable.getRegionName());
1384 zkEventWorkers.submit(new Runnable() {
1385 @Override
1386 public void run() {
1387 try {
1388 regRunnable.run();
1389 } finally {
1390
1391
1392 synchronized (regionsInProgress) {
1393 regionsInProgress.remove(regRunnable.getRegionName());
1394 synchronized (zkEventWorkerWaitingList) {
1395 java.util.Set<RegionRunnable> waiting = zkEventWorkerWaitingList.get(
1396 regRunnable.getRegionName());
1397 if (!waiting.isEmpty()) {
1398
1399 RegionRunnable toSubmit = waiting.iterator().next();
1400 zkEventWorkerWaitingList.remove(toSubmit.getRegionName(), toSubmit);
1401 zkEventWorkersSubmit(toSubmit);
1402 }
1403 }
1404 }
1405 }
1406 }
1407 });
1408 }
1409 }
1410
1411 @Override
1412 public void nodeDeleted(final String path) {
1413 if (path.startsWith(watcher.assignmentZNode)) {
1414 final String regionName = ZKAssign.getRegionName(watcher, path);
1415 zkEventWorkersSubmit(new RegionRunnable() {
1416 @Override
1417 public String getRegionName() {
1418 return regionName;
1419 }
1420
1421 @Override
1422 public void run() {
1423 Lock lock = locker.acquireLock(regionName);
1424 try {
1425 RegionState rs = regionStates.getRegionTransitionState(regionName);
1426 if (rs == null) {
1427 rs = regionStates.getRegionState(regionName);
1428 if (rs == null || !rs.isMergingNew()) {
1429
1430 return;
1431 }
1432 }
1433
1434 HRegionInfo regionInfo = rs.getRegion();
1435 String regionNameStr = regionInfo.getRegionNameAsString();
1436 LOG.debug("Znode " + regionNameStr + " deleted, state: " + rs);
1437
1438 boolean disabled = getTableStateManager().isTableState(regionInfo.getTable(),
1439 ZooKeeperProtos.Table.State.DISABLED, ZooKeeperProtos.Table.State.DISABLING);
1440
1441 ServerName serverName = rs.getServerName();
1442 if (serverManager.isServerOnline(serverName)) {
1443 if (rs.isOnServer(serverName) && (rs.isOpened() || rs.isSplitting())) {
1444 synchronized (regionStates) {
1445 regionOnline(regionInfo, serverName);
1446 if (rs.isSplitting() && splitRegions.containsKey(regionInfo)) {
1447
1448
1449 HRegionInfo hri_a = splitRegions.get(regionInfo).getFirst();
1450 HRegionInfo hri_b = splitRegions.get(regionInfo).getSecond();
1451 if (!regionStates.isRegionInTransition(hri_a.getEncodedName())) {
1452 LOG.warn("Split daughter region not in transition " + hri_a);
1453 }
1454 if (!regionStates.isRegionInTransition(hri_b.getEncodedName())) {
1455 LOG.warn("Split daughter region not in transition" + hri_b);
1456 }
1457 regionOffline(hri_a);
1458 regionOffline(hri_b);
1459 splitRegions.remove(regionInfo);
1460 }
1461 if (disabled) {
1462
1463 LOG.info("Opened " + regionNameStr
1464 + "but this table is disabled, triggering close of region");
1465 unassign(regionInfo);
1466 }
1467 }
1468 } else if (rs.isMergingNew()) {
1469 synchronized (regionStates) {
1470 String p = regionInfo.getEncodedName();
1471 PairOfSameType<HRegionInfo> regions = mergingRegions.get(p);
1472 if (regions != null) {
1473 onlineMergingRegion(disabled, regions.getFirst(), serverName);
1474 onlineMergingRegion(disabled, regions.getSecond(), serverName);
1475 }
1476 }
1477 }
1478 }
1479 } finally {
1480 lock.unlock();
1481 }
1482 }
1483
1484 private void onlineMergingRegion(boolean disabled,
1485 final HRegionInfo hri, final ServerName serverName) {
1486 RegionState regionState = regionStates.getRegionState(hri);
1487 if (regionState != null && regionState.isMerging()
1488 && regionState.isOnServer(serverName)) {
1489 regionOnline(regionState.getRegion(), serverName);
1490 if (disabled) {
1491 unassign(hri);
1492 }
1493 }
1494 }
1495 });
1496 }
1497 }
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511 @Override
1512 public void nodeChildrenChanged(String path) {
1513 if (path.equals(watcher.assignmentZNode)) {
1514 zkEventWorkers.submit(new Runnable() {
1515 @Override
1516 public void run() {
1517 try {
1518
1519 List<String> children =
1520 ZKUtil.listChildrenAndWatchForNewChildren(
1521 watcher, watcher.assignmentZNode);
1522 if (children != null) {
1523 Stat stat = new Stat();
1524 for (String child : children) {
1525
1526
1527
1528 if (!regionStates.isRegionInTransition(child)) {
1529 ZKAssign.getDataAndWatch(watcher, child, stat);
1530 }
1531 }
1532 }
1533 } catch (KeeperException e) {
1534 server.abort("Unexpected ZK exception reading unassigned children", e);
1535 }
1536 }
1537 });
1538 }
1539 }
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550 void regionOnline(HRegionInfo regionInfo, ServerName sn) {
1551 regionOnline(regionInfo, sn, HConstants.NO_SEQNUM);
1552 }
1553
1554 void regionOnline(HRegionInfo regionInfo, ServerName sn, long openSeqNum) {
1555 numRegionsOpened.incrementAndGet();
1556 regionStates.regionOnline(regionInfo, sn, openSeqNum);
1557
1558
1559 clearRegionPlan(regionInfo);
1560 balancer.regionOnline(regionInfo, sn);
1561
1562
1563 sendRegionOpenedNotification(regionInfo, sn);
1564 }
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574 private void handleAssignmentEvent(final String path) {
1575 if (path.startsWith(watcher.assignmentZNode)) {
1576 final String regionName = ZKAssign.getRegionName(watcher, path);
1577
1578 zkEventWorkersSubmit(new RegionRunnable() {
1579 @Override
1580 public String getRegionName() {
1581 return regionName;
1582 }
1583
1584 @Override
1585 public void run() {
1586 try {
1587 Stat stat = new Stat();
1588 byte [] data = ZKAssign.getDataAndWatch(watcher, path, stat);
1589 if (data == null) return;
1590
1591 RegionTransition rt = RegionTransition.parseFrom(data);
1592
1593
1594
1595 BaseCoordinatedStateManager csm =
1596 (BaseCoordinatedStateManager) server.getCoordinatedStateManager();
1597 OpenRegionCoordination openRegionCoordination = csm.getOpenRegionCoordination();
1598
1599 ZkOpenRegionCoordination.ZkOpenRegionDetails zkOrd =
1600 new ZkOpenRegionCoordination.ZkOpenRegionDetails();
1601 zkOrd.setVersion(stat.getVersion());
1602 zkOrd.setServerName(csm.getServer().getServerName());
1603
1604 handleRegion(rt, openRegionCoordination, zkOrd);
1605 } catch (KeeperException e) {
1606 server.abort("Unexpected ZK exception reading unassigned node data", e);
1607 } catch (DeserializationException e) {
1608 server.abort("Unexpected exception deserializing node data", e);
1609 }
1610 }
1611 });
1612 }
1613 }
1614
1615
1616
1617
1618
1619
1620
1621
1622 public void regionOffline(final HRegionInfo regionInfo) {
1623 if (regionStates.isRegionInState(regionInfo, State.MERGED, State.SPLIT)) {
1624 LOG.info("Try to offline region " + regionInfo.getEncodedName() +
1625 ", which is at state " + regionStates.getRegionState(regionInfo).getState() + ", skip");
1626 return;
1627 }
1628 regionOffline(regionInfo, null);
1629 }
1630
1631 public void offlineDisabledRegion(HRegionInfo regionInfo) {
1632 if (useZKForAssignment) {
1633
1634 LOG.debug("Table being disabled so deleting ZK node and removing from " +
1635 "regions in transition, skipping assignment of region " +
1636 regionInfo.getRegionNameAsString());
1637 String encodedName = regionInfo.getEncodedName();
1638 deleteNodeInStates(encodedName, "closed", null,
1639 EventType.RS_ZK_REGION_CLOSED, EventType.M_ZK_REGION_OFFLINE);
1640 }
1641 replicasToClose.remove(regionInfo);
1642
1643 getRegionStates().updateRegionState(regionInfo, State.OFFLINE, null);
1644 regionOffline(regionInfo);
1645 }
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667 public void assign(HRegionInfo region, boolean setOfflineInZK) {
1668 assign(region, setOfflineInZK, false);
1669 }
1670
1671
1672
1673
1674 @VisibleForTesting
1675 public void assign(HRegionInfo region,
1676 boolean setOfflineInZK, boolean forceNewPlan) {
1677 if (isDisabledorDisablingRegionInRIT(region)) {
1678 return;
1679 }
1680 String encodedName = region.getEncodedName();
1681 Lock lock = locker.acquireLock(encodedName);
1682 try {
1683 RegionState state = forceRegionStateToOffline(region, forceNewPlan);
1684 if (state != null) {
1685 if (regionStates.wasRegionOnDeadServer(encodedName)) {
1686 LOG.info("Skip assigning " + region.getRegionNameAsString()
1687 + ", it's host " + regionStates.getLastRegionServerOfRegion(encodedName)
1688 + " is dead but not processed yet");
1689 return;
1690 }
1691 assign(state, setOfflineInZK && useZKForAssignment, forceNewPlan);
1692 }
1693 } finally {
1694 lock.unlock();
1695 }
1696 }
1697
1698
1699
1700
1701
1702
1703
1704 boolean assign(final ServerName destination, final List<HRegionInfo> regions)
1705 throws InterruptedException {
1706 long startTime = EnvironmentEdgeManager.currentTime();
1707 try {
1708 int regionCount = regions.size();
1709 if (regionCount == 0) {
1710 return true;
1711 }
1712 LOG.info("Assigning " + regionCount + " region(s) to " + destination.toString());
1713 Set<String> encodedNames = new HashSet<String>(regionCount);
1714 for (HRegionInfo region : regions) {
1715 encodedNames.add(region.getEncodedName());
1716 }
1717
1718 List<HRegionInfo> failedToOpenRegions = new ArrayList<HRegionInfo>();
1719 Map<String, Lock> locks = locker.acquireLocks(encodedNames);
1720 try {
1721 AtomicInteger counter = new AtomicInteger(0);
1722 Map<String, Integer> offlineNodesVersions = new ConcurrentHashMap<String, Integer>();
1723 OfflineCallback cb = new OfflineCallback(
1724 watcher, destination, counter, offlineNodesVersions);
1725 Map<String, RegionPlan> plans = new HashMap<String, RegionPlan>(regions.size());
1726 List<RegionState> states = new ArrayList<RegionState>(regions.size());
1727 for (HRegionInfo region : regions) {
1728 String encodedName = region.getEncodedName();
1729 if (!isDisabledorDisablingRegionInRIT(region)) {
1730 RegionState state = forceRegionStateToOffline(region, false);
1731 boolean onDeadServer = false;
1732 if (state != null) {
1733 if (regionStates.wasRegionOnDeadServer(encodedName)) {
1734 LOG.info("Skip assigning " + region.getRegionNameAsString()
1735 + ", it's host " + regionStates.getLastRegionServerOfRegion(encodedName)
1736 + " is dead but not processed yet");
1737 onDeadServer = true;
1738 } else if (!useZKForAssignment
1739 || asyncSetOfflineInZooKeeper(state, cb, destination)) {
1740 RegionPlan plan = new RegionPlan(region, state.getServerName(), destination);
1741 plans.put(encodedName, plan);
1742 states.add(state);
1743 continue;
1744 }
1745 }
1746
1747 if (!onDeadServer) {
1748 LOG.info("failed to force region state to offline or "
1749 + "failed to set it offline in ZK, will reassign later: " + region);
1750 failedToOpenRegions.add(region);
1751 }
1752 }
1753
1754
1755 Lock lock = locks.remove(encodedName);
1756 lock.unlock();
1757 }
1758
1759 if (useZKForAssignment) {
1760
1761 int total = states.size();
1762 for (int oldCounter = 0; !server.isStopped();) {
1763 int count = counter.get();
1764 if (oldCounter != count) {
1765 LOG.debug(destination.toString() + " unassigned znodes=" + count +
1766 " of total=" + total + "; oldCounter=" + oldCounter);
1767 oldCounter = count;
1768 }
1769 if (count >= total) break;
1770 Thread.sleep(5);
1771 }
1772 }
1773
1774 if (server.isStopped()) {
1775 return false;
1776 }
1777
1778
1779
1780 this.addPlans(plans);
1781
1782 List<Triple<HRegionInfo, Integer, List<ServerName>>> regionOpenInfos =
1783 new ArrayList<Triple<HRegionInfo, Integer, List<ServerName>>>(states.size());
1784 for (RegionState state: states) {
1785 HRegionInfo region = state.getRegion();
1786 String encodedRegionName = region.getEncodedName();
1787 Integer nodeVersion = offlineNodesVersions.get(encodedRegionName);
1788 if (useZKForAssignment && (nodeVersion == null || nodeVersion == -1)) {
1789 LOG.warn("failed to offline in zookeeper: " + region);
1790 failedToOpenRegions.add(region);
1791 Lock lock = locks.remove(encodedRegionName);
1792 lock.unlock();
1793 } else {
1794 regionStates.updateRegionState(
1795 region, State.PENDING_OPEN, destination);
1796 List<ServerName> favoredNodes = ServerName.EMPTY_SERVER_LIST;
1797 if (this.shouldAssignRegionsWithFavoredNodes) {
1798 favoredNodes = ((FavoredNodeLoadBalancer)this.balancer).getFavoredNodes(region);
1799 }
1800 regionOpenInfos.add(new Triple<HRegionInfo, Integer, List<ServerName>>(
1801 region, nodeVersion, favoredNodes));
1802 }
1803 }
1804
1805
1806 try {
1807
1808
1809 long maxWaitTime = System.currentTimeMillis() +
1810 this.server.getConfiguration().
1811 getLong("hbase.regionserver.rpc.startup.waittime", 60000);
1812 for (int i = 1; i <= maximumAttempts && !server.isStopped(); i++) {
1813 try {
1814
1815 if (regionOpenInfos.isEmpty()) {
1816 break;
1817 }
1818 List<RegionOpeningState> regionOpeningStateList = serverManager
1819 .sendRegionOpen(destination, regionOpenInfos);
1820 if (regionOpeningStateList == null) {
1821
1822 return false;
1823 }
1824 for (int k = 0, n = regionOpeningStateList.size(); k < n; k++) {
1825 RegionOpeningState openingState = regionOpeningStateList.get(k);
1826 if (openingState != RegionOpeningState.OPENED) {
1827 HRegionInfo region = regionOpenInfos.get(k).getFirst();
1828 if (openingState == RegionOpeningState.ALREADY_OPENED) {
1829 processAlreadyOpenedRegion(region, destination);
1830 } else if (openingState == RegionOpeningState.FAILED_OPENING) {
1831
1832 failedToOpenRegions.add(region);
1833 } else {
1834 LOG.warn("THIS SHOULD NOT HAPPEN: unknown opening state "
1835 + openingState + " in assigning region " + region);
1836 }
1837 }
1838 }
1839 break;
1840 } catch (IOException e) {
1841 if (e instanceof RemoteException) {
1842 e = ((RemoteException)e).unwrapRemoteException();
1843 }
1844 if (e instanceof RegionServerStoppedException) {
1845 LOG.warn("The region server was shut down, ", e);
1846
1847 return false;
1848 } else if (e instanceof ServerNotRunningYetException) {
1849 long now = System.currentTimeMillis();
1850 if (now < maxWaitTime) {
1851 LOG.debug("Server is not yet up; waiting up to " +
1852 (maxWaitTime - now) + "ms", e);
1853 Thread.sleep(100);
1854 i--;
1855 continue;
1856 }
1857 } else if (e instanceof java.net.SocketTimeoutException
1858 && this.serverManager.isServerOnline(destination)) {
1859
1860
1861
1862
1863 if (LOG.isDebugEnabled()) {
1864 LOG.debug("Bulk assigner openRegion() to " + destination
1865 + " has timed out, but the regions might"
1866 + " already be opened on it.", e);
1867 }
1868
1869 Thread.sleep(100);
1870 i--;
1871 continue;
1872 }
1873 throw e;
1874 }
1875 }
1876 } catch (IOException e) {
1877
1878 LOG.info("Unable to communicate with " + destination
1879 + " in order to assign regions, ", e);
1880 return false;
1881 }
1882 } finally {
1883 for (Lock lock : locks.values()) {
1884 lock.unlock();
1885 }
1886 }
1887
1888 if (!failedToOpenRegions.isEmpty()) {
1889 for (HRegionInfo region : failedToOpenRegions) {
1890 if (!regionStates.isRegionOnline(region)) {
1891 invokeAssign(region);
1892 }
1893 }
1894 }
1895
1896
1897 ArrayList<HRegionInfo> userRegionSet = new ArrayList<HRegionInfo>(regions.size());
1898 for (HRegionInfo region: regions) {
1899 if (!region.getTable().isSystemTable()) {
1900 userRegionSet.add(region);
1901 }
1902 }
1903 if (!waitForAssignment(userRegionSet, true, userRegionSet.size(),
1904 System.currentTimeMillis())) {
1905 LOG.debug("some user regions are still in transition: " + userRegionSet);
1906 }
1907 LOG.debug("Bulk assigning done for " + destination);
1908 return true;
1909 } finally {
1910 metricsAssignmentManager.updateBulkAssignTime(EnvironmentEdgeManager.currentTime() - startTime);
1911 }
1912 }
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924 private void unassign(final HRegionInfo region,
1925 final RegionState state, final int versionOfClosingNode,
1926 final ServerName dest, final boolean transitionInZK,
1927 final ServerName src) {
1928 ServerName server = src;
1929 if (state != null) {
1930 server = state.getServerName();
1931 }
1932 long maxWaitTime = -1;
1933 for (int i = 1; i <= this.maximumAttempts; i++) {
1934 if (this.server.isStopped() || this.server.isAborted()) {
1935 LOG.debug("Server stopped/aborted; skipping unassign of " + region);
1936 return;
1937 }
1938
1939 if (!serverManager.isServerOnline(server)) {
1940 LOG.debug("Offline " + region.getRegionNameAsString()
1941 + ", no need to unassign since it's on a dead server: " + server);
1942 if (transitionInZK) {
1943
1944 deleteClosingOrClosedNode(region, server);
1945 }
1946 if (state != null) {
1947 regionOffline(region);
1948 }
1949 return;
1950 }
1951 try {
1952
1953 if (serverManager.sendRegionClose(server, region,
1954 versionOfClosingNode, dest, transitionInZK)) {
1955 LOG.debug("Sent CLOSE to " + server + " for region " +
1956 region.getRegionNameAsString());
1957 if (useZKForAssignment && !transitionInZK && state != null) {
1958
1959
1960 unassign(region, state, versionOfClosingNode,
1961 dest, transitionInZK, src);
1962 }
1963 return;
1964 }
1965
1966
1967 LOG.warn("Server " + server + " region CLOSE RPC returned false for " +
1968 region.getRegionNameAsString());
1969 } catch (Throwable t) {
1970 long sleepTime = 0;
1971 Configuration conf = this.server.getConfiguration();
1972 if (t instanceof RemoteException) {
1973 t = ((RemoteException)t).unwrapRemoteException();
1974 }
1975 boolean logRetries = true;
1976 if (t instanceof RegionServerAbortedException
1977 || t instanceof RegionServerStoppedException
1978 || t instanceof ServerNotRunningYetException) {
1979
1980
1981 sleepTime = 1 + conf.getInt(RpcClient.FAILED_SERVER_EXPIRY_KEY,
1982 RpcClient.FAILED_SERVER_EXPIRY_DEFAULT);
1983
1984 } else if (t instanceof NotServingRegionException) {
1985 LOG.debug("Offline " + region.getRegionNameAsString()
1986 + ", it's not any more on " + server, t);
1987 if (transitionInZK) {
1988 deleteClosingOrClosedNode(region, server);
1989 }
1990 if (state != null) {
1991 regionOffline(region);
1992 }
1993 return;
1994 } else if ((t instanceof FailedServerException) || (state != null &&
1995 t instanceof RegionAlreadyInTransitionException)) {
1996 if(t instanceof FailedServerException) {
1997 sleepTime = 1 + conf.getInt(RpcClient.FAILED_SERVER_EXPIRY_KEY,
1998 RpcClient.FAILED_SERVER_EXPIRY_DEFAULT);
1999 } else {
2000
2001 LOG.debug("update " + state + " the timestamp.");
2002 state.updateTimestampToNow();
2003 if (maxWaitTime < 0) {
2004 maxWaitTime =
2005 EnvironmentEdgeManager.currentTime()
2006 + conf.getLong(ALREADY_IN_TRANSITION_WAITTIME,
2007 DEFAULT_ALREADY_IN_TRANSITION_WAITTIME);
2008 }
2009 long now = EnvironmentEdgeManager.currentTime();
2010 if (now < maxWaitTime) {
2011 LOG.debug("Region is already in transition; "
2012 + "waiting up to " + (maxWaitTime - now) + "ms", t);
2013 sleepTime = 100;
2014 i--;
2015 logRetries = false;
2016 }
2017 }
2018 }
2019
2020 try {
2021 if (sleepTime > 0) {
2022 Thread.sleep(sleepTime);
2023 }
2024 } catch (InterruptedException ie) {
2025 LOG.warn("Failed to unassign "
2026 + region.getRegionNameAsString() + " since interrupted", ie);
2027 Thread.currentThread().interrupt();
2028 if (state != null) {
2029 regionStates.updateRegionState(region, State.FAILED_CLOSE);
2030 }
2031 return;
2032 }
2033
2034 if (logRetries) {
2035 LOG.info("Server " + server + " returned " + t + " for "
2036 + region.getRegionNameAsString() + ", try=" + i
2037 + " of " + this.maximumAttempts, t);
2038
2039 }
2040 }
2041 }
2042
2043 if (state != null) {
2044 regionStates.updateRegionState(region, State.FAILED_CLOSE);
2045 }
2046 }
2047
2048
2049
2050
2051 private RegionState forceRegionStateToOffline(
2052 final HRegionInfo region, final boolean forceNewPlan) {
2053 RegionState state = regionStates.getRegionState(region);
2054 if (state == null) {
2055 LOG.warn("Assigning but not in region states: " + region);
2056 state = regionStates.createRegionState(region);
2057 }
2058
2059 ServerName sn = state.getServerName();
2060 if (forceNewPlan && LOG.isDebugEnabled()) {
2061 LOG.debug("Force region state offline " + state);
2062 }
2063
2064 switch (state.getState()) {
2065 case OPEN:
2066 case OPENING:
2067 case PENDING_OPEN:
2068 case CLOSING:
2069 case PENDING_CLOSE:
2070 if (!forceNewPlan) {
2071 LOG.debug("Skip assigning " +
2072 region + ", it is already " + state);
2073 return null;
2074 }
2075 case FAILED_CLOSE:
2076 case FAILED_OPEN:
2077 unassign(region, state, -1, null, false, null);
2078 state = regionStates.getRegionState(region);
2079 if (state.isFailedClose()) {
2080
2081
2082 LOG.info("Skip assigning " +
2083 region + ", we couldn't close it: " + state);
2084 return null;
2085 }
2086 case OFFLINE:
2087
2088
2089
2090
2091
2092
2093
2094
2095 if (useZKForAssignment
2096 && regionStates.isServerDeadAndNotProcessed(sn)
2097 && wasRegionOnDeadServerByMeta(region, sn)) {
2098 if (!regionStates.isRegionInTransition(region)) {
2099 LOG.info("Updating the state to " + State.OFFLINE + " to allow to be reassigned by SSH");
2100 regionStates.updateRegionState(region, State.OFFLINE);
2101 }
2102 LOG.info("Skip assigning " + region.getRegionNameAsString()
2103 + ", it is on a dead but not processed yet server: " + sn);
2104 return null;
2105 }
2106 case CLOSED:
2107 break;
2108 default:
2109 LOG.error("Trying to assign region " + region
2110 + ", which is " + state);
2111 return null;
2112 }
2113 return state;
2114 }
2115
2116 @SuppressWarnings("deprecation")
2117 protected boolean wasRegionOnDeadServerByMeta(
2118 final HRegionInfo region, final ServerName sn) {
2119 try {
2120 if (region.isMetaRegion()) {
2121 ServerName server = this.server.getMetaTableLocator().
2122 getMetaRegionLocation(this.server.getZooKeeper());
2123 return regionStates.isServerDeadAndNotProcessed(server);
2124 }
2125 while (!server.isStopped()) {
2126 try {
2127 this.server.getMetaTableLocator().waitMetaRegionLocation(server.getZooKeeper());
2128 Result r = MetaTableAccessor.getRegionResult(server.getConnection(),
2129 region.getRegionName());
2130 if (r == null || r.isEmpty()) return false;
2131 ServerName server = HRegionInfo.getServerName(r);
2132 return regionStates.isServerDeadAndNotProcessed(server);
2133 } catch (IOException ioe) {
2134 LOG.info("Received exception accessing hbase:meta during force assign "
2135 + region.getRegionNameAsString() + ", retrying", ioe);
2136 }
2137 }
2138 } catch (InterruptedException e) {
2139 Thread.currentThread().interrupt();
2140 LOG.info("Interrupted accessing hbase:meta", e);
2141 }
2142
2143 return regionStates.isServerDeadAndNotProcessed(sn);
2144 }
2145
2146
2147
2148
2149
2150
2151
2152 public void assign(RegionState state,
2153 boolean setOfflineInZK, final boolean forceNewPlan) {
2154 long startTime = EnvironmentEdgeManager.currentTime();
2155 try {
2156 Configuration conf = server.getConfiguration();
2157 RegionState currentState = state;
2158 int versionOfOfflineNode = -1;
2159 RegionPlan plan = null;
2160 long maxWaitTime = -1;
2161 HRegionInfo region = state.getRegion();
2162 RegionOpeningState regionOpenState;
2163 Throwable previousException = null;
2164 for (int i = 1; i <= maximumAttempts; i++) {
2165 if (server.isStopped() || server.isAborted()) {
2166 LOG.info("Skip assigning " + region.getRegionNameAsString()
2167 + ", the server is stopped/aborted");
2168 return;
2169 }
2170
2171 if (plan == null) {
2172 try {
2173 plan = getRegionPlan(region, forceNewPlan);
2174 } catch (HBaseIOException e) {
2175 LOG.warn("Failed to get region plan", e);
2176 }
2177 }
2178
2179 if (plan == null) {
2180 LOG.warn("Unable to determine a plan to assign " + region);
2181
2182
2183 if (region.isMetaRegion()) {
2184 if (i == maximumAttempts) {
2185 i = 0;
2186
2187 LOG.warn("Unable to determine a plan to assign a hbase:meta region " + region +
2188 " after maximumAttempts (" + this.maximumAttempts +
2189 "). Reset attempts count and continue retrying.");
2190 }
2191 waitForRetryingMetaAssignment();
2192 continue;
2193 }
2194
2195 regionStates.updateRegionState(region, State.FAILED_OPEN);
2196 return;
2197 }
2198 if (setOfflineInZK && versionOfOfflineNode == -1) {
2199 LOG.info("Setting node as OFFLINED in ZooKeeper for region " + region);
2200
2201
2202 versionOfOfflineNode = setOfflineInZooKeeper(currentState, plan.getDestination());
2203 if (versionOfOfflineNode != -1) {
2204 if (isDisabledorDisablingRegionInRIT(region)) {
2205 return;
2206 }
2207
2208
2209
2210
2211
2212
2213 TableName tableName = region.getTable();
2214 if (!tableStateManager.isTableState(tableName,
2215 ZooKeeperProtos.Table.State.ENABLED, ZooKeeperProtos.Table.State.ENABLING)) {
2216 LOG.debug("Setting table " + tableName + " to ENABLED state.");
2217 setEnabledTable(tableName);
2218 }
2219 }
2220 }
2221 if (setOfflineInZK && versionOfOfflineNode == -1) {
2222 LOG.info("Unable to set offline in ZooKeeper to assign " + region);
2223
2224
2225
2226
2227 if (!server.isAborted()) {
2228 continue;
2229 }
2230 }
2231 LOG.info("Assigning " + region.getRegionNameAsString() +
2232 " to " + plan.getDestination().toString());
2233
2234 currentState = regionStates.updateRegionState(region,
2235 State.PENDING_OPEN, plan.getDestination());
2236
2237 boolean needNewPlan;
2238 final String assignMsg = "Failed assignment of " + region.getRegionNameAsString() +
2239 " to " + plan.getDestination();
2240 try {
2241 List<ServerName> favoredNodes = ServerName.EMPTY_SERVER_LIST;
2242 if (this.shouldAssignRegionsWithFavoredNodes) {
2243 favoredNodes = ((FavoredNodeLoadBalancer)this.balancer).getFavoredNodes(region);
2244 }
2245 regionOpenState = serverManager.sendRegionOpen(
2246 plan.getDestination(), region, versionOfOfflineNode, favoredNodes);
2247
2248 if (regionOpenState == RegionOpeningState.FAILED_OPENING) {
2249
2250 needNewPlan = true;
2251 LOG.warn(assignMsg + ", regionserver says 'FAILED_OPENING', " +
2252 " trying to assign elsewhere instead; " +
2253 "try=" + i + " of " + this.maximumAttempts);
2254 } else {
2255
2256 if (regionOpenState == RegionOpeningState.ALREADY_OPENED) {
2257 processAlreadyOpenedRegion(region, plan.getDestination());
2258 }
2259 return;
2260 }
2261
2262 } catch (Throwable t) {
2263 if (t instanceof RemoteException) {
2264 t = ((RemoteException) t).unwrapRemoteException();
2265 }
2266 previousException = t;
2267
2268
2269
2270
2271 boolean hold = (t instanceof RegionAlreadyInTransitionException ||
2272 t instanceof ServerNotRunningYetException);
2273
2274
2275
2276
2277
2278
2279 boolean retry = !hold && (t instanceof java.net.SocketTimeoutException
2280 && this.serverManager.isServerOnline(plan.getDestination()));
2281
2282
2283 if (hold) {
2284 LOG.warn(assignMsg + ", waiting a little before trying on the same region server " +
2285 "try=" + i + " of " + this.maximumAttempts, t);
2286
2287 if (maxWaitTime < 0) {
2288 if (t instanceof RegionAlreadyInTransitionException) {
2289 maxWaitTime = EnvironmentEdgeManager.currentTime()
2290 + this.server.getConfiguration().getLong(ALREADY_IN_TRANSITION_WAITTIME,
2291 DEFAULT_ALREADY_IN_TRANSITION_WAITTIME);
2292 } else {
2293 maxWaitTime = EnvironmentEdgeManager.currentTime()
2294 + this.server.getConfiguration().getLong(
2295 "hbase.regionserver.rpc.startup.waittime", 60000);
2296 }
2297 }
2298 try {
2299 needNewPlan = false;
2300 long now = EnvironmentEdgeManager.currentTime();
2301 if (now < maxWaitTime) {
2302 LOG.debug("Server is not yet up or region is already in transition; "
2303 + "waiting up to " + (maxWaitTime - now) + "ms", t);
2304 Thread.sleep(100);
2305 i--;
2306 } else if (!(t instanceof RegionAlreadyInTransitionException)) {
2307 LOG.debug("Server is not up for a while; try a new one", t);
2308 needNewPlan = true;
2309 }
2310 } catch (InterruptedException ie) {
2311 LOG.warn("Failed to assign "
2312 + region.getRegionNameAsString() + " since interrupted", ie);
2313 regionStates.updateRegionState(region, State.FAILED_OPEN);
2314 Thread.currentThread().interrupt();
2315 return;
2316 }
2317 } else if (retry) {
2318 needNewPlan = false;
2319 i--;
2320 LOG.warn(assignMsg + ", trying to assign to the same region server due ", t);
2321 } else {
2322 needNewPlan = true;
2323 LOG.warn(assignMsg + ", trying to assign elsewhere instead;" +
2324 " try=" + i + " of " + this.maximumAttempts, t);
2325 }
2326 }
2327
2328 if (i == this.maximumAttempts) {
2329
2330 if (region.isMetaRegion()) {
2331 i = 0;
2332 LOG.warn(assignMsg +
2333 ", trying to assign a hbase:meta region reached to maximumAttempts (" +
2334 this.maximumAttempts + "). Reset attempt counts and continue retrying.");
2335 waitForRetryingMetaAssignment();
2336 }
2337 else {
2338
2339
2340 continue;
2341 }
2342 }
2343
2344
2345
2346
2347 if (needNewPlan) {
2348
2349
2350
2351
2352 RegionPlan newPlan = null;
2353 try {
2354 newPlan = getRegionPlan(region, true);
2355 } catch (HBaseIOException e) {
2356 LOG.warn("Failed to get region plan", e);
2357 }
2358 if (newPlan == null) {
2359 regionStates.updateRegionState(region, State.FAILED_OPEN);
2360 LOG.warn("Unable to find a viable location to assign region " +
2361 region.getRegionNameAsString());
2362 return;
2363 }
2364
2365 if (plan != newPlan && !plan.getDestination().equals(newPlan.getDestination())) {
2366
2367
2368
2369 LOG.info("Region assignment plan changed from " + plan.getDestination() + " to "
2370 + newPlan.getDestination() + " server.");
2371 currentState = regionStates.updateRegionState(region, State.OFFLINE);
2372 versionOfOfflineNode = -1;
2373 if (useZKForAssignment) {
2374 setOfflineInZK = true;
2375 }
2376 plan = newPlan;
2377 } else if(plan.getDestination().equals(newPlan.getDestination()) &&
2378 previousException instanceof FailedServerException) {
2379 try {
2380 LOG.info("Trying to re-assign " + region.getRegionNameAsString() +
2381 " to the same failed server.");
2382 Thread.sleep(1 + conf.getInt(RpcClient.FAILED_SERVER_EXPIRY_KEY,
2383 RpcClient.FAILED_SERVER_EXPIRY_DEFAULT));
2384 } catch (InterruptedException ie) {
2385 LOG.warn("Failed to assign "
2386 + region.getRegionNameAsString() + " since interrupted", ie);
2387 regionStates.updateRegionState(region, State.FAILED_OPEN);
2388 Thread.currentThread().interrupt();
2389 return;
2390 }
2391 }
2392 }
2393 }
2394
2395 regionStates.updateRegionState(region, State.FAILED_OPEN);
2396 } finally {
2397 metricsAssignmentManager.updateAssignmentTime(EnvironmentEdgeManager.currentTime() - startTime);
2398 }
2399 }
2400
2401 private void processAlreadyOpenedRegion(HRegionInfo region, ServerName sn) {
2402
2403
2404
2405 LOG.debug("ALREADY_OPENED " + region.getRegionNameAsString()
2406 + " to " + sn);
2407 String encodedName = region.getEncodedName();
2408
2409
2410
2411 if(useZKForAssignment){
2412 String node = ZKAssign.getNodeName(watcher, encodedName);
2413 Stat stat = new Stat();
2414 try {
2415 byte[] existingBytes = ZKUtil.getDataNoWatch(watcher, node, stat);
2416 if(existingBytes!=null){
2417 RegionTransition rt= RegionTransition.parseFrom(existingBytes);
2418 EventType et = rt.getEventType();
2419 if (et.equals(EventType.RS_ZK_REGION_OPENED)) {
2420 LOG.debug("ALREADY_OPENED " + region.getRegionNameAsString()
2421 + " and node in "+et+" state");
2422 return;
2423 }
2424 }
2425 } catch (KeeperException ke) {
2426 LOG.warn("Unexpected ZK exception getData " + node
2427 + " node for the region " + encodedName, ke);
2428 } catch (DeserializationException e) {
2429 LOG.warn("Get RegionTransition from zk deserialization failed! ", e);
2430 }
2431
2432 deleteNodeInStates(encodedName, "offline", sn, EventType.M_ZK_REGION_OFFLINE);
2433 }
2434
2435 regionStates.regionOnline(region, sn);
2436 }
2437
2438 private boolean isDisabledorDisablingRegionInRIT(final HRegionInfo region) {
2439 if (this.tableStateManager.isTableState(region.getTable(),
2440 ZooKeeperProtos.Table.State.DISABLED,
2441 ZooKeeperProtos.Table.State.DISABLING) || replicasToClose.contains(region)) {
2442 LOG.info("Table " + region.getTable() + " is disabled or disabling;"
2443 + " skipping assign of " + region.getRegionNameAsString());
2444 offlineDisabledRegion(region);
2445 return true;
2446 }
2447 return false;
2448 }
2449
2450
2451
2452
2453
2454
2455
2456
2457 private int setOfflineInZooKeeper(final RegionState state, final ServerName destination) {
2458 if (!state.isClosed() && !state.isOffline()) {
2459 String msg = "Unexpected state : " + state + " .. Cannot transit it to OFFLINE.";
2460 this.server.abort(msg, new IllegalStateException(msg));
2461 return -1;
2462 }
2463 regionStates.updateRegionState(state.getRegion(), State.OFFLINE);
2464 int versionOfOfflineNode;
2465 try {
2466
2467 versionOfOfflineNode = ZKAssign.createOrForceNodeOffline(watcher,
2468 state.getRegion(), destination);
2469 if (versionOfOfflineNode == -1) {
2470 LOG.warn("Attempted to create/force node into OFFLINE state before "
2471 + "completing assignment but failed to do so for " + state);
2472 return -1;
2473 }
2474 } catch (KeeperException e) {
2475 server.abort("Unexpected ZK exception creating/setting node OFFLINE", e);
2476 return -1;
2477 }
2478 return versionOfOfflineNode;
2479 }
2480
2481
2482
2483
2484
2485
2486 private RegionPlan getRegionPlan(final HRegionInfo region,
2487 final boolean forceNewPlan) throws HBaseIOException {
2488 return getRegionPlan(region, null, forceNewPlan);
2489 }
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500 private RegionPlan getRegionPlan(final HRegionInfo region,
2501 final ServerName serverToExclude, final boolean forceNewPlan) throws HBaseIOException {
2502
2503 final String encodedName = region.getEncodedName();
2504 final List<ServerName> destServers =
2505 serverManager.createDestinationServersList(serverToExclude);
2506
2507 if (destServers.isEmpty()){
2508 LOG.warn("Can't move " + encodedName +
2509 ", there is no destination server available.");
2510 return null;
2511 }
2512
2513 RegionPlan randomPlan = null;
2514 boolean newPlan = false;
2515 RegionPlan existingPlan;
2516
2517 synchronized (this.regionPlans) {
2518 existingPlan = this.regionPlans.get(encodedName);
2519
2520 if (existingPlan != null && existingPlan.getDestination() != null) {
2521 LOG.debug("Found an existing plan for " + region.getRegionNameAsString()
2522 + " destination server is " + existingPlan.getDestination() +
2523 " accepted as a dest server = " + destServers.contains(existingPlan.getDestination()));
2524 }
2525
2526 if (forceNewPlan
2527 || existingPlan == null
2528 || existingPlan.getDestination() == null
2529 || !destServers.contains(existingPlan.getDestination())) {
2530 newPlan = true;
2531 }
2532 }
2533
2534 if (newPlan) {
2535 ServerName destination = balancer.randomAssignment(region, destServers);
2536 if (destination == null) {
2537 LOG.warn("Can't find a destination for " + encodedName);
2538 return null;
2539 }
2540 synchronized (this.regionPlans) {
2541 randomPlan = new RegionPlan(region, null, destination);
2542 if (!region.isMetaTable() && shouldAssignRegionsWithFavoredNodes) {
2543 List<HRegionInfo> regions = new ArrayList<HRegionInfo>(1);
2544 regions.add(region);
2545 try {
2546 processFavoredNodes(regions);
2547 } catch (IOException ie) {
2548 LOG.warn("Ignoring exception in processFavoredNodes " + ie);
2549 }
2550 }
2551 this.regionPlans.put(encodedName, randomPlan);
2552 }
2553 LOG.debug("No previous transition plan found (or ignoring " + "an existing plan) for "
2554 + region.getRegionNameAsString() + "; generated random plan=" + randomPlan + "; "
2555 + destServers.size() + " (online=" + serverManager.getOnlineServers().size()
2556 + ") available servers, forceNewPlan=" + forceNewPlan);
2557 return randomPlan;
2558 }
2559 LOG.debug("Using pre-existing plan for " +
2560 region.getRegionNameAsString() + "; plan=" + existingPlan);
2561 return existingPlan;
2562 }
2563
2564
2565
2566
2567 private void waitForRetryingMetaAssignment() {
2568 try {
2569 Thread.sleep(this.sleepTimeBeforeRetryingMetaAssignment);
2570 } catch (InterruptedException e) {
2571 LOG.error("Got exception while waiting for hbase:meta assignment");
2572 Thread.currentThread().interrupt();
2573 }
2574 }
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589 public void unassign(HRegionInfo region) {
2590 unassign(region, false);
2591 }
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608 public void unassign(HRegionInfo region, boolean force, ServerName dest) {
2609
2610 LOG.debug("Starting unassign of " + region.getRegionNameAsString()
2611 + " (offlining), current state: " + regionStates.getRegionState(region));
2612
2613 String encodedName = region.getEncodedName();
2614
2615 int versionOfClosingNode = -1;
2616
2617
2618 ReentrantLock lock = locker.acquireLock(encodedName);
2619 RegionState state = regionStates.getRegionTransitionState(encodedName);
2620 boolean reassign = true;
2621 try {
2622 if (state == null) {
2623
2624
2625 state = regionStates.getRegionState(encodedName);
2626 if (state != null && state.isUnassignable()) {
2627 LOG.info("Attempting to unassign " + state + ", ignored");
2628
2629 return;
2630 }
2631
2632 try {
2633 if (state == null || state.getServerName() == null) {
2634
2635
2636 LOG.warn("Attempting to unassign a region not in RegionStates "
2637 + region.getRegionNameAsString() + ", offlined");
2638 regionOffline(region);
2639 return;
2640 }
2641 if (useZKForAssignment) {
2642 versionOfClosingNode = ZKAssign.createNodeClosing(
2643 watcher, region, state.getServerName());
2644 if (versionOfClosingNode == -1) {
2645 LOG.info("Attempting to unassign " +
2646 region.getRegionNameAsString() + " but ZK closing node "
2647 + "can't be created.");
2648 reassign = false;
2649 return;
2650 }
2651 }
2652 } catch (KeeperException e) {
2653 if (e instanceof NodeExistsException) {
2654
2655
2656
2657
2658 NodeExistsException nee = (NodeExistsException)e;
2659 String path = nee.getPath();
2660 try {
2661 if (isSplitOrSplittingOrMergedOrMerging(path)) {
2662 LOG.debug(path + " is SPLIT or SPLITTING or MERGED or MERGING; " +
2663 "skipping unassign because region no longer exists -- its split or merge");
2664 reassign = false;
2665 return;
2666 }
2667 } catch (KeeperException.NoNodeException ke) {
2668 LOG.warn("Failed getData on SPLITTING/SPLIT at " + path +
2669 "; presuming split and that the region to unassign, " +
2670 encodedName + ", no longer exists -- confirm", ke);
2671 return;
2672 } catch (KeeperException ke) {
2673 LOG.error("Unexpected zk state", ke);
2674 } catch (DeserializationException de) {
2675 LOG.error("Failed parse", de);
2676 }
2677 }
2678
2679 server.abort("Unexpected ZK exception creating node CLOSING", e);
2680 reassign = false;
2681 return;
2682 }
2683 state = regionStates.updateRegionState(region, State.PENDING_CLOSE);
2684 } else if (state.isFailedOpen()) {
2685
2686 regionOffline(region);
2687 return;
2688 } else if (force && state.isPendingCloseOrClosing()) {
2689 LOG.debug("Attempting to unassign " + region.getRegionNameAsString() +
2690 " which is already " + state.getState() +
2691 " but forcing to send a CLOSE RPC again ");
2692 if (state.isFailedClose()) {
2693 state = regionStates.updateRegionState(region, State.PENDING_CLOSE);
2694 }
2695 state.updateTimestampToNow();
2696 } else {
2697 LOG.debug("Attempting to unassign " +
2698 region.getRegionNameAsString() + " but it is " +
2699 "already in transition (" + state.getState() + ", force=" + force + ")");
2700 return;
2701 }
2702
2703 unassign(region, state, versionOfClosingNode, dest, useZKForAssignment, null);
2704 } finally {
2705 lock.unlock();
2706
2707
2708 if (!replicasToClose.contains(region) && reassign && regionStates.isRegionOffline(region)) {
2709 assign(region, true);
2710 }
2711 }
2712 }
2713
2714 public void unassign(HRegionInfo region, boolean force){
2715 unassign(region, force, null);
2716 }
2717
2718
2719
2720
2721 public void deleteClosingOrClosedNode(HRegionInfo region, ServerName sn) {
2722 String encodedName = region.getEncodedName();
2723 deleteNodeInStates(encodedName, "closing", sn, EventType.M_ZK_REGION_CLOSING,
2724 EventType.RS_ZK_REGION_CLOSED);
2725 }
2726
2727
2728
2729
2730
2731
2732
2733 private boolean isSplitOrSplittingOrMergedOrMerging(final String path)
2734 throws KeeperException, DeserializationException {
2735 boolean result = false;
2736
2737
2738 byte [] data = ZKAssign.getData(watcher, path);
2739 if (data == null) {
2740 LOG.info("Node " + path + " is gone");
2741 return false;
2742 }
2743 RegionTransition rt = RegionTransition.parseFrom(data);
2744 switch (rt.getEventType()) {
2745 case RS_ZK_REQUEST_REGION_SPLIT:
2746 case RS_ZK_REGION_SPLIT:
2747 case RS_ZK_REGION_SPLITTING:
2748 case RS_ZK_REQUEST_REGION_MERGE:
2749 case RS_ZK_REGION_MERGED:
2750 case RS_ZK_REGION_MERGING:
2751 result = true;
2752 break;
2753 default:
2754 LOG.info("Node " + path + " is in " + rt.getEventType());
2755 break;
2756 }
2757 return result;
2758 }
2759
2760
2761
2762
2763
2764
2765 public int getNumRegionsOpened() {
2766 return numRegionsOpened.get();
2767 }
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778 public boolean waitForAssignment(HRegionInfo regionInfo)
2779 throws InterruptedException {
2780 ArrayList<HRegionInfo> regionSet = new ArrayList<HRegionInfo>(1);
2781 regionSet.add(regionInfo);
2782 return waitForAssignment(regionSet, true, Long.MAX_VALUE);
2783 }
2784
2785
2786
2787
2788 protected boolean waitForAssignment(final Collection<HRegionInfo> regionSet,
2789 final boolean waitTillAllAssigned, final int reassigningRegions,
2790 final long minEndTime) throws InterruptedException {
2791 long deadline = minEndTime + bulkPerRegionOpenTimeGuesstimate * (reassigningRegions + 1);
2792 if (deadline < 0) {
2793 deadline = Long.MAX_VALUE;
2794 }
2795 return waitForAssignment(regionSet, waitTillAllAssigned, deadline);
2796 }
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806 protected boolean waitForAssignment(final Collection<HRegionInfo> regionSet,
2807 final boolean waitTillAllAssigned, final long deadline) throws InterruptedException {
2808
2809 while (!regionSet.isEmpty() && !server.isStopped() && deadline > System.currentTimeMillis()) {
2810 int failedOpenCount = 0;
2811 Iterator<HRegionInfo> regionInfoIterator = regionSet.iterator();
2812 while (regionInfoIterator.hasNext()) {
2813 HRegionInfo hri = regionInfoIterator.next();
2814 if (regionStates.isRegionOnline(hri) || regionStates.isRegionInState(hri,
2815 State.SPLITTING, State.SPLIT, State.MERGING, State.MERGED)) {
2816 regionInfoIterator.remove();
2817 } else if (regionStates.isRegionInState(hri, State.FAILED_OPEN)) {
2818 failedOpenCount++;
2819 }
2820 }
2821 if (!waitTillAllAssigned) {
2822
2823 break;
2824 }
2825 if (!regionSet.isEmpty()) {
2826 if (failedOpenCount == regionSet.size()) {
2827
2828 break;
2829 }
2830 regionStates.waitForUpdate(100);
2831 }
2832 }
2833 return regionSet.isEmpty();
2834 }
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847 public void assignMeta(HRegionInfo hri) throws KeeperException {
2848 this.server.getMetaTableLocator().deleteMetaLocation(this.watcher, hri.getReplicaId());
2849 assign(hri, true);
2850 }
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860 public void assign(Map<HRegionInfo, ServerName> regions)
2861 throws IOException, InterruptedException {
2862 if (regions == null || regions.isEmpty()) {
2863 return;
2864 }
2865 List<ServerName> servers = serverManager.createDestinationServersList();
2866 if (servers == null || servers.isEmpty()) {
2867 throw new IOException("Found no destination server to assign region(s)");
2868 }
2869
2870
2871 Map<ServerName, List<HRegionInfo>> bulkPlan =
2872 balancer.retainAssignment(regions, servers);
2873 if (bulkPlan == null) {
2874 throw new IOException("Unable to determine a plan to assign region(s)");
2875 }
2876
2877 assign(regions.size(), servers.size(),
2878 "retainAssignment=true", bulkPlan);
2879 }
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889 public void assign(List<HRegionInfo> regions)
2890 throws IOException, InterruptedException {
2891 if (regions == null || regions.isEmpty()) {
2892 return;
2893 }
2894
2895 List<ServerName> servers = serverManager.createDestinationServersList();
2896 if (servers == null || servers.isEmpty()) {
2897 throw new IOException("Found no destination server to assign region(s)");
2898 }
2899
2900
2901 Map<ServerName, List<HRegionInfo>> bulkPlan = balancer.roundRobinAssignment(regions, servers);
2902 if (bulkPlan == null) {
2903 throw new IOException("Unable to determine a plan to assign region(s)");
2904 }
2905
2906 processFavoredNodes(regions);
2907 assign(regions.size(), servers.size(), "round-robin=true", bulkPlan);
2908 }
2909
2910 private void assign(int regions, int totalServers,
2911 String message, Map<ServerName, List<HRegionInfo>> bulkPlan)
2912 throws InterruptedException, IOException {
2913
2914 int servers = bulkPlan.size();
2915 if (servers == 1 || (regions < bulkAssignThresholdRegions
2916 && servers < bulkAssignThresholdServers)) {
2917
2918
2919
2920 if (LOG.isTraceEnabled()) {
2921 LOG.trace("Not using bulk assignment since we are assigning only " + regions +
2922 " region(s) to " + servers + " server(s)");
2923 }
2924
2925
2926 ArrayList<HRegionInfo> userRegionSet = new ArrayList<HRegionInfo>(regions);
2927 for (Map.Entry<ServerName, List<HRegionInfo>> plan: bulkPlan.entrySet()) {
2928 if (!assign(plan.getKey(), plan.getValue())) {
2929 for (HRegionInfo region: plan.getValue()) {
2930 if (!regionStates.isRegionOnline(region)) {
2931 invokeAssign(region);
2932 if (!region.getTable().isSystemTable()) {
2933 userRegionSet.add(region);
2934 }
2935 }
2936 }
2937 }
2938 }
2939
2940
2941 if (!waitForAssignment(userRegionSet, true, userRegionSet.size(),
2942 System.currentTimeMillis())) {
2943 LOG.debug("some user regions are still in transition: " + userRegionSet);
2944 }
2945 } else {
2946 LOG.info("Bulk assigning " + regions + " region(s) across "
2947 + totalServers + " server(s), " + message);
2948
2949
2950 BulkAssigner ba = new GeneralBulkAssigner(
2951 this.server, bulkPlan, this, bulkAssignWaitTillAllAssigned);
2952 ba.bulkAssign();
2953 LOG.info("Bulk assigning done");
2954 }
2955 }
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966 private void assignAllUserRegions(Map<HRegionInfo, ServerName> allRegions)
2967 throws IOException, InterruptedException {
2968 if (allRegions == null || allRegions.isEmpty()) return;
2969
2970
2971 boolean retainAssignment = server.getConfiguration().
2972 getBoolean("hbase.master.startup.retainassign", true);
2973
2974 Set<HRegionInfo> regionsFromMetaScan = allRegions.keySet();
2975 if (retainAssignment) {
2976 assign(allRegions);
2977 } else {
2978 List<HRegionInfo> regions = new ArrayList<HRegionInfo>(regionsFromMetaScan);
2979 assign(regions);
2980 }
2981
2982 for (HRegionInfo hri : regionsFromMetaScan) {
2983 TableName tableName = hri.getTable();
2984 if (!tableStateManager.isTableState(tableName,
2985 ZooKeeperProtos.Table.State.ENABLED)) {
2986 setEnabledTable(tableName);
2987 }
2988 }
2989
2990 assign(replicaRegionsNotRecordedInMeta(regionsFromMetaScan, server));
2991 }
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004 public static List<HRegionInfo> replicaRegionsNotRecordedInMeta(
3005 Set<HRegionInfo> regionsRecordedInMeta, MasterServices master)throws IOException {
3006 List<HRegionInfo> regionsNotRecordedInMeta = new ArrayList<HRegionInfo>();
3007 for (HRegionInfo hri : regionsRecordedInMeta) {
3008 TableName table = hri.getTable();
3009 HTableDescriptor htd = master.getTableDescriptors().get(table);
3010
3011 int desiredRegionReplication = htd.getRegionReplication();
3012 for (int i = 0; i < desiredRegionReplication; i++) {
3013 HRegionInfo replica = RegionReplicaUtil.getRegionInfoForReplica(hri, i);
3014 if (regionsRecordedInMeta.contains(replica)) continue;
3015 regionsNotRecordedInMeta.add(replica);
3016 }
3017 }
3018 return regionsNotRecordedInMeta;
3019 }
3020
3021
3022
3023
3024
3025
3026
3027 boolean waitUntilNoRegionsInTransition(final long timeout)
3028 throws InterruptedException {
3029
3030
3031
3032
3033
3034
3035 final long endTime = System.currentTimeMillis() + timeout;
3036
3037 while (!this.server.isStopped() && regionStates.isRegionsInTransition()
3038 && endTime > System.currentTimeMillis()) {
3039 regionStates.waitForUpdate(100);
3040 }
3041
3042 return !regionStates.isRegionsInTransition();
3043 }
3044
3045
3046
3047
3048
3049
3050
3051 Set<ServerName> rebuildUserRegions() throws
3052 IOException, KeeperException, CoordinatedStateException {
3053 Set<TableName> disabledOrEnablingTables = tableStateManager.getTablesInStates(
3054 ZooKeeperProtos.Table.State.DISABLED, ZooKeeperProtos.Table.State.ENABLING);
3055
3056 Set<TableName> disabledOrDisablingOrEnabling = tableStateManager.getTablesInStates(
3057 ZooKeeperProtos.Table.State.DISABLED,
3058 ZooKeeperProtos.Table.State.DISABLING,
3059 ZooKeeperProtos.Table.State.ENABLING);
3060
3061
3062 List<Result> results = MetaTableAccessor.fullScanOfMeta(server.getConnection());
3063
3064 Set<ServerName> onlineServers = serverManager.getOnlineServers().keySet();
3065
3066 Set<ServerName> offlineServers = new HashSet<ServerName>();
3067
3068 for (Result result : results) {
3069 if (result == null && LOG.isDebugEnabled()){
3070 LOG.debug("null result from meta - ignoring but this is strange.");
3071 continue;
3072 }
3073
3074
3075
3076 PairOfSameType<HRegionInfo> p = MetaTableAccessor.getMergeRegions(result);
3077 if (p.getFirst() != null && p.getSecond() != null) {
3078 int numReplicas = server.getTableDescriptors().get(p.getFirst().
3079 getTable()).getRegionReplication();
3080 for (HRegionInfo merge : p) {
3081 for (int i = 1; i < numReplicas; i++) {
3082 replicasToClose.add(RegionReplicaUtil.getRegionInfoForReplica(merge, i));
3083 }
3084 }
3085 }
3086 RegionLocations rl = MetaTableAccessor.getRegionLocations(result);
3087 if (rl == null) continue;
3088 HRegionLocation[] locations = rl.getRegionLocations();
3089 if (locations == null) continue;
3090 for (HRegionLocation hrl : locations) {
3091 if (hrl == null) continue;
3092 HRegionInfo regionInfo = hrl.getRegionInfo();
3093 if (regionInfo == null) continue;
3094 int replicaId = regionInfo.getReplicaId();
3095 State state = RegionStateStore.getRegionState(result, replicaId);
3096
3097
3098
3099 if (replicaId == 0 && state.equals(State.SPLIT)) {
3100 for (HRegionLocation h : locations) {
3101 replicasToClose.add(h.getRegionInfo());
3102 }
3103 }
3104 ServerName lastHost = hrl.getServerName();
3105 ServerName regionLocation = RegionStateStore.getRegionServer(result, replicaId);
3106 if (tableStateManager.isTableState(regionInfo.getTable(),
3107 ZooKeeperProtos.Table.State.DISABLED)) {
3108
3109
3110 lastHost = null;
3111 regionLocation = null;
3112 }
3113 regionStates.createRegionState(regionInfo, state, regionLocation, lastHost);
3114 if (!regionStates.isRegionInState(regionInfo, State.OPEN)) {
3115
3116 continue;
3117 }
3118 TableName tableName = regionInfo.getTable();
3119 if (!onlineServers.contains(regionLocation)) {
3120
3121 offlineServers.add(regionLocation);
3122 if (useZKForAssignment) {
3123 regionStates.regionOffline(regionInfo);
3124 }
3125 } else if (!disabledOrEnablingTables.contains(tableName)) {
3126
3127
3128 regionStates.regionOnline(regionInfo, regionLocation);
3129 balancer.regionOnline(regionInfo, regionLocation);
3130 } else if (useZKForAssignment) {
3131 regionStates.regionOffline(regionInfo);
3132 }
3133
3134
3135 if (!disabledOrDisablingOrEnabling.contains(tableName)
3136 && !getTableStateManager().isTableState(tableName,
3137 ZooKeeperProtos.Table.State.ENABLED)) {
3138 setEnabledTable(tableName);
3139 }
3140 }
3141 }
3142 return offlineServers;
3143 }
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153 private void recoverTableInDisablingState()
3154 throws KeeperException, IOException, CoordinatedStateException {
3155 Set<TableName> disablingTables =
3156 tableStateManager.getTablesInStates(ZooKeeperProtos.Table.State.DISABLING);
3157 if (disablingTables.size() != 0) {
3158 for (TableName tableName : disablingTables) {
3159
3160 LOG.info("The table " + tableName
3161 + " is in DISABLING state. Hence recovering by moving the table"
3162 + " to DISABLED state.");
3163 new DisableTableHandler(this.server, tableName,
3164 this, tableLockManager, true).prepare().process();
3165 }
3166 }
3167 }
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177 private void recoverTableInEnablingState()
3178 throws KeeperException, IOException, CoordinatedStateException {
3179 Set<TableName> enablingTables = tableStateManager.
3180 getTablesInStates(ZooKeeperProtos.Table.State.ENABLING);
3181 if (enablingTables.size() != 0) {
3182 for (TableName tableName : enablingTables) {
3183
3184 LOG.info("The table " + tableName
3185 + " is in ENABLING state. Hence recovering by moving the table"
3186 + " to ENABLED state.");
3187
3188
3189 EnableTableHandler eth = new EnableTableHandler(this.server, tableName,
3190 this, tableLockManager, true);
3191 try {
3192 eth.prepare();
3193 } catch (TableNotFoundException e) {
3194 LOG.warn("Table " + tableName + " not found in hbase:meta to recover.");
3195 continue;
3196 }
3197 eth.process();
3198 }
3199 }
3200 }
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213 private void processDeadServersAndRecoverLostRegions(Set<ServerName> deadServers)
3214 throws IOException, KeeperException {
3215 if (deadServers != null && !deadServers.isEmpty()) {
3216 for (ServerName serverName: deadServers) {
3217 if (!serverManager.isServerDead(serverName)) {
3218 serverManager.expireServer(serverName);
3219 }
3220 }
3221 }
3222
3223 List<String> nodes = useZKForAssignment ?
3224 ZKUtil.listChildrenAndWatchForNewChildren(watcher, watcher.assignmentZNode)
3225 : ZKUtil.listChildrenNoWatch(watcher, watcher.assignmentZNode);
3226 if (nodes != null && !nodes.isEmpty()) {
3227 for (String encodedRegionName : nodes) {
3228 processRegionInTransition(encodedRegionName, null);
3229 }
3230 } else if (!useZKForAssignment) {
3231 processRegionInTransitionZkLess();
3232 }
3233 }
3234
3235 void processRegionInTransitionZkLess() {
3236
3237
3238
3239
3240
3241 Map<String, RegionState> rits = regionStates.getRegionsInTransition();
3242 for (RegionState regionState : rits.values()) {
3243 LOG.info("Processing " + regionState);
3244 ServerName serverName = regionState.getServerName();
3245
3246
3247 if (serverName != null
3248 && !serverManager.getOnlineServers().containsKey(serverName)) {
3249 LOG.info("Server " + serverName + " isn't online. SSH will handle this");
3250 continue;
3251 }
3252 HRegionInfo regionInfo = regionState.getRegion();
3253 State state = regionState.getState();
3254
3255 switch (state) {
3256 case CLOSED:
3257 invokeAssign(regionInfo);
3258 break;
3259 case PENDING_OPEN:
3260 retrySendRegionOpen(regionState);
3261 break;
3262 case PENDING_CLOSE:
3263 retrySendRegionClose(regionState);
3264 break;
3265 case FAILED_CLOSE:
3266 case FAILED_OPEN:
3267 invokeUnAssign(regionInfo);
3268 break;
3269 default:
3270
3271 }
3272 }
3273 }
3274
3275
3276
3277
3278
3279 private void retrySendRegionOpen(final RegionState regionState) {
3280 this.executorService.submit(
3281 new EventHandler(server, EventType.M_MASTER_RECOVERY) {
3282 @Override
3283 public void process() throws IOException {
3284 HRegionInfo hri = regionState.getRegion();
3285 ServerName serverName = regionState.getServerName();
3286 ReentrantLock lock = locker.acquireLock(hri.getEncodedName());
3287 try {
3288 for (int i = 1; i <= maximumAttempts; i++) {
3289 if (!serverManager.isServerOnline(serverName)
3290 || server.isStopped() || server.isAborted()) {
3291 return;
3292 }
3293 try {
3294 if (!regionState.equals(regionStates.getRegionState(hri))) {
3295 return;
3296 }
3297 List<ServerName> favoredNodes = ServerName.EMPTY_SERVER_LIST;
3298 if (shouldAssignRegionsWithFavoredNodes) {
3299 favoredNodes = ((FavoredNodeLoadBalancer)balancer).getFavoredNodes(hri);
3300 }
3301 RegionOpeningState regionOpenState = serverManager.sendRegionOpen(
3302 serverName, hri, -1, favoredNodes);
3303
3304 if (regionOpenState == RegionOpeningState.FAILED_OPENING) {
3305
3306
3307 LOG.debug("Got failed_opening in retry sendRegionOpen for "
3308 + regionState + ", re-assign it");
3309 invokeAssign(hri, true);
3310 }
3311 return;
3312 } catch (Throwable t) {
3313 if (t instanceof RemoteException) {
3314 t = ((RemoteException) t).unwrapRemoteException();
3315 }
3316
3317 if (t instanceof java.net.SocketTimeoutException
3318 || t instanceof FailedServerException) {
3319 Threads.sleep(100);
3320 continue;
3321 }
3322
3323 LOG.debug("Got exception in retry sendRegionOpen for "
3324 + regionState + ", re-assign it", t);
3325 invokeAssign(hri);
3326 return;
3327 }
3328 }
3329 } finally {
3330 lock.unlock();
3331 }
3332 }
3333 });
3334 }
3335
3336
3337
3338
3339
3340 private void retrySendRegionClose(final RegionState regionState) {
3341 this.executorService.submit(
3342 new EventHandler(server, EventType.M_MASTER_RECOVERY) {
3343 @Override
3344 public void process() throws IOException {
3345 HRegionInfo hri = regionState.getRegion();
3346 ServerName serverName = regionState.getServerName();
3347 ReentrantLock lock = locker.acquireLock(hri.getEncodedName());
3348 try {
3349 for (int i = 1; i <= maximumAttempts; i++) {
3350 if (!serverManager.isServerOnline(serverName)
3351 || server.isStopped() || server.isAborted()) {
3352 return;
3353 }
3354 try {
3355 if (!regionState.equals(regionStates.getRegionState(hri))) {
3356 return;
3357 }
3358 if (!serverManager.sendRegionClose(serverName, hri, -1, null, false)) {
3359
3360 LOG.debug("Got false in retry sendRegionClose for "
3361 + regionState + ", re-close it");
3362 invokeUnAssign(hri);
3363 }
3364 return;
3365 } catch (Throwable t) {
3366 if (t instanceof RemoteException) {
3367 t = ((RemoteException) t).unwrapRemoteException();
3368 }
3369
3370 if (t instanceof java.net.SocketTimeoutException
3371 || t instanceof FailedServerException) {
3372 Threads.sleep(100);
3373 continue;
3374 }
3375 if (!(t instanceof NotServingRegionException
3376 || t instanceof RegionAlreadyInTransitionException)) {
3377
3378
3379
3380 LOG.debug("Got exception in retry sendRegionClose for "
3381 + regionState + ", re-close it", t);
3382 invokeUnAssign(hri);
3383 }
3384 return;
3385 }
3386 }
3387 } finally {
3388 lock.unlock();
3389 }
3390 }
3391 });
3392 }
3393
3394
3395
3396
3397
3398
3399
3400
3401 public void updateRegionsInTransitionMetrics() {
3402 long currentTime = System.currentTimeMillis();
3403 int totalRITs = 0;
3404 int totalRITsOverThreshold = 0;
3405 long oldestRITTime = 0;
3406 int ritThreshold = this.server.getConfiguration().
3407 getInt(HConstants.METRICS_RIT_STUCK_WARNING_THRESHOLD, 60000);
3408 for (RegionState state: regionStates.getRegionsInTransition().values()) {
3409 totalRITs++;
3410 long ritTime = currentTime - state.getStamp();
3411 if (ritTime > ritThreshold) {
3412 totalRITsOverThreshold++;
3413 }
3414 if (oldestRITTime < ritTime) {
3415 oldestRITTime = ritTime;
3416 }
3417 }
3418 if (this.metricsAssignmentManager != null) {
3419 this.metricsAssignmentManager.updateRITOldestAge(oldestRITTime);
3420 this.metricsAssignmentManager.updateRITCount(totalRITs);
3421 this.metricsAssignmentManager.updateRITCountOverThreshold(totalRITsOverThreshold);
3422 }
3423 }
3424
3425
3426
3427
3428 void clearRegionPlan(final HRegionInfo region) {
3429 synchronized (this.regionPlans) {
3430 this.regionPlans.remove(region.getEncodedName());
3431 }
3432 }
3433
3434
3435
3436
3437
3438
3439 public void waitOnRegionToClearRegionsInTransition(final HRegionInfo hri)
3440 throws IOException, InterruptedException {
3441 waitOnRegionToClearRegionsInTransition(hri, -1L);
3442 }
3443
3444
3445
3446
3447
3448
3449
3450
3451 public boolean waitOnRegionToClearRegionsInTransition(final HRegionInfo hri, long timeOut)
3452 throws InterruptedException {
3453 if (!regionStates.isRegionInTransition(hri)) return true;
3454 long end = (timeOut <= 0) ? Long.MAX_VALUE : EnvironmentEdgeManager.currentTime()
3455 + timeOut;
3456
3457
3458 LOG.info("Waiting for " + hri.getEncodedName() +
3459 " to leave regions-in-transition, timeOut=" + timeOut + " ms.");
3460 while (!this.server.isStopped() && regionStates.isRegionInTransition(hri)) {
3461 regionStates.waitForUpdate(100);
3462 if (EnvironmentEdgeManager.currentTime() > end) {
3463 LOG.info("Timed out on waiting for " + hri.getEncodedName() + " to be assigned.");
3464 return false;
3465 }
3466 }
3467 if (this.server.isStopped()) {
3468 LOG.info("Giving up wait on regions in transition because stoppable.isStopped is set");
3469 return false;
3470 }
3471 return true;
3472 }
3473
3474 void invokeAssign(HRegionInfo regionInfo) {
3475 invokeAssign(regionInfo, true);
3476 }
3477
3478 void invokeAssign(HRegionInfo regionInfo, boolean newPlan) {
3479 threadPoolExecutorService.submit(new AssignCallable(this, regionInfo, newPlan));
3480 }
3481
3482 void invokeUnAssign(HRegionInfo regionInfo) {
3483 threadPoolExecutorService.submit(new UnAssignCallable(this, regionInfo));
3484 }
3485
3486 public ServerHostRegion isCarryingMeta(ServerName serverName) {
3487 return isCarryingRegion(serverName, HRegionInfo.FIRST_META_REGIONINFO);
3488 }
3489
3490 public ServerHostRegion isCarryingMetaReplica(ServerName serverName, int replicaId) {
3491 return isCarryingRegion(serverName,
3492 RegionReplicaUtil.getRegionInfoForReplica(HRegionInfo.FIRST_META_REGIONINFO, replicaId));
3493 }
3494
3495 public ServerHostRegion isCarryingMetaReplica(ServerName serverName, HRegionInfo metaHri) {
3496 return isCarryingRegion(serverName, metaHri);
3497 }
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509 private ServerHostRegion isCarryingRegion(ServerName serverName, HRegionInfo hri) {
3510 RegionTransition rt = null;
3511 try {
3512 byte [] data = ZKAssign.getData(watcher, hri.getEncodedName());
3513
3514 rt = data == null? null: RegionTransition.parseFrom(data);
3515 } catch (KeeperException e) {
3516 server.abort("Exception reading unassigned node for region=" + hri.getEncodedName(), e);
3517 } catch (DeserializationException e) {
3518 server.abort("Exception parsing unassigned node for region=" + hri.getEncodedName(), e);
3519 }
3520
3521 ServerName addressFromZK = rt != null? rt.getServerName(): null;
3522 if (addressFromZK != null) {
3523
3524 boolean matchZK = addressFromZK.equals(serverName);
3525 LOG.debug("Checking region=" + hri.getRegionNameAsString() + ", zk server=" + addressFromZK +
3526 " current=" + serverName + ", matches=" + matchZK);
3527 return matchZK ? ServerHostRegion.HOSTING_REGION : ServerHostRegion.NOT_HOSTING_REGION;
3528 }
3529
3530 ServerName addressFromAM = regionStates.getRegionServerOfRegion(hri);
3531 if (LOG.isDebugEnabled()) {
3532 LOG.debug("based on AM, current region=" + hri.getRegionNameAsString() +
3533 " is on server=" + (addressFromAM != null ? addressFromAM : "null") +
3534 " server being checked: " + serverName);
3535 }
3536 if (addressFromAM != null) {
3537 return addressFromAM.equals(serverName) ?
3538 ServerHostRegion.HOSTING_REGION : ServerHostRegion.NOT_HOSTING_REGION;
3539 }
3540
3541 if (hri.isMetaRegion() && RegionReplicaUtil.isDefaultReplica(hri)) {
3542
3543 final ServerName serverNameInZK =
3544 server.getMetaTableLocator().getMetaRegionLocation(this.server.getZooKeeper());
3545 if (LOG.isDebugEnabled()) {
3546 LOG.debug("Based on MetaTableLocator, the META region is on server=" +
3547 (serverNameInZK == null ? "null" : serverNameInZK) +
3548 " server being checked: " + serverName);
3549 }
3550 if (serverNameInZK != null) {
3551 return serverNameInZK.equals(serverName) ?
3552 ServerHostRegion.HOSTING_REGION : ServerHostRegion.NOT_HOSTING_REGION;
3553 }
3554 }
3555
3556
3557 return ServerHostRegion.UNKNOWN;
3558 }
3559
3560
3561
3562
3563
3564
3565 public List<HRegionInfo> cleanOutCrashedServerReferences(final ServerName sn) {
3566
3567 synchronized (this.regionPlans) {
3568 for (Iterator <Map.Entry<String, RegionPlan>> i = this.regionPlans.entrySet().iterator();
3569 i.hasNext();) {
3570 Map.Entry<String, RegionPlan> e = i.next();
3571 ServerName otherSn = e.getValue().getDestination();
3572
3573 if (otherSn != null && otherSn.equals(sn)) {
3574
3575 i.remove();
3576 }
3577 }
3578 }
3579 List<HRegionInfo> regions = regionStates.serverOffline(watcher, sn);
3580 for (Iterator<HRegionInfo> it = regions.iterator(); it.hasNext(); ) {
3581 HRegionInfo hri = it.next();
3582 String encodedName = hri.getEncodedName();
3583
3584
3585 Lock lock = locker.acquireLock(encodedName);
3586 try {
3587 RegionState regionState = regionStates.getRegionTransitionState(encodedName);
3588 if (regionState == null
3589 || (regionState.getServerName() != null && !regionState.isOnServer(sn))
3590 || !(regionState.isFailedClose() || regionState.isOffline()
3591 || regionState.isPendingOpenOrOpening())) {
3592 LOG.info("Skip " + regionState + " since it is not opening/failed_close"
3593 + " on the dead server any more: " + sn);
3594 it.remove();
3595 } else {
3596 try {
3597
3598 ZKAssign.deleteNodeFailSilent(watcher, hri);
3599 } catch (KeeperException ke) {
3600 server.abort("Unexpected ZK exception deleting node " + hri, ke);
3601 }
3602 if (tableStateManager.isTableState(hri.getTable(),
3603 ZooKeeperProtos.Table.State.DISABLED, ZooKeeperProtos.Table.State.DISABLING)) {
3604 regionStates.regionOffline(hri);
3605 it.remove();
3606 continue;
3607 }
3608
3609 regionStates.updateRegionState(hri, State.OFFLINE);
3610 }
3611 } finally {
3612 lock.unlock();
3613 }
3614 }
3615 return regions;
3616 }
3617
3618
3619
3620
3621 public void balance(final RegionPlan plan) {
3622
3623 HRegionInfo hri = plan.getRegionInfo();
3624 TableName tableName = hri.getTable();
3625 if (tableStateManager.isTableState(tableName,
3626 ZooKeeperProtos.Table.State.DISABLED, ZooKeeperProtos.Table.State.DISABLING)) {
3627 LOG.info("Ignored moving region of disabling/disabled table "
3628 + tableName);
3629 return;
3630 }
3631
3632
3633 String encodedName = hri.getEncodedName();
3634 ReentrantLock lock = locker.acquireLock(encodedName);
3635 try {
3636 if (!regionStates.isRegionOnline(hri)) {
3637 RegionState state = regionStates.getRegionState(encodedName);
3638 LOG.info("Ignored moving region not assigned: " + hri + ", "
3639 + (state == null ? "not in region states" : state));
3640 return;
3641 }
3642 synchronized (this.regionPlans) {
3643 this.regionPlans.put(plan.getRegionName(), plan);
3644 }
3645 unassign(hri, false, plan.getDestination());
3646 } finally {
3647 lock.unlock();
3648 }
3649 }
3650
3651 public void stop() {
3652 shutdown();
3653 }
3654
3655
3656
3657
3658 public void shutdown() {
3659
3660 synchronized (zkEventWorkerWaitingList){
3661 zkEventWorkerWaitingList.clear();
3662 }
3663
3664
3665 threadPoolExecutorService.shutdownNow();
3666 zkEventWorkers.shutdownNow();
3667 regionStateStore.stop();
3668 }
3669
3670 protected void setEnabledTable(TableName tableName) {
3671 try {
3672 this.tableStateManager.setTableState(tableName,
3673 ZooKeeperProtos.Table.State.ENABLED);
3674 } catch (CoordinatedStateException e) {
3675
3676 String errorMsg = "Unable to ensure that the table " + tableName
3677 + " will be" + " enabled because of a ZooKeeper issue";
3678 LOG.error(errorMsg);
3679 this.server.abort(errorMsg, e);
3680 }
3681 }
3682
3683
3684
3685
3686
3687
3688
3689 private boolean asyncSetOfflineInZooKeeper(final RegionState state,
3690 final AsyncCallback.StringCallback cb, final ServerName destination) {
3691 if (!state.isClosed() && !state.isOffline()) {
3692 this.server.abort("Unexpected state trying to OFFLINE; " + state,
3693 new IllegalStateException());
3694 return false;
3695 }
3696 regionStates.updateRegionState(state.getRegion(), State.OFFLINE);
3697 try {
3698 ZKAssign.asyncCreateNodeOffline(watcher, state.getRegion(),
3699 destination, cb, state);
3700 } catch (KeeperException e) {
3701 if (e instanceof NodeExistsException) {
3702 LOG.warn("Node for " + state.getRegion() + " already exists");
3703 } else {
3704 server.abort("Unexpected ZK exception creating/setting node OFFLINE", e);
3705 }
3706 return false;
3707 }
3708 return true;
3709 }
3710
3711 private boolean deleteNodeInStates(String encodedName,
3712 String desc, ServerName sn, EventType... types) {
3713 try {
3714 for (EventType et: types) {
3715 if (ZKAssign.deleteNode(watcher, encodedName, et, sn)) {
3716 return true;
3717 }
3718 }
3719 LOG.info("Failed to delete the " + desc + " node for "
3720 + encodedName + ". The node type may not match");
3721 } catch (NoNodeException e) {
3722 if (LOG.isDebugEnabled()) {
3723 LOG.debug("The " + desc + " node for " + encodedName + " already deleted");
3724 }
3725 } catch (KeeperException ke) {
3726 server.abort("Unexpected ZK exception deleting " + desc
3727 + " node for the region " + encodedName, ke);
3728 }
3729 return false;
3730 }
3731
3732 private void deleteMergingNode(String encodedName, ServerName sn) {
3733 deleteNodeInStates(encodedName, "merging", sn, EventType.RS_ZK_REGION_MERGING,
3734 EventType.RS_ZK_REQUEST_REGION_MERGE, EventType.RS_ZK_REGION_MERGED);
3735 }
3736
3737 private void deleteSplittingNode(String encodedName, ServerName sn) {
3738 deleteNodeInStates(encodedName, "splitting", sn, EventType.RS_ZK_REGION_SPLITTING,
3739 EventType.RS_ZK_REQUEST_REGION_SPLIT, EventType.RS_ZK_REGION_SPLIT);
3740 }
3741
3742 @edu.umd.cs.findbugs.annotations.SuppressWarnings(
3743 value="AT_OPERATION_SEQUENCE_ON_CONCURRENT_ABSTRACTION",
3744 justification="Modification of Maps not ATOMIC!!!! FIX!!!")
3745 private void onRegionFailedOpen(
3746 final HRegionInfo hri, final ServerName sn) {
3747 String encodedName = hri.getEncodedName();
3748
3749 AtomicInteger failedOpenCount = failedOpenTracker.get(encodedName);
3750 if (failedOpenCount == null) {
3751 failedOpenCount = new AtomicInteger();
3752
3753
3754
3755
3756 failedOpenTracker.put(encodedName, failedOpenCount);
3757 }
3758 if (failedOpenCount.incrementAndGet() >= maximumAttempts && !hri.isMetaRegion()) {
3759
3760 regionStates.updateRegionState(hri, State.FAILED_OPEN);
3761
3762
3763 failedOpenTracker.remove(encodedName);
3764 } else {
3765 if (hri.isMetaRegion() && failedOpenCount.get() >= maximumAttempts) {
3766
3767
3768 LOG.warn("Failed to open the hbase:meta region " +
3769 hri.getRegionNameAsString() + " after" +
3770 failedOpenCount.get() + " retries. Continue retrying.");
3771 }
3772
3773
3774 RegionState regionState = regionStates.updateRegionState(hri, State.CLOSED);
3775 if (regionState != null) {
3776
3777
3778 if (getTableStateManager().isTableState(hri.getTable(),
3779 ZooKeeperProtos.Table.State.DISABLED, ZooKeeperProtos.Table.State.DISABLING) ||
3780 replicasToClose.contains(hri)) {
3781 offlineDisabledRegion(hri);
3782 return;
3783 }
3784
3785 regionStates.updateRegionState(hri, RegionState.State.CLOSED);
3786
3787 removeClosedRegion(hri);
3788 try {
3789 getRegionPlan(hri, sn, true);
3790 } catch (HBaseIOException e) {
3791 LOG.warn("Failed to get region plan", e);
3792 }
3793 invokeAssign(hri, false);
3794 }
3795 }
3796 }
3797
3798 private void onRegionOpen(final HRegionInfo hri, final ServerName sn, long openSeqNum) {
3799 regionOnline(hri, sn, openSeqNum);
3800 if (useZKForAssignment) {
3801 try {
3802
3803 ZKAssign.deleteNodeFailSilent(watcher, hri);
3804 } catch (KeeperException ke) {
3805 server.abort("Unexpected ZK exception deleting node " + hri, ke);
3806 }
3807 }
3808
3809
3810 failedOpenTracker.remove(hri.getEncodedName());
3811 if (getTableStateManager().isTableState(hri.getTable(),
3812 ZooKeeperProtos.Table.State.DISABLED, ZooKeeperProtos.Table.State.DISABLING)) {
3813 invokeUnAssign(hri);
3814 }
3815 }
3816
3817 private void onRegionClosed(final HRegionInfo hri) {
3818 if (getTableStateManager().isTableState(hri.getTable(),
3819 ZooKeeperProtos.Table.State.DISABLED, ZooKeeperProtos.Table.State.DISABLING) ||
3820 replicasToClose.contains(hri)) {
3821 offlineDisabledRegion(hri);
3822 return;
3823 }
3824 regionStates.updateRegionState(hri, RegionState.State.CLOSED);
3825 sendRegionClosedNotification(hri);
3826
3827 removeClosedRegion(hri);
3828 invokeAssign(hri, false);
3829 }
3830
3831 private String checkInStateForSplit(ServerName sn,
3832 final HRegionInfo p, final HRegionInfo a, final HRegionInfo b) {
3833 final RegionState rs_p = regionStates.getRegionState(p);
3834 RegionState rs_a = regionStates.getRegionState(a);
3835 RegionState rs_b = regionStates.getRegionState(b);
3836 if (!(rs_p.isOpenOrSplittingOnServer(sn)
3837 && (rs_a == null || rs_a.isOpenOrSplittingNewOnServer(sn))
3838 && (rs_b == null || rs_b.isOpenOrSplittingNewOnServer(sn)))) {
3839 return "Not in state good for split";
3840 }
3841 return "";
3842 }
3843
3844 private String onRegionSplitReverted(ServerName sn,
3845 final HRegionInfo p, final HRegionInfo a, final HRegionInfo b) {
3846 String s = checkInStateForSplit(sn, p, a, b);
3847 if (!org.apache.commons.lang.StringUtils.isEmpty(s)) {
3848 return s;
3849 }
3850
3851
3852
3853 regionOnline(p, sn);
3854
3855
3856 RegionState regionStateA = regionStates.getRegionState(a);
3857 RegionState regionStateB = regionStates.getRegionState(b);
3858 if (regionStateA != null) {
3859 regionOffline(a);
3860 }
3861 if (regionStateB != null) {
3862 regionOffline(b);
3863 }
3864
3865 if (getTableStateManager().isTableState(p.getTable(),
3866 ZooKeeperProtos.Table.State.DISABLED, ZooKeeperProtos.Table.State.DISABLING)) {
3867 invokeUnAssign(p);
3868 }
3869 return null;
3870 }
3871
3872 private String onRegionSplit(ServerName sn, TransitionCode code,
3873 final HRegionInfo p, final HRegionInfo a, final HRegionInfo b) {
3874 String s = checkInStateForSplit(sn, p, a, b);
3875 if (!org.apache.commons.lang.StringUtils.isEmpty(s)) {
3876 return s;
3877 }
3878 regionStates.updateRegionState(a, State.SPLITTING_NEW, sn);
3879 regionStates.updateRegionState(b, State.SPLITTING_NEW, sn);
3880 regionStates.updateRegionState(p, State.SPLITTING);
3881
3882 if (code == TransitionCode.SPLIT) {
3883 if (TEST_SKIP_SPLIT_HANDLING) {
3884 return "Skipping split message, TEST_SKIP_SPLIT_HANDLING is set";
3885 }
3886 regionOffline(p, State.SPLIT);
3887 regionOnline(a, sn, 1);
3888 regionOnline(b, sn, 1);
3889
3890
3891 if (getTableStateManager().isTableState(p.getTable(),
3892 ZooKeeperProtos.Table.State.DISABLED, ZooKeeperProtos.Table.State.DISABLING)) {
3893 invokeUnAssign(a);
3894 invokeUnAssign(b);
3895 } else {
3896 Callable<Object> splitReplicasCallable = new Callable<Object>() {
3897 @Override
3898 public Object call() {
3899 doSplittingOfReplicas(p, a, b);
3900 return null;
3901 }
3902 };
3903 threadPoolExecutorService.submit(splitReplicasCallable);
3904 }
3905 } else if (code == TransitionCode.SPLIT_PONR) {
3906 try {
3907 regionStates.splitRegion(p, a, b, sn);
3908 } catch (IOException ioe) {
3909 LOG.info("Failed to record split region " + p.getShortNameToLog());
3910 return "Failed to record the splitting in meta";
3911 }
3912 }
3913 return null;
3914 }
3915
3916 private String onRegionMerge(ServerName sn, TransitionCode code,
3917 final HRegionInfo p, final HRegionInfo a, final HRegionInfo b) {
3918 RegionState rs_p = regionStates.getRegionState(p);
3919 RegionState rs_a = regionStates.getRegionState(a);
3920 RegionState rs_b = regionStates.getRegionState(b);
3921 if (!(rs_a.isOpenOrMergingOnServer(sn) && rs_b.isOpenOrMergingOnServer(sn)
3922 && (rs_p == null || rs_p.isOpenOrMergingNewOnServer(sn)))) {
3923 return "Not in state good for merge";
3924 }
3925 regionStates.updateRegionState(a, State.MERGING);
3926 regionStates.updateRegionState(b, State.MERGING);
3927 regionStates.updateRegionState(p, State.MERGING_NEW, sn);
3928
3929 String encodedName = p.getEncodedName();
3930 if (code == TransitionCode.READY_TO_MERGE) {
3931 mergingRegions.put(encodedName,
3932 new PairOfSameType<HRegionInfo>(a, b));
3933 } else if (code == TransitionCode.MERGED) {
3934
3935 if (TEST_SKIP_MERGE_HANDLING) {
3936 return "Skipping merge message, TEST_SKIP_MERGE_HANDLING is set for merge parent: " + p;
3937 }
3938
3939 mergingRegions.remove(encodedName);
3940 regionOffline(a, State.MERGED);
3941 regionOffline(b, State.MERGED);
3942 regionOnline(p, sn, 1);
3943
3944
3945 if (getTableStateManager().isTableState(p.getTable(),
3946 ZooKeeperProtos.Table.State.DISABLED, ZooKeeperProtos.Table.State.DISABLING)) {
3947 invokeUnAssign(p);
3948 } else {
3949 Callable<Object> mergeReplicasCallable = new Callable<Object>() {
3950 @Override
3951 public Object call() {
3952 doMergingOfReplicas(p, a, b);
3953 return null;
3954 }
3955 };
3956 threadPoolExecutorService.submit(mergeReplicasCallable);
3957 }
3958 } else if (code == TransitionCode.MERGE_PONR) {
3959 try {
3960 regionStates.mergeRegions(p, a, b, sn);
3961 } catch (IOException ioe) {
3962 LOG.info("Failed to record merged region " + p.getShortNameToLog());
3963 return "Failed to record the merging in meta";
3964 }
3965 }
3966 return null;
3967 }
3968
3969 private String onRegionMergeReverted(ServerName sn, TransitionCode code,
3970 final HRegionInfo p, final HRegionInfo a, final HRegionInfo b) {
3971 RegionState rs_p = regionStates.getRegionState(p);
3972 String encodedName = p.getEncodedName();
3973 mergingRegions.remove(encodedName);
3974
3975
3976
3977 regionOnline(a, sn);
3978 regionOnline(b, sn);
3979
3980
3981 if (rs_p != null) {
3982 regionOffline(p);
3983 }
3984
3985 if (getTableStateManager().isTableState(p.getTable(),
3986 ZooKeeperProtos.Table.State.DISABLED, ZooKeeperProtos.Table.State.DISABLING)) {
3987 invokeUnAssign(a);
3988 invokeUnAssign(b);
3989 }
3990
3991 return null;
3992 }
3993
3994
3995
3996
3997
3998 private boolean handleRegionMerging(final RegionTransition rt, final String encodedName,
3999 final String prettyPrintedRegionName, final ServerName sn) {
4000 if (!serverManager.isServerOnline(sn)) {
4001 LOG.warn("Dropped merging! ServerName=" + sn + " unknown.");
4002 return false;
4003 }
4004 byte [] payloadOfMerging = rt.getPayload();
4005 List<HRegionInfo> mergingRegions;
4006 try {
4007 mergingRegions = HRegionInfo.parseDelimitedFrom(
4008 payloadOfMerging, 0, payloadOfMerging.length);
4009 } catch (IOException e) {
4010 LOG.error("Dropped merging! Failed reading " + rt.getEventType()
4011 + " payload for " + prettyPrintedRegionName);
4012 return false;
4013 }
4014 assert mergingRegions.size() == 3;
4015 HRegionInfo p = mergingRegions.get(0);
4016 HRegionInfo hri_a = mergingRegions.get(1);
4017 HRegionInfo hri_b = mergingRegions.get(2);
4018
4019 RegionState rs_p = regionStates.getRegionState(p);
4020 RegionState rs_a = regionStates.getRegionState(hri_a);
4021 RegionState rs_b = regionStates.getRegionState(hri_b);
4022
4023 if (!((rs_a == null || rs_a.isOpenOrMergingOnServer(sn))
4024 && (rs_b == null || rs_b.isOpenOrMergingOnServer(sn))
4025 && (rs_p == null || rs_p.isOpenOrMergingNewOnServer(sn)))) {
4026 LOG.warn("Dropped merging! Not in state good for MERGING; rs_p="
4027 + rs_p + ", rs_a=" + rs_a + ", rs_b=" + rs_b);
4028 return false;
4029 }
4030
4031 EventType et = rt.getEventType();
4032 if (et == EventType.RS_ZK_REQUEST_REGION_MERGE) {
4033 try {
4034 RegionMergeCoordination.RegionMergeDetails std =
4035 ((BaseCoordinatedStateManager) server.getCoordinatedStateManager())
4036 .getRegionMergeCoordination().getDefaultDetails();
4037 ((BaseCoordinatedStateManager) server.getCoordinatedStateManager())
4038 .getRegionMergeCoordination().processRegionMergeRequest(p, hri_a, hri_b, sn, std);
4039 if (((ZkRegionMergeCoordination.ZkRegionMergeDetails) std).getZnodeVersion() == -1) {
4040 byte[] data = ZKAssign.getData(watcher, encodedName);
4041 EventType currentType = null;
4042 if (data != null) {
4043 RegionTransition newRt = RegionTransition.parseFrom(data);
4044 currentType = newRt.getEventType();
4045 }
4046 if (currentType == null || (currentType != EventType.RS_ZK_REGION_MERGED
4047 && currentType != EventType.RS_ZK_REGION_MERGING)) {
4048 LOG.warn("Failed to transition pending_merge node "
4049 + encodedName + " to merging, it's now " + currentType);
4050 return false;
4051 }
4052 }
4053 } catch (Exception e) {
4054 LOG.warn("Failed to transition pending_merge node "
4055 + encodedName + " to merging", e);
4056 return false;
4057 }
4058 }
4059
4060 synchronized (regionStates) {
4061 regionStates.updateRegionState(hri_a, State.MERGING);
4062 regionStates.updateRegionState(hri_b, State.MERGING);
4063 regionStates.updateRegionState(p, State.MERGING_NEW, sn);
4064
4065 if (TEST_SKIP_MERGE_HANDLING) {
4066 LOG.warn("Skipping merge message, TEST_SKIP_MERGE_HANDLING is set for merge parent: " + p);
4067 return true;
4068 }
4069
4070 if (et != EventType.RS_ZK_REGION_MERGED) {
4071 this.mergingRegions.put(encodedName,
4072 new PairOfSameType<HRegionInfo>(hri_a, hri_b));
4073 } else {
4074 this.mergingRegions.remove(encodedName);
4075 regionOffline(hri_a, State.MERGED);
4076 regionOffline(hri_b, State.MERGED);
4077 regionOnline(p, sn);
4078 }
4079 }
4080
4081 if (et == EventType.RS_ZK_REGION_MERGED) {
4082 doMergingOfReplicas(p, hri_a, hri_b);
4083 LOG.debug("Handling MERGED event for " + encodedName + "; deleting node");
4084
4085 try {
4086 boolean successful = false;
4087 while (!successful) {
4088
4089
4090 successful = ZKAssign.deleteNode(watcher, encodedName,
4091 EventType.RS_ZK_REGION_MERGED, sn);
4092 }
4093 } catch (KeeperException e) {
4094 if (e instanceof NoNodeException) {
4095 String znodePath = ZKUtil.joinZNode(watcher.splitLogZNode, encodedName);
4096 LOG.debug("The znode " + znodePath + " does not exist. May be deleted already.");
4097 } else {
4098 server.abort("Error deleting MERGED node " + encodedName, e);
4099 }
4100 }
4101 LOG.info("Handled MERGED event; merged=" + p.getRegionNameAsString()
4102 + ", region_a=" + hri_a.getRegionNameAsString() + ", region_b="
4103 + hri_b.getRegionNameAsString() + ", on " + sn);
4104
4105
4106 if (tableStateManager.isTableState(p.getTable(),
4107 ZooKeeperProtos.Table.State.DISABLED, ZooKeeperProtos.Table.State.DISABLING)) {
4108 unassign(p);
4109 }
4110 }
4111 return true;
4112 }
4113
4114
4115
4116
4117 private boolean handleRegionSplitting(final RegionTransition rt, final String encodedName,
4118 final String prettyPrintedRegionName, final ServerName sn) {
4119 if (!serverManager.isServerOnline(sn)) {
4120 LOG.warn("Dropped splitting! ServerName=" + sn + " unknown.");
4121 return false;
4122 }
4123 byte [] payloadOfSplitting = rt.getPayload();
4124 List<HRegionInfo> splittingRegions;
4125 try {
4126 splittingRegions = HRegionInfo.parseDelimitedFrom(
4127 payloadOfSplitting, 0, payloadOfSplitting.length);
4128 } catch (IOException e) {
4129 LOG.error("Dropped splitting! Failed reading " + rt.getEventType()
4130 + " payload for " + prettyPrintedRegionName);
4131 return false;
4132 }
4133 assert splittingRegions.size() == 2;
4134 HRegionInfo hri_a = splittingRegions.get(0);
4135 HRegionInfo hri_b = splittingRegions.get(1);
4136
4137 RegionState rs_p = regionStates.getRegionState(encodedName);
4138 RegionState rs_a = regionStates.getRegionState(hri_a);
4139 RegionState rs_b = regionStates.getRegionState(hri_b);
4140
4141 if (!((rs_p == null || rs_p.isOpenOrSplittingOnServer(sn))
4142 && (rs_a == null || rs_a.isOpenOrSplittingNewOnServer(sn))
4143 && (rs_b == null || rs_b.isOpenOrSplittingNewOnServer(sn)))) {
4144 LOG.warn("Dropped splitting! Not in state good for SPLITTING; rs_p="
4145 + rs_p + ", rs_a=" + rs_a + ", rs_b=" + rs_b);
4146 return false;
4147 }
4148
4149 if (rs_p == null) {
4150
4151 rs_p = regionStates.updateRegionState(rt, State.OPEN);
4152 if (rs_p == null) {
4153 LOG.warn("Received splitting for region " + prettyPrintedRegionName
4154 + " from server " + sn + " but it doesn't exist anymore,"
4155 + " probably already processed its split");
4156 return false;
4157 }
4158 regionStates.regionOnline(rs_p.getRegion(), sn);
4159 }
4160
4161 HRegionInfo p = rs_p.getRegion();
4162 EventType et = rt.getEventType();
4163 if (et == EventType.RS_ZK_REQUEST_REGION_SPLIT) {
4164 try {
4165 SplitTransactionDetails std =
4166 ((BaseCoordinatedStateManager) server.getCoordinatedStateManager())
4167 .getSplitTransactionCoordination().getDefaultDetails();
4168 if (((BaseCoordinatedStateManager) server.getCoordinatedStateManager())
4169 .getSplitTransactionCoordination().processTransition(p, hri_a, hri_b, sn, std) == -1) {
4170 byte[] data = ZKAssign.getData(watcher, encodedName);
4171 EventType currentType = null;
4172 if (data != null) {
4173 RegionTransition newRt = RegionTransition.parseFrom(data);
4174 currentType = newRt.getEventType();
4175 }
4176 if (currentType == null
4177 || (currentType != EventType.RS_ZK_REGION_SPLIT && currentType != EventType.RS_ZK_REGION_SPLITTING)) {
4178 LOG.warn("Failed to transition pending_split node " + encodedName
4179 + " to splitting, it's now " + currentType);
4180 return false;
4181 }
4182 }
4183 } catch (Exception e) {
4184 LOG.warn("Failed to transition pending_split node " + encodedName + " to splitting", e);
4185 return false;
4186 }
4187 }
4188
4189 synchronized (regionStates) {
4190 splitRegions.put(p, new PairOfSameType<HRegionInfo>(hri_a, hri_b));
4191 regionStates.updateRegionState(hri_a, State.SPLITTING_NEW, sn);
4192 regionStates.updateRegionState(hri_b, State.SPLITTING_NEW, sn);
4193 regionStates.updateRegionState(rt, State.SPLITTING);
4194
4195
4196
4197 if (TEST_SKIP_SPLIT_HANDLING) {
4198 LOG.warn("Skipping split message, TEST_SKIP_SPLIT_HANDLING is set");
4199 return true;
4200 }
4201
4202 if (et == EventType.RS_ZK_REGION_SPLIT) {
4203 regionOffline(p, State.SPLIT);
4204 regionOnline(hri_a, sn);
4205 regionOnline(hri_b, sn);
4206 splitRegions.remove(p);
4207 }
4208 }
4209
4210 if (et == EventType.RS_ZK_REGION_SPLIT) {
4211
4212 doSplittingOfReplicas(rs_p.getRegion(), hri_a, hri_b);
4213 LOG.debug("Handling SPLIT event for " + encodedName + "; deleting node");
4214
4215 try {
4216 boolean successful = false;
4217 while (!successful) {
4218
4219
4220 successful = ZKAssign.deleteNode(watcher, encodedName,
4221 EventType.RS_ZK_REGION_SPLIT, sn);
4222 }
4223 } catch (KeeperException e) {
4224 if (e instanceof NoNodeException) {
4225 String znodePath = ZKUtil.joinZNode(watcher.splitLogZNode, encodedName);
4226 LOG.debug("The znode " + znodePath + " does not exist. May be deleted already.");
4227 } else {
4228 server.abort("Error deleting SPLIT node " + encodedName, e);
4229 }
4230 }
4231 LOG.info("Handled SPLIT event; parent=" + p.getRegionNameAsString()
4232 + ", daughter a=" + hri_a.getRegionNameAsString() + ", daughter b="
4233 + hri_b.getRegionNameAsString() + ", on " + sn);
4234
4235
4236 if (tableStateManager.isTableState(p.getTable(),
4237 ZooKeeperProtos.Table.State.DISABLED, ZooKeeperProtos.Table.State.DISABLING)) {
4238 unassign(hri_a);
4239 unassign(hri_b);
4240 }
4241 }
4242 return true;
4243 }
4244
4245 private void doMergingOfReplicas(HRegionInfo mergedHri, final HRegionInfo hri_a,
4246 final HRegionInfo hri_b) {
4247
4248
4249 List<HRegionInfo> unmergedRegions = new ArrayList<HRegionInfo>();
4250 unmergedRegions.add(hri_a);
4251 unmergedRegions.add(hri_b);
4252 Map<ServerName, List<HRegionInfo>> map = regionStates.getRegionAssignments(unmergedRegions);
4253 Collection<List<HRegionInfo>> c = map.values();
4254 for (List<HRegionInfo> l : c) {
4255 for (HRegionInfo h : l) {
4256 if (!RegionReplicaUtil.isDefaultReplica(h)) {
4257 LOG.debug("Unassigning un-merged replica " + h);
4258 unassign(h);
4259 }
4260 }
4261 }
4262 int numReplicas = 1;
4263 try {
4264 numReplicas = server.getTableDescriptors().get(mergedHri.getTable()).
4265 getRegionReplication();
4266 } catch (IOException e) {
4267 LOG.warn("Couldn't get the replication attribute of the table " + mergedHri.getTable() +
4268 " due to " + e.getMessage() + ". The assignment of replicas for the merged region " +
4269 "will not be done");
4270 }
4271 List<HRegionInfo> regions = new ArrayList<HRegionInfo>();
4272 for (int i = 1; i < numReplicas; i++) {
4273 regions.add(RegionReplicaUtil.getRegionInfoForReplica(mergedHri, i));
4274 }
4275 try {
4276 assign(regions);
4277 } catch (IOException ioe) {
4278 LOG.warn("Couldn't assign all replica(s) of region " + mergedHri + " because of " +
4279 ioe.getMessage());
4280 } catch (InterruptedException ie) {
4281 LOG.warn("Couldn't assign all replica(s) of region " + mergedHri+ " because of " +
4282 ie.getMessage());
4283 }
4284
4285 clearReplicaRegions(c);
4286 }
4287
4288 private void doSplittingOfReplicas(final HRegionInfo parentHri, final HRegionInfo hri_a,
4289 final HRegionInfo hri_b) {
4290
4291
4292
4293 int numReplicas = 1;
4294 try {
4295 numReplicas = server.getTableDescriptors().get(parentHri.getTable()).
4296 getRegionReplication();
4297 } catch (IOException e) {
4298 LOG.warn("Couldn't get the replication attribute of the table " + parentHri.getTable() +
4299 " due to " + e.getMessage() + ". The assignment of daughter replicas " +
4300 "replicas will not be done");
4301 }
4302
4303 List<HRegionInfo> parentRegion = new ArrayList<HRegionInfo>();
4304 parentRegion.add(parentHri);
4305 Map<ServerName, List<HRegionInfo>> currentAssign =
4306 regionStates.getRegionAssignments(parentRegion);
4307 Collection<List<HRegionInfo>> c = currentAssign.values();
4308 for (List<HRegionInfo> l : c) {
4309 for (HRegionInfo h : l) {
4310 if (!RegionReplicaUtil.isDefaultReplica(h)) {
4311 LOG.debug("Unassigning parent's replica " + h);
4312 unassign(h);
4313 }
4314 }
4315 }
4316
4317 Map<HRegionInfo, ServerName> map = new HashMap<HRegionInfo, ServerName>();
4318 for (int i = 1; i < numReplicas; i++) {
4319 prepareDaughterReplicaForAssignment(hri_a, parentHri, i, map);
4320 prepareDaughterReplicaForAssignment(hri_b, parentHri, i, map);
4321 }
4322 try {
4323 assign(map);
4324 } catch (IOException e) {
4325 LOG.warn("Caught exception " + e + " while trying to assign replica(s) of daughter(s)");
4326 } catch (InterruptedException e) {
4327 LOG.warn("Caught exception " + e + " while trying to assign replica(s) of daughter(s)");
4328 }
4329
4330 clearReplicaRegions(c);
4331 }
4332
4333
4334
4335
4336 private void clearReplicaRegions(Collection<List<HRegionInfo>> regionInfos) {
4337 for (List<HRegionInfo> regionInfoList : regionInfos) {
4338 for (HRegionInfo regionInfo : regionInfoList) {
4339 if (!RegionReplicaUtil.isDefaultReplica(regionInfo)) {
4340 regionStates.deleteRegion(regionInfo);
4341 }
4342 }
4343 }
4344 }
4345
4346 private void prepareDaughterReplicaForAssignment(HRegionInfo daughterHri, HRegionInfo parentHri,
4347 int replicaId, Map<HRegionInfo, ServerName> map) {
4348 HRegionInfo parentReplica = RegionReplicaUtil.getRegionInfoForReplica(parentHri, replicaId);
4349 HRegionInfo daughterReplica = RegionReplicaUtil.getRegionInfoForReplica(daughterHri,
4350 replicaId);
4351 LOG.debug("Created replica region for daughter " + daughterReplica);
4352 ServerName sn;
4353 if ((sn = regionStates.getRegionServerOfRegion(parentReplica)) != null) {
4354 map.put(daughterReplica, sn);
4355 } else {
4356 List<ServerName> servers = serverManager.getOnlineServersList();
4357 sn = servers.get((new Random(System.currentTimeMillis())).nextInt(servers.size()));
4358 map.put(daughterReplica, sn);
4359 }
4360 }
4361
4362 public Set<HRegionInfo> getReplicasToClose() {
4363 return replicasToClose;
4364 }
4365
4366
4367
4368
4369
4370
4371 private void regionOffline(final HRegionInfo regionInfo, final State state) {
4372 regionStates.regionOffline(regionInfo, state);
4373 removeClosedRegion(regionInfo);
4374
4375 clearRegionPlan(regionInfo);
4376 balancer.regionOffline(regionInfo);
4377
4378
4379 sendRegionClosedNotification(regionInfo);
4380
4381 if (state != null && state.equals(State.SPLIT)) {
4382 Collection<HRegionInfo> c = new ArrayList<HRegionInfo>(1);
4383 c.add(regionInfo);
4384 Map<ServerName, List<HRegionInfo>> map = regionStates.getRegionAssignments(c);
4385 Collection<List<HRegionInfo>> allReplicas = map.values();
4386 for (List<HRegionInfo> list : allReplicas) {
4387 replicasToClose.addAll(list);
4388 }
4389 }
4390 else if (state != null && state.equals(State.MERGED)) {
4391 Collection<HRegionInfo> c = new ArrayList<HRegionInfo>(1);
4392 c.add(regionInfo);
4393 Map<ServerName, List<HRegionInfo>> map = regionStates.getRegionAssignments(c);
4394 Collection<List<HRegionInfo>> allReplicas = map.values();
4395 for (List<HRegionInfo> list : allReplicas) {
4396 replicasToClose.addAll(list);
4397 }
4398 }
4399 }
4400
4401 private void sendRegionOpenedNotification(final HRegionInfo regionInfo,
4402 final ServerName serverName) {
4403 if (!this.listeners.isEmpty()) {
4404 for (AssignmentListener listener : this.listeners) {
4405 listener.regionOpened(regionInfo, serverName);
4406 }
4407 }
4408 }
4409
4410 private void sendRegionClosedNotification(final HRegionInfo regionInfo) {
4411 if (!this.listeners.isEmpty()) {
4412 for (AssignmentListener listener : this.listeners) {
4413 listener.regionClosed(regionInfo);
4414 }
4415 }
4416 }
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462 protected String onRegionTransition(final ServerName serverName,
4463 final RegionStateTransition transition) {
4464 TransitionCode code = transition.getTransitionCode();
4465 HRegionInfo hri = HRegionInfo.convert(transition.getRegionInfo(0));
4466 RegionState current = regionStates.getRegionState(hri);
4467 if (LOG.isDebugEnabled()) {
4468 LOG.debug("Got transition " + code + " for "
4469 + (current != null ? current.toString() : hri.getShortNameToLog())
4470 + " from " + serverName);
4471 }
4472 String errorMsg = null;
4473 switch (code) {
4474 case OPENED:
4475 if (current != null && current.isOpened() && current.isOnServer(serverName)) {
4476 LOG.info("Region " + hri.getShortNameToLog() + " is already " + current.getState() + " on "
4477 + serverName);
4478 break;
4479 }
4480 case FAILED_OPEN:
4481 if (current == null
4482 || !current.isPendingOpenOrOpeningOnServer(serverName)) {
4483 errorMsg = hri.getShortNameToLog()
4484 + " is not pending open on " + serverName;
4485 } else if (code == TransitionCode.FAILED_OPEN) {
4486 onRegionFailedOpen(hri, serverName);
4487 } else {
4488 long openSeqNum = HConstants.NO_SEQNUM;
4489 if (transition.hasOpenSeqNum()) {
4490 openSeqNum = transition.getOpenSeqNum();
4491 }
4492 if (openSeqNum < 0) {
4493 errorMsg = "Newly opened region has invalid open seq num " + openSeqNum;
4494 } else {
4495 onRegionOpen(hri, serverName, openSeqNum);
4496 }
4497 }
4498 break;
4499
4500 case CLOSED:
4501 if (current == null
4502 || !current.isPendingCloseOrClosingOnServer(serverName)) {
4503 errorMsg = hri.getShortNameToLog()
4504 + " is not pending close on " + serverName;
4505 } else {
4506 onRegionClosed(hri);
4507 }
4508 break;
4509
4510 case READY_TO_SPLIT:
4511 try {
4512 regionStateListener.onRegionSplit(hri);
4513 if (!((HMaster)server).getSplitOrMergeTracker().isSplitOrMergeEnabled(
4514 Admin.MasterSwitchType.SPLIT)) {
4515 errorMsg = "split switch is off!";
4516 break;
4517 }
4518 } catch (IOException exp) {
4519 errorMsg = StringUtils.stringifyException(exp);
4520 break;
4521 }
4522
4523 case SPLIT_PONR:
4524 case SPLIT:
4525 errorMsg =
4526 onRegionSplit(serverName, code, hri, HRegionInfo.convert(transition.getRegionInfo(1)),
4527 HRegionInfo.convert(transition.getRegionInfo(2)));
4528 break;
4529
4530 case SPLIT_REVERTED:
4531 errorMsg =
4532 onRegionSplitReverted(serverName, hri,
4533 HRegionInfo.convert(transition.getRegionInfo(1)),
4534 HRegionInfo.convert(transition.getRegionInfo(2)));
4535 if (org.apache.commons.lang.StringUtils.isEmpty(errorMsg)) {
4536 try {
4537 regionStateListener.onRegionSplitReverted(hri);
4538 } catch (IOException exp) {
4539 LOG.warn(StringUtils.stringifyException(exp));
4540 }
4541 }
4542 break;
4543 case READY_TO_MERGE:
4544 if (!((HMaster)server).getSplitOrMergeTracker().isSplitOrMergeEnabled(
4545 Admin.MasterSwitchType.MERGE)) {
4546 errorMsg = "merge switch is off!";
4547 break;
4548 }
4549
4550 case MERGE_PONR:
4551 case MERGED:
4552 errorMsg = onRegionMerge(serverName, code, hri,
4553 HRegionInfo.convert(transition.getRegionInfo(1)),
4554 HRegionInfo.convert(transition.getRegionInfo(2)));
4555 if (code == TransitionCode.MERGED && org.apache.commons.lang.StringUtils.isEmpty(errorMsg)) {
4556 try {
4557 regionStateListener.onRegionMerged(hri);
4558 } catch (IOException exp) {
4559 errorMsg = StringUtils.stringifyException(exp);
4560 }
4561 }
4562 break;
4563 case MERGE_REVERTED:
4564 errorMsg = onRegionMergeReverted(serverName, code, hri,
4565 HRegionInfo.convert(transition.getRegionInfo(1)),
4566 HRegionInfo.convert(transition.getRegionInfo(2)));
4567 break;
4568
4569 default:
4570 errorMsg = "Unexpected transition code " + code;
4571 }
4572 if (errorMsg != null) {
4573 LOG.error("Failed to transtion region from " + current + " to "
4574 + code + " by " + serverName + ": " + errorMsg);
4575 }
4576 return errorMsg;
4577 }
4578
4579
4580
4581
4582 public LoadBalancer getBalancer() {
4583 return this.balancer;
4584 }
4585
4586 public Map<ServerName, List<HRegionInfo>>
4587 getSnapShotOfAssignment(Collection<HRegionInfo> infos) {
4588 return getRegionStates().getRegionAssignments(infos);
4589 }
4590
4591 void setRegionStateListener(RegionStateListener listener) {
4592 this.regionStateListener = listener;
4593 }
4594
4595
4596
4597
4598 @VisibleForTesting
4599 public static void setTestSkipSplitHandling(boolean skipSplitHandling) {
4600 TEST_SKIP_SPLIT_HANDLING = skipSplitHandling;
4601 }
4602
4603
4604
4605
4606 @VisibleForTesting
4607 public static void setTestSkipMergeHandling(boolean skipMergeHandling) {
4608 TEST_SKIP_MERGE_HANDLING = skipMergeHandling;
4609 }
4610 }