View Javadoc

1   /**
2    *
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *     http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing, software
14   * distributed under the License is distributed on an "AS IS" BASIS,
15   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16   * See the License for the specific language governing permissions and
17   * limitations under the License.
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  * Manages and performs region assignment.
124  * <p>
125  * Monitors ZooKeeper for events related to regions in transition.
126  * <p>
127  * Handles existing regions in transition during master failover.
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; // 1 minute
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    * Map of regions to reopen after the schema of a table is changed. Key -
160    * encoded region name, value - HRegionInfo
161    */
162   private final Map <String, HRegionInfo> regionsToReopen;
163 
164   /*
165    * Maximum times we recurse an assignment/unassignment.
166    * See below in {@link #assign()} and {@link #unassign()}.
167    */
168   private final int maximumAttempts;
169 
170   /**
171    * Map of two merging regions from the region to be created.
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    * The sleep time for which the assignment will wait before retrying in case of hbase:meta assignment
181    * failure due to lack of availability of region plan or bad region plan
182    */
183   private final long sleepTimeBeforeRetryingMetaAssignment;
184 
185   /** Plans for region movement. Key is the encoded version of a region name*/
186   // TODO: When do plans get cleaned out?  Ever? In server open and in server
187   // shutdown processing -- St.Ack
188   // All access to this Map must be synchronized.
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   // For unit tests, keep track of calls to ClosedRegionHandler
197   private Map<HRegionInfo, AtomicBoolean> closedRegionHandlerCalled = null;
198 
199   // For unit tests, keep track of calls to OpenedRegionHandler
200   private Map<HRegionInfo, AtomicBoolean> openedRegionHandlerCalled = null;
201 
202   //Thread pool executor service for timeout monitor
203   private java.util.concurrent.ExecutorService threadPoolExecutorService;
204 
205   // A bunch of ZK events workers. Each is a single thread executor service
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   // The threshold to use bulk assigning. Using bulk assignment
214   // only if assigning at least this many regions to at least this
215   // many servers. If assigning fewer regions to fewer servers,
216   // bulk assigning may be not as efficient.
217   private final int bulkAssignThresholdRegions;
218   private final int bulkAssignThresholdServers;
219   private final int bulkPerRegionOpenTimeGuesstimate;
220 
221   // Should bulk assignment wait till all regions are assigned,
222   // or it is timed out?  This is useful to measure bulk assignment
223   // performance, but not needed in most use cases.
224   private final boolean bulkAssignWaitTillAllAssigned;
225 
226   /**
227    * Indicator that AssignmentManager has recovered the region states so
228    * that ServerShutdownHandler can be fully enabled and re-assign regions
229    * of dead servers. So that when re-assignment happens, AssignmentManager
230    * has proper region states.
231    *
232    * Protected to ease testing.
233    */
234   protected final AtomicBoolean failoverCleanupDone = new AtomicBoolean(false);
235 
236   /**
237    * A map to track the count a region fails to open in a row.
238    * So that we don't try to open a region forever if the failure is
239    * unrecoverable.  We don't put this information in region states
240    * because we don't expect this to happen frequently; we don't
241    * want to copy this information over during each state transition either.
242    */
243   private final ConcurrentHashMap<String, AtomicInteger>
244     failedOpenTracker = new ConcurrentHashMap<String, AtomicInteger>();
245 
246   // A flag to indicate if we are using ZK for region assignment
247   private final boolean useZKForAssignment;
248 
249   // In case not using ZK for region assignment, region states
250   // are persisted in meta with a state store
251   private final RegionStateStore regionStateStore;
252 
253   /**
254    * For testing only!  Set to true to skip handling of split and merge.
255    */
256   private static boolean TEST_SKIP_SPLIT_HANDLING = false;
257   private static boolean TEST_SKIP_MERGE_HANDLING = false;
258 
259   /** Listeners that are called on assignment events. */
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    * Constructs a new assignment manager.
270    *
271    * @param server instance of HMaster this AM running inside
272    * @param serverManager serverManager for associated HMaster
273    * @param balancer implementation of {@link LoadBalancer}
274    * @param service Executor service
275    * @param metricsMaster metrics manager
276    * @param tableLockManager TableLock manager
277    * @throws KeeperException
278    * @throws IOException
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     // Only read favored nodes if using the favored nodes load balancer.
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     // This is the max attempts, not retries, so it should be at least 1.
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    * Add the listener to the notification list.
341    * @param listener The AssignmentListener to register
342    */
343   public void registerListener(final AssignmentListener listener) {
344     this.listeners.add(listener);
345   }
346 
347   /**
348    * Remove the listener from the notification list.
349    * @param listener The AssignmentListener to unregister
350    */
351   public boolean unregisterListener(final AssignmentListener listener) {
352     return this.listeners.remove(listener);
353   }
354 
355   /**
356    * @return Instance of ZKTableStateManager.
357    */
358   public TableStateManager getTableStateManager() {
359     // These are 'expensive' to make involving trip to zk ensemble so allow
360     // sharing.
361     return this.tableStateManager;
362   }
363 
364   /**
365    * This SHOULD not be public. It is public now
366    * because of some unit tests.
367    *
368    * TODO: make it package private and keep RegionStates in the master package
369    */
370   public RegionStates getRegionStates() {
371     return regionStates;
372   }
373 
374   /**
375    * Used in some tests to mock up region state in meta
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    * Add a regionPlan for the specified region.
388    * @param encodedName
389    * @param plan
390    */
391   public void addPlan(String encodedName, RegionPlan plan) {
392     synchronized (regionPlans) {
393       regionPlans.put(encodedName, plan);
394     }
395   }
396 
397   /**
398    * Add a map of region plans.
399    */
400   public void addPlans(Map<String, RegionPlan> plans) {
401     synchronized (regionPlans) {
402       regionPlans.putAll(plans);
403     }
404   }
405 
406   /**
407    * Set the list of regions that will be reopened
408    * because of an update in table schema
409    *
410    * @param regions
411    *          list of regions that should be tracked for reopen
412    */
413   public void setRegionsToReopen(List <HRegionInfo> regions) {
414     for(HRegionInfo hri : regions) {
415       regionsToReopen.put(hri.getEncodedName(), hri);
416     }
417   }
418 
419   /**
420    * Used by the client to identify if all regions have the schema updates
421    *
422    * @param tableName
423    * @return Pair indicating the status of the alter command
424    * @throws IOException
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       // no lock concurrent access ok: sequential consistency respected.
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    * Used by ServerShutdownHandler to make sure AssignmentManager has completed
450    * the failover cleanup before re-assigning regions of dead servers. So that
451    * when re-assignment happens, AssignmentManager has proper region states.
452    */
453   public boolean isFailoverCleanupDone() {
454     return failoverCleanupDone.get();
455   }
456 
457   /**
458    * To avoid racing with AM, external entities may need to lock a region,
459    * for example, when SSH checks what regions to skip re-assigning.
460    */
461   public Lock acquireRegionLock(final String encodedName) {
462     return locker.acquireLock(encodedName);
463   }
464 
465   /**
466    * Now, failover cleanup is completed. Notify server manager to
467    * process queued up dead servers processing, if any.
468    */
469   void failoverCleanupDone() {
470     failoverCleanupDone.set(true);
471     serverManager.processQueuedDeadServers();
472   }
473 
474   /**
475    * Called on startup.
476    * Figures whether a fresh cluster start of we are joining extant running cluster.
477    * @throws IOException
478    * @throws KeeperException
479    * @throws InterruptedException
480    * @throws CoordinatedStateException
481    */
482   void joinCluster() throws IOException,
483       KeeperException, InterruptedException, CoordinatedStateException {
484     long startTime = System.currentTimeMillis();
485     // Concurrency note: In the below the accesses on regionsInTransition are
486     // outside of a synchronization block where usually all accesses to RIT are
487     // synchronized.  The presumption is that in this case it is safe since this
488     // method is being played by a single thread on startup.
489 
490     // TODO: Regions that have a null location and are not in regionsInTransitions
491     // need to be handled.
492 
493     // Scan hbase:meta to build list of existing regions, servers, and assignment
494     // Returns servers who have not checked in (assumed dead) that some regions
495     // were assigned to (according to the meta)
496     Set<ServerName> deadServers = rebuildUserRegions();
497 
498     // This method will assign all user regions if a clean server startup or
499     // it will reconstruct master state and cleanup any leftovers from previous master process.
500     boolean failover = processDeadServersAndRegionsInTransition(deadServers);
501 
502     if (!useZKForAssignment) {
503       // Not use ZK for assignment any more, remove the ZNode
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    * Process all regions that are in transition in zookeeper and also
514    * processes the list of dead servers.
515    * Used by master joining an cluster.  If we figure this is a clean cluster
516    * startup, will assign all user regions.
517    * @param deadServers Set of servers that are offline probably legitimately that were carrying
518    * regions according to a scan of hbase:meta. Can be null.
519    * @throws KeeperException
520    * @throws IOException
521    * @throws InterruptedException
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; // Doesn't matter in this case
531     }
532 
533     boolean failover = !serverManager.getDeadServers().isEmpty();
534     if (failover) {
535       // This may not be a failover actually, especially if meta is on this master.
536       if (LOG.isDebugEnabled()) {
537         LOG.debug("Found dead servers out on cluster " + serverManager.getDeadServers());
538       }
539     } else {
540       // If any one region except meta is assigned, it's a failover.
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         // If any one region except meta is in transition, it's a failover.
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       // If any region except meta is in transition on a live server, it's a failover.
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       // If we get here, we have a full cluster restart. It is a failover only
582       // if there are some WALs are not split yet. For meta WALs, they should have
583       // been split already, if any. We can walk through those queued dead servers,
584       // if they don't have any WALs, this restart should be considered as a clean one
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           // In the case of a clean exit, the shutdown handler would have presplit any WALs and
592           // removed empty directories.
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           // We figured that it's not a failover, so no need to
604           // work on these re-queued dead servers any more.
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       // Retrieve user regions except tables region that are in disabled/disabling/enabling states.
615       allRegions = getUserRegionsToAssign();
616     }
617 
618     // Now region states are restored
619     regionStateStore.start();
620 
621     // If we found user regions out on cluster, its a failover.
622     if (failover) {
623       LOG.info("Found regions out on cluster or in RIT; presuming failover");
624       // Process list of dead servers and regions in RIT.
625       // See HBASE-4580 for more information.
626       processDeadServersAndRecoverLostRegions(deadServers);
627 
628       // Handle the scenario when meta is rebuild by OfflineMetaRepair tool.
629       // In this scenario, meta will have only info:regioninfo entries (won't contain info:server)
630       // which lead SSH/SCP to skip holding region assignment.
631       if (!MetaTableAccessor.infoServerExists(server.getConnection())) {
632         // Need to assign the user region as a fresh startup, otherwise user region assignment will
633         // never happen
634         assignRegionsOnSSHCompletion();
635       }
636     }
637 
638     if (!failover && useZKForAssignment) {
639       // Cleanup any existing ZK nodes and start watching
640       ZKAssign.deleteAllNodes(watcher);
641       ZKUtil.listChildrenAndWatchForNewChildren(this.watcher,
642         this.watcher.assignmentZNode);
643     }
644 
645     // Now we can safely claim failover cleanup completed and enable
646     // ServerShutdownHandler for further processing. The nodes (below)
647     // in transition, if any, are for regions not related to those
648     // dead servers at all, and can be done in parallel to SSH.
649     failoverCleanupDone();
650     if (!failover) {
651       // Fresh cluster startup.
652       LOG.info("Clean cluster startup. Assigning user regions");
653       assignAllUserRegions(allRegions);
654     }
655     // unassign replicas of the split parents and the merged regions
656     // the daughter replicas are opened in assignAllUserRegions if it was
657     // not already opened.
658     for (HRegionInfo h : replicasToClose) {
659       unassign(h);
660     }
661     replicasToClose.clear();
662     return failover;
663   }
664 
665   /*
666    * At cluster clean re/start, mark all user regions closed except those of tables that are
667    * excluded, such as disabled/disabling/enabling tables. All user regions and their previous
668    * locations are returned.
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     // Clean re/start, mark all user regions closed before reassignment
677     return regionStates.closeAllUserRegions(disabledOrDisablingOrEnabling);
678   }
679 
680   /*
681    * Wait for SSH completion and assign user region which are not in disabled/disabling/enabling
682    * table states.
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         // Wait until all dead server processing finish
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           // Assign the regions
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    * If region is up in zk in transition, then do fixup and block and wait until
713    * the region is assigned and out of transition.  Used on startup for
714    * catalog regions.
715    * @param hri Region to look for.
716    * @return True if we processed a region in transition else false if region
717    * was not up in zk in transition.
718    * @throws InterruptedException
719    * @throws KeeperException
720    * @throws IOException
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; // The region is not in transition
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         // The region is not in transition, or not in transition on an online
734         // server. Doesn't help to block here any more. Caller need to
735         // verify the region is actually assigned.
736         break;
737       }
738       this.regionStates.waitForUpdate(100);
739     }
740     return true;
741   }
742 
743   /**
744    * Process failover of new master for region <code>encodedRegionName</code>
745    * up in zookeeper.
746    * @param encodedRegionName Region to process failover for.
747    * @param regionInfo If null we'll go get it from meta table.
748    * @return True if we processed <code>regionInfo</code> as a RIT.
749    * @throws KeeperException
750    * @throws IOException
751    */
752   boolean processRegionInTransition(final String encodedRegionName,
753       final HRegionInfo regionInfo) throws KeeperException, IOException {
754     // We need a lock here to ensure that we will not put the same region twice
755     // It has no reason to be a lock shared with the other operations.
756     // We can do the lock on the region only, instead of a global lock: what we want to ensure
757     // is that we don't have two threads working on the same region.
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         // The region info is not passed in. We will try to find the region
773         // from region states map/meta based on the encoded region name. But we
774         // may not be able to find it. This is valid for online merge that
775         // the region may have not been created if the merge is not completed.
776         // Therefore, it is not in meta at master recovery time.
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       // TODO: This code is tied to ZK anyway, so for now leaving it as is,
787       // will refactor when whole region assignment will be abstracted from ZK
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    * This call is invoked only (1) master assign meta;
806    * (2) during failover mode startup, zk assignment node processing.
807    * The locker is set in the caller. It returns true if the region
808    * is in transition for sure, false otherwise.
809    *
810    * It should be private but it is used by some test too.
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     // Get ServerName.  Could not be null.
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       // Just return
830       return true;
831     }
832     if (!serverManager.isServerOnline(sn)) {
833       // It was transitioning on a dead server, so it's closed now.
834       // Force to OFFLINE and put it in transition, but not assign it
835       // since log splitting for the dead server is not done yet.
836       LOG.debug("RIT " + encodedName + " in state=" + rt.getEventType() +
837         " was on deadserver; forcing offline");
838       if (regionStates.isRegionOnline(regionInfo)) {
839         // Meta could still show the region is assigned to the previous
840         // server. If that server is online, when we reload the meta, the
841         // region is put back to online, we need to offline it.
842         regionStates.regionOffline(regionInfo);
843         sendRegionClosedNotification(regionInfo);
844       }
845       // Put it back in transition so that SSH can re-assign it
846       regionStates.updateRegionState(regionInfo, State.OFFLINE, sn);
847 
848       if (regionInfo.isMetaRegion()) {
849         // If it's meta region, reset the meta location.
850         // So that master knows the right meta region server.
851         MetaTableLocator.setMetaLocation(watcher, sn, State.OPEN);
852       } else {
853         // No matter the previous server is online or offline,
854         // we need to reset the last region server of the region.
855         regionStates.setLastRegionServerOfRegion(sn, encodedName);
856         // Make sure we know the server is dead.
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         // Insert into RIT & resend the query to the region server: may be the previous master
866         // died before sending the query the first time.
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         // Region is closed, insert into RIT and handle it
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         // Insert in RIT and resend to the regionserver
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         // Region is opened, insert into RIT and handle it
924         // This could be done asynchronously, we would need then to acquire the lock in the
925         //  handler.
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         // Splitting region should be online. We could have skipped it during
933         // user region rebuilding since we may consider the split is completed.
934         // Put it in SPLITTING state to avoid complications.
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    * When a region is closed, it should be removed from the regionsToReopen
961    * @param hri HRegionInfo of the region which was closed
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    * Handles various states an unassigned node can be in.
971    * <p>
972    * Method is called when a state change is suspected for an unassigned node.
973    * <p>
974    * This deals with skipped transitions (we got a CLOSED but didn't see CLOSING
975    * yet).
976    * @param rt region transition
977    * @param coordination coordination for opening region
978    * @param ord details about opening region
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     // Check if this is a special HBCK transition
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     // Verify this is a known server
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     // We don't do anything for this event,
1019     // so separate it out, no need to lock/unlock anything
1020     if (rt.getEventType() == EventType.M_ZK_REGION_OFFLINE) {
1021       return;
1022     }
1023 
1024     // We need a lock on the region as we could update it
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         // If region split not enabled then skip only if event type is RS_ZK_REQUEST_REGION_SPLIT,
1046         // allow on-going split operations
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         // Merged region is a new region, we can't find it in the region states now.
1058         // However, the two merging regions are not new. They should be in state for merging.
1059         // If region merge not enabled then skip only if event type is RS_ZK_REQUEST_REGION_MERGE,
1060         // allow on-going merge operations
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         // Should see CLOSING after we have asked it to CLOSE or additional
1070         // times after already being in state of CLOSING
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         // Transition to CLOSING (or update stamp if already CLOSING)
1079         regionStates.updateRegionState(rt, State.CLOSING);
1080         break;
1081 
1082       case RS_ZK_REGION_CLOSED:
1083         // Should see CLOSED after CLOSING but possible after PENDING_CLOSE
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         // Handle CLOSED by assigning elsewhere or stopping if a disable
1092         // If we got here all is good.  Need to update RegionState -- else
1093         // what follows will fail because not in expected state.
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             // No need to use putIfAbsent, or extra synchronization since
1110             // this whole handleRegion block is locked on the encoded region
1111             // name, and failedOpenTracker is updated only in this block
1112             // FindBugs: AT_OPERATION_SEQUENCE_ON_CONCURRENT_ABSTRACTION
1113             failedOpenTracker.put(encodedName, failedOpenCount);
1114           }
1115           if (failedOpenCount.incrementAndGet() >= maximumAttempts) {
1116             // FindBugs: AT_OPERATION_SEQUENCE_ON_CONCURRENT_ABSTRACTION
1117             regionStates.updateRegionState(rt, State.FAILED_OPEN);
1118             // remove the tracking info to save memory, also reset
1119             // the count for next open initiative
1120             failedOpenTracker.remove(encodedName);
1121           } else {
1122             // Handle this the same as if it were opened and then closed.
1123             regionState = regionStates.setRegionStateTOCLOSED(rt.getRegionName(), sn);
1124             if (regionState != null) {
1125               // When there are more than one region server a new RS is selected as the
1126               // destination and the same is updated in the regionplan. (HBASE-5546)
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           // Should see OPENING after we have asked it to OPEN or additional
1139           // times after already being in state of OPENING
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           // Transition to OPENING (or update stamp if already OPENING)
1148           regionStates.updateRegionState(rt, State.OPENING);
1149           break;
1150 
1151         case RS_ZK_REGION_OPENED:
1152           // Should see OPENED after OPENING but possible after PENDING_OPEN.
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                 //if this region was opened before on this rs, we don't have to unassign it. It won't cause
1162                 //double assign. One possible scenario of what happened is HBASE-17275
1163                 failedOpenTracker.remove(encodedName); // reset the count, if any
1164                 new OpenedRegionHandler(
1165                     server, this, regionState.getRegion(), coordination, ord).process();
1166                 updateOpenedRegionHandlerTracker(regionState.getRegion());
1167               } else {
1168                 // Close it without updating the internal region states,
1169                 // so as not to create double assignments in unlucky scenarios
1170                 // mentioned in OpenRegionHandler#process
1171                 unassign(regionState.getRegion(), null, -1, null, false, sn);
1172               }
1173             }
1174             return;
1175           }
1176           // Handle OPENED by removing from transition and deleted zk node
1177           regionState =
1178               regionStates.transitionOpenFromPendingOpenOrOpeningOnServer(rt,regionState, sn);
1179           if (regionState != null) {
1180             failedOpenTracker.remove(encodedName); // reset the count, if any
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    * Check whether region split or merge enabled.
1197    * @param rt Region transition info
1198    * @param prettyPrintedRegionName Region name
1199    * @param switchType Region operation type
1200    * @param eventType Event type
1201    * @return true if region split/merge enabled
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   // For unit tests only
1214   boolean wasClosedHandlerCalled(HRegionInfo hri) {
1215     AtomicBoolean b = closedRegionHandlerCalled.get(hri);
1216     //compareAndSet to be sure that unit tests don't see stale values. Means,
1217     //we will return true exactly once unless the handler code resets to true
1218     //this value.
1219     return b == null ? false : b.compareAndSet(true, false);
1220   }
1221 
1222   //For unit tests only
1223   boolean wasOpenedHandlerCalled(HRegionInfo hri) {
1224     AtomicBoolean b = openedRegionHandlerCalled.get(hri);
1225     //compareAndSet to be sure that unit tests don't see stale values. Means,
1226     //we will return true exactly once unless the handler code resets to true
1227     //this value.
1228     return b == null ? false : b.compareAndSet(true, false);
1229   }
1230 
1231   //For unit tests only
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) { //only for unit tests this is true
1239       closedRegionHandlerCalled.put(hri, new AtomicBoolean(true));
1240     }
1241   }
1242 
1243   void updateOpenedRegionHandlerTracker(HRegionInfo hri) {
1244     if (openedRegionHandlerCalled != null) { //only for unit tests this is true
1245       openedRegionHandlerCalled.put(hri, new AtomicBoolean(true));
1246     }
1247   }
1248 
1249   // TODO: processFavoredNodes might throw an exception, for e.g., if the
1250   // meta could not be contacted/updated. We need to see how seriously to treat
1251   // this problem as. Should we fail the current assignment. We should be able
1252   // to recover from this problem eventually (if the meta couldn't be updated
1253   // things should work normally and eventually get fixed up).
1254   void processFavoredNodes(List<HRegionInfo> regions) throws IOException {
1255     if (!shouldAssignRegionsWithFavoredNodes) return;
1256     // The AM gets the favored nodes info for each region and updates the meta
1257     // table with that info
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    * Handle a ZK unassigned node transition triggered by HBCK repair tool.
1270    * <p>
1271    * This is handled in a separate code path because it breaks the normal rules.
1272    * @param rt
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         // trigger assign, node is already in OFFLINE so don't need to update ZK
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   // ZooKeeper events
1311 
1312   /**
1313    * New unassigned node has been created.
1314    *
1315    * <p>This happens when an RS begins the OPENING or CLOSING of a region by
1316    * creating an unassigned node.
1317    *
1318    * <p>When this happens we must:
1319    * <ol>
1320    *   <li>Watch the node for further events</li>
1321    *   <li>Read and handle the state in the node</li>
1322    * </ol>
1323    */
1324   @Override
1325   public void nodeCreated(String path) {
1326     handleAssignmentEvent(path);
1327   }
1328 
1329   /**
1330    * Existing unassigned node has had data changed.
1331    *
1332    * <p>This happens when an RS transitions from OFFLINE to OPENING, or between
1333    * OPENING/OPENED and CLOSING/CLOSED.
1334    *
1335    * <p>When this happens we must:
1336    * <ol>
1337    *   <li>Watch the node for further events</li>
1338    *   <li>Read and handle the state in the node</li>
1339    * </ol>
1340    */
1341   @Override
1342   public void nodeDataChanged(String path) {
1343     handleAssignmentEvent(path);
1344   }
1345 
1346 
1347   // We  don't want to have two events on the same region managed simultaneously.
1348   // For this reason, we need to wait if an event on the same region is currently in progress.
1349   // So we track the region names of the events in progress, and we keep a waiting list.
1350   private final Set<String> regionsInProgress = new HashSet<String>();
1351   // In a LinkedHashMultimap, the put order is kept when we retrieve the collection back. We need
1352   //  this as we want the events to be managed in the same order as we received them.
1353   private final LinkedHashMultimap <String, RegionRunnable>
1354       zkEventWorkerWaitingList = LinkedHashMultimap.create();
1355 
1356   /**
1357    * A specific runnable that works only on a region.
1358    */
1359   private interface RegionRunnable extends Runnable{
1360     /**
1361      * @return - the name of the region it works on.
1362      */
1363     String getRegionName();
1364   }
1365 
1366   /**
1367    * Submit a task, ensuring that there is only one task at a time that working on a given region.
1368    * Order is respected.
1369    */
1370   protected void zkEventWorkersSubmit(final RegionRunnable regRunnable) {
1371 
1372     synchronized (regionsInProgress) {
1373       // If we're there is already a task with this region, we add it to the
1374       //  waiting list and return.
1375       if (regionsInProgress.contains(regRunnable.getRegionName())) {
1376         synchronized (zkEventWorkerWaitingList){
1377           zkEventWorkerWaitingList.put(regRunnable.getRegionName(), regRunnable);
1378         }
1379         return;
1380       }
1381 
1382       // No event in progress on this region => we can submit a new task immediately.
1383       regionsInProgress.add(regRunnable.getRegionName());
1384       zkEventWorkers.submit(new Runnable() {
1385         @Override
1386         public void run() {
1387           try {
1388             regRunnable.run();
1389           } finally {
1390             // now that we have finished, let's see if there is an event for the same region in the
1391             //  waiting list. If it's the case, we can now submit it to the pool.
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                   // We want the first object only. The only way to get it is through an iterator.
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                 // MergingNew is an offline state
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                     // Check if the daugter regions are still there, if they are present, offline
1448                     // as its the case of a rollback.
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                     // if server is offline, no hurt to unassign again
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    * New unassigned node has been created.
1501    *
1502    * <p>This happens when an RS begins the OPENING, SPLITTING or CLOSING of a
1503    * region by creating a znode.
1504    *
1505    * <p>When this happens we must:
1506    * <ol>
1507    *   <li>Watch the node for further children changed events</li>
1508    *   <li>Watch all new children for changed events</li>
1509    * </ol>
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             // Just make sure we see the changes for the new znodes
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                 // if region is in transition, we already have a watch
1526                 // on it, so no need to watch it again. So, as I know for now,
1527                 // this is needed to watch splitting nodes only.
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    * Marks the region as online.  Removes it from regions in transition and
1544    * updates the in-memory assignment information.
1545    * <p>
1546    * Used when a region has been successfully opened on a region server.
1547    * @param regionInfo
1548    * @param sn
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     // Remove plan if one.
1559     clearRegionPlan(regionInfo);
1560     balancer.regionOnline(regionInfo, sn);
1561 
1562     // Tell our listeners that a region was opened
1563     sendRegionOpenedNotification(regionInfo, sn);
1564   }
1565 
1566   /**
1567    * Pass the assignment event to a worker for processing.
1568    * Each worker is a single thread executor service.  The reason
1569    * for just one thread is to make sure all events for a given
1570    * region are processed in order.
1571    *
1572    * @param path
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             // TODO: This code is tied to ZK anyway, so for now leaving it as is,
1594             // will refactor when whole region assignment will be abstracted from ZK
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    * Marks the region as offline.  Removes it from regions in transition and
1617    * removes in-memory assignment information.
1618    * <p>
1619    * Used when a region has been closed and should remain closed.
1620    * @param regionInfo
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       // Disabling so should not be reassigned, just delete the CLOSED node
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     //Set servername in regionstate to null, see HBASE-18014
1643     getRegionStates().updateRegionState(regionInfo, State.OFFLINE, null);
1644     regionOffline(regionInfo);
1645   }
1646 
1647   // Assignment methods
1648 
1649   /**
1650    * Assigns the specified region.
1651    * <p>
1652    * If a RegionPlan is available with a valid destination then it will be used
1653    * to determine what server region is assigned to.  If no RegionPlan is
1654    * available, region will be assigned to a random available server.
1655    * <p>
1656    * Updates the RegionState and sends the OPEN RPC.
1657    * <p>
1658    * This will only succeed if the region is in transition and in a CLOSED or
1659    * OFFLINE state or not in transition (in-memory not zk), and of course, the
1660    * chosen server is up and running (It may have just crashed!).  If the
1661    * in-memory checks pass, the zk node is forced to OFFLINE before assigning.
1662    *
1663    * @param region server to be assigned
1664    * @param setOfflineInZK whether ZK node should be created/transitioned to an
1665    *                       OFFLINE state before assigning the region
1666    */
1667   public void assign(HRegionInfo region, boolean setOfflineInZK) {
1668     assign(region, setOfflineInZK, false);
1669   }
1670 
1671   /**
1672    * Use care with forceNewPlan. It could cause double assignment.
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    * Bulk assign regions to <code>destination</code>.
1700    * @param destination
1701    * @param regions Regions to assign.
1702    * @return true if successful
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             // Reassign if the region wasn't on a dead server
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); // assign individually later
1751             }
1752           }
1753           // Release the lock, this region is excluded from bulk assign because
1754           // we can't update its state, or set its znode to offline.
1755           Lock lock = locks.remove(encodedName);
1756           lock.unlock();
1757         }
1758 
1759         if (useZKForAssignment) {
1760           // Wait until all unassigned nodes have been put up and watchers set.
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         // Add region plans, so we can updateTimers when one region is opened so
1779         // that unnecessary timeout on RIT is reduced.
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); // assign individually later
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         // Move on to open regions.
1806         try {
1807           // Send OPEN RPC. If it fails on a IOE or RemoteException,
1808           // regions will be assigned individually.
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               // regionOpenInfos is empty if all regions are in failedToOpenRegions list
1815               if (regionOpenInfos.isEmpty()) {
1816                 break;
1817               }
1818               List<RegionOpeningState> regionOpeningStateList = serverManager
1819                 .sendRegionOpen(destination, regionOpenInfos);
1820               if (regionOpeningStateList == null) {
1821                 // Failed getting RPC connection to this server
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                     // Failed opening this region, reassign it later
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                 // No need to retry, the region server is a goner.
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--; // reset the try count
1855                   continue;
1856                 }
1857               } else if (e instanceof java.net.SocketTimeoutException
1858                   && this.serverManager.isServerOnline(destination)) {
1859                 // In case socket is timed out and the region server is still online,
1860                 // the openRegion RPC could have been accepted by the server and
1861                 // just the response didn't go through.  So we will retry to
1862                 // open the region on the same server.
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                 // wait and reset the re-try count, server might be just busy.
1869                 Thread.sleep(100);
1870                 i--;
1871                 continue;
1872               }
1873               throw e;
1874             }
1875           }
1876         } catch (IOException e) {
1877           // Can be a socket timeout, EOF, NoRouteToHost, etc
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       // wait for assignment completion
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    * Send CLOSE RPC if the server is online, otherwise, offline the region.
1916    *
1917    * The RPC will be sent only to the region sever found in the region state
1918    * if it is passed in, otherwise, to the src server specified. If region
1919    * state is not specified, we don't update region state at all, instead
1920    * we just send the RPC call. This is useful for some cleanup without
1921    * messing around the region states (see handleRegion, on region opened
1922    * on an unexpected server scenario, for an example)
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       // ClosedRegionhandler can remove the server from this.regions
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           // delete the node. if no node exists need not bother.
1944           deleteClosingOrClosedNode(region, server);
1945         }
1946         if (state != null) {
1947           regionOffline(region);
1948         }
1949         return;
1950       }
1951       try {
1952         // Send CLOSE RPC
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             // Retry to make sure the region is
1959             // closed so as to avoid double assignment.
1960             unassign(region, state, versionOfClosingNode,
1961               dest, transitionInZK, src);
1962           }
1963           return;
1964         }
1965         // This never happens. Currently regionserver close always return true.
1966         // Todo; this can now happen (0.96) if there is an exception in a coprocessor
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           // RS is aborting or stopping, we cannot offline the region since the region may need
1980           // to do WAL recovery. Until we see  the RS expiration, we should retry.
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             // RS is already processing this region, only need to update the timestamp
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--; // reset the try count
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           // Presume retry or server will expire.
2039         }
2040       }
2041     }
2042     // Run out of attempts
2043     if (state != null) {
2044       regionStates.updateRegionState(region, State.FAILED_CLOSE);
2045     }
2046   }
2047 
2048   /**
2049    * Set region to OFFLINE unless it is opening and forceNewPlan is false.
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         // If we can't close the region, we can't re-assign
2081         // it so as to avoid possible double assignment/data loss.
2082         LOG.info("Skip assigning " +
2083           region + ", we couldn't close it: " + state);
2084         return null;
2085       }
2086     case OFFLINE:
2087       // This region could have been open on this server
2088       // for a while. If the server is dead and not processed
2089       // yet, we can move on only if the meta shows the
2090       // region is not on this server actually, or on a server
2091       // not dead, or dead and processed already.
2092       // In case not using ZK, we don't need this check because
2093       // we have the latest info in memory, and the caller
2094       // will do another round checking any way.
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     // Call is interrupted or server is stopped.
2143     return regionStates.isServerDeadAndNotProcessed(sn);
2144   }
2145 
2146   /**
2147    * Caller must hold lock on the passed <code>state</code> object.
2148    * @param state
2149    * @param setOfflineInZK
2150    * @param forceNewPlan
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) { // Get a server for the region at first
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           // For meta region, we have to keep retrying until succeeding
2183           if (region.isMetaRegion()) {
2184             if (i == maximumAttempts) {
2185               i = 0; // re-set attempt count to 0 for at least 1 retry
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           // get the version of the znode after setting it to OFFLINE.
2201           // versionOfOfflineNode will be -1 if the znode was not set to OFFLINE
2202           versionOfOfflineNode = setOfflineInZooKeeper(currentState, plan.getDestination());
2203           if (versionOfOfflineNode != -1) {
2204             if (isDisabledorDisablingRegionInRIT(region)) {
2205               return;
2206             }
2207             // In case of assignment from EnableTableHandler table state is ENABLING. Any how
2208             // EnableTableHandler will set ENABLED after assigning all the table regions. If we
2209             // try to set to ENABLED directly then client API may think table is enabled.
2210             // When we have a case such as all the regions are added directly into hbase:meta and we call
2211             // assignRegion then we need to make the table ENABLED. Hence in such case the table
2212             // will not be in ENABLING or ENABLED state.
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           // Setting offline in ZK must have been failed due to ZK racing or some
2224           // exception which may make the server to abort. If it is ZK racing,
2225           // we should retry since we already reset the region state,
2226           // existing (re)assignment will fail anyway.
2227           if (!server.isAborted()) {
2228             continue;
2229           }
2230         }
2231         LOG.info("Assigning " + region.getRegionNameAsString() +
2232             " to " + plan.getDestination().toString());
2233         // Transition RegionState to PENDING_OPEN
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             // Failed opening this region, looping again on a new server.
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             // we're done
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           // Should we wait a little before retrying? If the server is starting it's yes.
2269           // If the region is already in transition, it's yes as well: we want to be sure that
2270           //  the region will get opened but we don't want a double assignment.
2271           boolean hold = (t instanceof RegionAlreadyInTransitionException ||
2272               t instanceof ServerNotRunningYetException);
2273 
2274           // In case socket is timed out and the region server is still online,
2275           // the openRegion RPC could have been accepted by the server and
2276           // just the response didn't go through.  So we will retry to
2277           // open the region on the same server to avoid possible
2278           // double assignment.
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--; // reset the try count
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--; // we want to retry as many times as needed as long as the RS is not dead.
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           // For meta region, we have to keep retrying until succeeding
2330           if (region.isMetaRegion()) {
2331             i = 0; // re-set attempt count to 0 for at least 1 retry
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             // Don't reset the region state or get a new plan any more.
2339             // This is the last try.
2340             continue;
2341           }
2342         }
2343 
2344         // If region opened on destination of present plan, reassigning to new
2345         // RS may cause double assignments. In case of RegionAlreadyInTransitionException
2346         // reassigning to same RS.
2347         if (needNewPlan) {
2348           // Force a new plan and reassign. Will return null if no servers.
2349           // The new plan could be the same as the existing plan since we don't
2350           // exclude the server of the original plan, which should not be
2351           // excluded since it could be the only server up now.
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             // Clean out plan we failed execute and one that doesn't look like it'll
2367             // succeed anyways; we need a new plan!
2368             // Transition back to OFFLINE
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       // Run out of attempts
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     // Remove region from in-memory transition and unassigned node from ZK
2403     // While trying to enable the table the regions of the table were
2404     // already enabled.
2405     LOG.debug("ALREADY_OPENED " + region.getRegionNameAsString()
2406       + " to " + sn);
2407     String encodedName = region.getEncodedName();
2408     
2409     //If use ZkForAssignment, region already Opened event should not be handled, 
2410     //leave it to zk event. See HBase-14407.
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    * Set region as OFFLINED up in zookeeper
2452    *
2453    * @param state
2454    * @return the version of the offline node if setting of the OFFLINE node was
2455    *         successful, -1 otherwise.
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       // get the version after setting the znode to OFFLINE
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    * @param region the region to assign
2483    * @return Plan for passed <code>region</code> (If none currently, it creates one or
2484    * if no servers to assign, it returns null).
2485    */
2486   private RegionPlan getRegionPlan(final HRegionInfo region,
2487       final boolean forceNewPlan)  throws HBaseIOException {
2488     return getRegionPlan(region, null, forceNewPlan);
2489   }
2490 
2491   /**
2492    * @param region the region to assign
2493    * @param serverToExclude Server to exclude (we know its bad). Pass null if
2494    * all servers are thought to be assignable.
2495    * @param forceNewPlan If true, then if an existing plan exists, a new plan
2496    * will be generated.
2497    * @return Plan for passed <code>region</code> (If none currently, it creates one or
2498    * if no servers to assign, it returns null).
2499    */
2500   private RegionPlan getRegionPlan(final HRegionInfo region,
2501       final ServerName serverToExclude, final boolean forceNewPlan) throws HBaseIOException {
2502     // Pickup existing plan or make a new one
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    * Wait for some time before retrying meta table region assignment
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    * Unassigns the specified region.
2578    * <p>
2579    * Updates the RegionState and sends the CLOSE RPC unless region is being
2580    * split by regionserver; then the unassign fails (silently) because we
2581    * presume the region being unassigned no longer exists (its been split out
2582    * of existence). TODO: What to do if split fails and is rolled back and
2583    * parent is revivified?
2584    * <p>
2585    * If a RegionPlan is already set, it will remain.
2586    *
2587    * @param region server to be unassigned
2588    */
2589   public void unassign(HRegionInfo region) {
2590     unassign(region, false);
2591   }
2592 
2593 
2594   /**
2595    * Unassigns the specified region.
2596    * <p>
2597    * Updates the RegionState and sends the CLOSE RPC unless region is being
2598    * split by regionserver; then the unassign fails (silently) because we
2599    * presume the region being unassigned no longer exists (its been split out
2600    * of existence). TODO: What to do if split fails and is rolled back and
2601    * parent is revivified?
2602    * <p>
2603    * If a RegionPlan is already set, it will remain.
2604    *
2605    * @param region server to be unassigned
2606    * @param force if region should be closed even if already closing
2607    */
2608   public void unassign(HRegionInfo region, boolean force, ServerName dest) {
2609     // TODO: Method needs refactoring.  Ugly buried returns throughout.  Beware!
2610     LOG.debug("Starting unassign of " + region.getRegionNameAsString()
2611       + " (offlining), current state: " + regionStates.getRegionState(region));
2612 
2613     String encodedName = region.getEncodedName();
2614     // Grab the state of this region and synchronize on it
2615     int versionOfClosingNode = -1;
2616     // We need a lock here as we're going to do a put later and we don't want multiple states
2617     //  creation
2618     ReentrantLock lock = locker.acquireLock(encodedName);
2619     RegionState state = regionStates.getRegionTransitionState(encodedName);
2620     boolean reassign = true;
2621     try {
2622       if (state == null) {
2623         // Region is not in transition.
2624         // We can unassign it only if it's not SPLIT/MERGED.
2625         state = regionStates.getRegionState(encodedName);
2626         if (state != null && state.isUnassignable()) {
2627           LOG.info("Attempting to unassign " + state + ", ignored");
2628           // Offline region will be reassigned below
2629           return;
2630         }
2631         // Create the znode in CLOSING state
2632         try {
2633           if (state == null || state.getServerName() == null) {
2634             // We don't know where the region is, offline it.
2635             // No need to send CLOSE RPC
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; // not unassigned at all
2649               return;
2650             }
2651           }
2652         } catch (KeeperException e) {
2653           if (e instanceof NodeExistsException) {
2654             // Handle race between master initiated close and regionserver
2655             // orchestrated splitting. See if existing node is in a
2656             // SPLITTING or SPLIT state.  If so, the regionserver started
2657             // an op on node before we could get our CLOSING in.  Deal.
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; // no need to reassign for split/merged region
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           // If we get here, don't understand whats going on -- abort.
2679           server.abort("Unexpected ZK exception creating node CLOSING", e);
2680           reassign = false; // heading out already
2681           return;
2682         }
2683         state = regionStates.updateRegionState(region, State.PENDING_CLOSE);
2684       } else if (state.isFailedOpen()) {
2685         // The region is not open yet
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       // Region is expected to be reassigned afterwards
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    * @param region regioninfo of znode to be deleted.
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    * @param path
2729    * @return True if znode is in SPLIT or SPLITTING or MERGED or MERGING state.
2730    * @throws KeeperException Can happen if the znode went away in meantime.
2731    * @throws DeserializationException
2732    */
2733   private boolean isSplitOrSplittingOrMergedOrMerging(final String path)
2734       throws KeeperException, DeserializationException {
2735     boolean result = false;
2736     // This may fail if the SPLIT or SPLITTING or MERGED or MERGING znode gets
2737     // cleaned up before we can get data from it.
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    * Used by unit tests. Return the number of regions opened so far in the life
2762    * of the master. Increases by one every time the master opens a region
2763    * @return the counter value of the number of regions opened so far
2764    */
2765   public int getNumRegionsOpened() {
2766     return numRegionsOpened.get();
2767   }
2768 
2769   /**
2770    * Waits until the specified region has completed assignment.
2771    * <p>
2772    * If the region is already assigned, returns immediately.  Otherwise, method
2773    * blocks until the region is assigned.
2774    * @param regionInfo region to wait on assignment for
2775    * @return true if the region is assigned false otherwise.
2776    * @throws InterruptedException
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    * Waits until the specified region has completed assignment, or the deadline is reached.
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) { // Overflow
2793       deadline = Long.MAX_VALUE; // wait forever
2794     }
2795     return waitForAssignment(regionSet, waitTillAllAssigned, deadline);
2796   }
2797 
2798   /**
2799    * Waits until the specified region has completed assignment, or the deadline is reached.
2800    * @param regionSet set of region to wait on. the set is modified and the assigned regions removed
2801    * @param waitTillAllAssigned true if we should wait all the regions to be assigned
2802    * @param deadline the timestamp after which the wait is aborted
2803    * @return true if all the regions are assigned false otherwise.
2804    * @throws InterruptedException
2805    */
2806   protected boolean waitForAssignment(final Collection<HRegionInfo> regionSet,
2807       final boolean waitTillAllAssigned, final long deadline) throws InterruptedException {
2808     // We're not synchronizing on regionsInTransition now because we don't use any iterator.
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         // No need to wait, let assignment going on asynchronously
2823         break;
2824       }
2825       if (!regionSet.isEmpty()) {
2826         if (failedOpenCount == regionSet.size()) {
2827           // all the regions we are waiting had an error on open.
2828           break;
2829         }
2830         regionStates.waitForUpdate(100);
2831       }
2832     }
2833     return regionSet.isEmpty();
2834   }
2835 
2836   /**
2837    * Assigns the hbase:meta region or a replica.
2838    * <p>
2839    * Assumes that hbase:meta is currently closed and is not being actively served by
2840    * any RegionServer.
2841    * <p>
2842    * Forcibly unsets the current meta region location in ZooKeeper and assigns
2843    * hbase:meta to a random RegionServer.
2844    * @param hri TODO
2845    * @throws KeeperException
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    * Assigns specified regions retaining assignments, if any.
2854    * <p>
2855    * This is a synchronous call and will return once every region has been
2856    * assigned.  If anything fails, an exception is thrown
2857    * @throws InterruptedException
2858    * @throws IOException
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     // Reuse existing assignment info
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    * Assigns specified regions round robin, if any.
2883    * <p>
2884    * This is a synchronous call and will return once every region has been
2885    * assigned.  If anything fails, an exception is thrown
2886    * @throws InterruptedException
2887    * @throws IOException
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     // Generate a round-robin bulk assignment plan
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       // Not use bulk assignment.  This could be more efficient in small
2919       // cluster, especially mini cluster for testing, so that tests won't time out
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       // invoke assignment (async)
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       // wait for assignment completion
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       // Use fixed count thread pool assigning.
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    * Assigns all user regions, if any exist.  Used during cluster startup.
2959    * <p>
2960    * This is a synchronous call and will return once every region has been
2961    * assigned.  If anything fails, an exception is thrown and the cluster
2962    * should be shutdown.
2963    * @throws InterruptedException
2964    * @throws IOException
2965    */
2966   private void assignAllUserRegions(Map<HRegionInfo, ServerName> allRegions)
2967       throws IOException, InterruptedException {
2968     if (allRegions == null || allRegions.isEmpty()) return;
2969 
2970     // Determine what type of assignment to do on startup
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     // assign all the replicas that were not recorded in the meta
2990     assign(replicaRegionsNotRecordedInMeta(regionsFromMetaScan, server));
2991   }
2992 
2993   /**
2994    * Get a list of replica regions that are:
2995    * not recorded in meta yet. We might not have recorded the locations
2996    * for the replicas since the replicas may not have been online yet, master restarted
2997    * in the middle of assigning, ZK erased, etc.
2998    * @param regionsRecordedInMeta the list of regions we know are recorded in meta
2999    * either as a default, or, as the location of a replica
3000    * @param master
3001    * @return list of replica regions
3002    * @throws IOException
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       // look at the HTD for the replica count. That's the source of truth
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    * Wait until no regions in transition.
3023    * @param timeout How long to wait.
3024    * @return True if nothing in regions in transition.
3025    * @throws InterruptedException
3026    */
3027   boolean waitUntilNoRegionsInTransition(final long timeout)
3028       throws InterruptedException {
3029     // Blocks until there are no regions in transition. It is possible that
3030     // there
3031     // are regions in transition immediately after this returns but guarantees
3032     // that if it returns without an exception that there was a period of time
3033     // with no regions in transition from the point-of-view of the in-memory
3034     // state of the Master.
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    * Rebuild the list of user regions and assignment information.
3047    * Updates regionstates with findings as we go through list of regions.
3048    * @return set of servers not online that hosted some regions according to a scan of hbase:meta
3049    * @throws IOException
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     // Region assignment from META
3062     List<Result> results = MetaTableAccessor.fullScanOfMeta(server.getConnection());
3063     // Get any new but slow to checkin region server that joined the cluster
3064     Set<ServerName> onlineServers = serverManager.getOnlineServers().keySet();
3065     // Set of offline servers to be returned
3066     Set<ServerName> offlineServers = new HashSet<ServerName>();
3067     // Iterate regions in META
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       // keep a track of replicas to close. These were the replicas of the originally
3074       // unmerged regions. The master might have closed them before but it mightn't
3075       // maybe because it crashed.
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         // keep a track of replicas to close. These were the replicas of the split parents
3097         // from the previous life of the master. The master should have closed them before
3098         // but it couldn't maybe because it crashed
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           // force region to forget it hosts for disabled/disabling tables.
3109           // see HBASE-13326
3110           lastHost = null;
3111           regionLocation = null;
3112         }
3113         regionStates.createRegionState(regionInfo, state, regionLocation, lastHost);
3114         if (!regionStates.isRegionInState(regionInfo, State.OPEN)) {
3115           // Region is not open (either offline or in transition), skip
3116           continue;
3117         }
3118         TableName tableName = regionInfo.getTable();
3119         if (!onlineServers.contains(regionLocation)) {
3120           // Region is located on a server that isn't online
3121           offlineServers.add(regionLocation);
3122           if (useZKForAssignment) {
3123             regionStates.regionOffline(regionInfo);
3124           }
3125         } else if (!disabledOrEnablingTables.contains(tableName)) {
3126           // Region is being served and on an active server
3127           // add only if region not in disabled or enabling table
3128           regionStates.regionOnline(regionInfo, regionLocation);
3129           balancer.regionOnline(regionInfo, regionLocation);
3130         } else if (useZKForAssignment) {
3131           regionStates.regionOffline(regionInfo);
3132         }
3133         // need to enable the table if not disabled or disabling or enabling
3134         // this will be used in rolling restarts
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    * Recover the tables that were not fully moved to DISABLED state. These
3147    * tables are in DISABLING state when the master restarted/switched.
3148    *
3149    * @throws KeeperException
3150    * @throws TableNotFoundException
3151    * @throws IOException
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         // Recover by calling DisableTableHandler
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    * Recover the tables that are not fully moved to ENABLED state. These tables
3171    * are in ENABLING state when the master restarted/switched
3172    *
3173    * @throws KeeperException
3174    * @throws org.apache.hadoop.hbase.TableNotFoundException
3175    * @throws IOException
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         // Recover by calling EnableTableHandler
3184         LOG.info("The table " + tableName
3185             + " is in ENABLING state.  Hence recovering by moving the table"
3186             + " to ENABLED state.");
3187         // enableTable in sync way during master startup,
3188         // no need to invoke coprocessor
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    * Processes list of dead servers from result of hbase:meta scan and regions in RIT.
3204    * This is used for failover to recover the lost regions that belonged to
3205    * RegionServers which failed while there was no active master or are offline for whatever
3206    * reason and for regions that were in RIT.
3207    *
3208    * @param deadServers
3209    *          The list of dead servers which failed while there was no active master. Can be null.
3210    * @throws IOException
3211    * @throws KeeperException
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); // Let SSH do region re-assign
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     // We need to send RPC call again for PENDING_OPEN/PENDING_CLOSE regions
3237     // in case the RPC call is not sent out yet before the master was shut down
3238     // since we update the state before we send the RPC call. We can't update
3239     // the state after the RPC call. Otherwise, we don't know what's happened
3240     // to the region if the master dies right after the RPC call is out.
3241     Map<String, RegionState> rits = regionStates.getRegionsInTransition();
3242     for (RegionState regionState : rits.values()) {
3243       LOG.info("Processing " + regionState);
3244       ServerName serverName = regionState.getServerName();
3245       // Server could be null in case of FAILED_OPEN when master cannot find a region plan. In that
3246       // case, try assigning it here.
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         // No process for other states
3271       }
3272     }
3273   }
3274 
3275   /**
3276    * At master failover, for pending_open region, make sure
3277    * sendRegionOpen RPC call is sent to the target regionserver
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; // No need any more
3292               }
3293               try {
3294                 if (!regionState.equals(regionStates.getRegionState(hri))) {
3295                   return; // Region is not in the expected state any more
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                   // Failed opening this region, this means the target server didn't get
3306                   // the original region open RPC, so re-assign it with a new plan
3307                   LOG.debug("Got failed_opening in retry sendRegionOpen for "
3308                     + regionState + ", re-assign it");
3309                   invokeAssign(hri, true);
3310                 }
3311                 return; // Done.
3312               } catch (Throwable t) {
3313                 if (t instanceof RemoteException) {
3314                   t = ((RemoteException) t).unwrapRemoteException();
3315                 }
3316                 // In case SocketTimeoutException/FailedServerException, retry
3317                 if (t instanceof java.net.SocketTimeoutException
3318                     || t instanceof FailedServerException) {
3319                   Threads.sleep(100);
3320                   continue;
3321                 }
3322                 // For other exceptions, re-assign it
3323                 LOG.debug("Got exception in retry sendRegionOpen for "
3324                   + regionState + ", re-assign it", t);
3325                 invokeAssign(hri);
3326                 return; // Done.
3327               }
3328             }
3329           } finally {
3330             lock.unlock();
3331           }
3332         }
3333       });
3334   }
3335 
3336   /**
3337    * At master failover, for pending_close region, make sure
3338    * sendRegionClose RPC call is sent to the target regionserver
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; // No need any more
3353               }
3354               try {
3355                 if (!regionState.equals(regionStates.getRegionState(hri))) {
3356                   return; // Region is not in the expected state any more
3357                 }
3358                 if (!serverManager.sendRegionClose(serverName, hri, -1, null, false)) {
3359                   // This means the region is still on the target server
3360                   LOG.debug("Got false in retry sendRegionClose for "
3361                     + regionState + ", re-close it");
3362                   invokeUnAssign(hri);
3363                 }
3364                 return; // Done.
3365               } catch (Throwable t) {
3366                 if (t instanceof RemoteException) {
3367                   t = ((RemoteException) t).unwrapRemoteException();
3368                 }
3369                 // In case SocketTimeoutException/FailedServerException, retry
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                   // NotServingRegionException/RegionAlreadyInTransitionException
3378                   // means the target server got the original region close request.
3379                   // For other exceptions, re-close it
3380                   LOG.debug("Got exception in retry sendRegionClose for "
3381                     + regionState + ", re-close it", t);
3382                   invokeUnAssign(hri);
3383                 }
3384                 return; // Done.
3385               }
3386             }
3387           } finally {
3388             lock.unlock();
3389           }
3390         }
3391       });
3392   }
3393 
3394   /**
3395    * Set Regions in transitions metrics.
3396    * This takes an iterator on the RegionInTransition map (CLSM), and is not synchronized.
3397    * This iterator is not fail fast, which may lead to stale read; but that's better than
3398    * creating a copy of the map for metrics computation, as this method will be invoked
3399    * on a frequent interval.
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) { // more than the threshold
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    * @param region Region whose plan we are to clear.
3427    */
3428   void clearRegionPlan(final HRegionInfo region) {
3429     synchronized (this.regionPlans) {
3430       this.regionPlans.remove(region.getEncodedName());
3431     }
3432   }
3433 
3434   /**
3435    * Wait on region to clear regions-in-transition.
3436    * @param hri Region to wait on.
3437    * @throws IOException
3438    */
3439   public void waitOnRegionToClearRegionsInTransition(final HRegionInfo hri)
3440       throws IOException, InterruptedException {
3441     waitOnRegionToClearRegionsInTransition(hri, -1L);
3442   }
3443 
3444   /**
3445    * Wait on region to clear regions-in-transition or time out
3446    * @param hri
3447    * @param timeOut Milliseconds to wait for current region to be out of transition state.
3448    * @return True when a region clears regions-in-transition before timeout otherwise false
3449    * @throws InterruptedException
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     // There is already a timeout monitor on regions in transition so I
3457     // should not have to have one here too?
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    * Check if the shutdown server carries the specific region.
3501    * We have a bunch of places that store region location
3502    * Those values aren't consistent. There is a delay of notification.
3503    * The location from zookeeper unassigned node has the most recent data;
3504    * but the node could be deleted after the region is opened by AM.
3505    * The AM's info could be old when OpenedRegionHandler
3506    * processing hasn't finished yet when server shutdown occurs.
3507    * @return whether the serverName currently hosts the region
3508    */
3509   private ServerHostRegion isCarryingRegion(ServerName serverName, HRegionInfo hri) {
3510     RegionTransition rt = null;
3511     try {
3512       byte [] data = ZKAssign.getData(watcher, hri.getEncodedName());
3513       // This call can legitimately come by null
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       // if we get something from ZK, we will use the data
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       // For the Meta region (default replica), we can do one more check on MetaTableLocator
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     // Checked everywhere, if reaching here, we are unsure whether the server is carrying region.
3557     return ServerHostRegion.UNKNOWN;
3558   }
3559 
3560   /**
3561    * Clean out crashed server removing any assignments.
3562    * @param sn Server that went down.
3563    * @return list of regions in transition on this server
3564    */
3565   public List<HRegionInfo> cleanOutCrashedServerReferences(final ServerName sn) {
3566     // Clean out any existing assignment plans for this server
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         // The name will be null if the region is planned for a random assign.
3573         if (otherSn != null && otherSn.equals(sn)) {
3574           // Use iterator's remove else we'll get CME
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       // We need a lock on the region as we could update it
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             // Delete the ZNode if exists
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           // Mark the region offline and assign it again by SSH
3609           regionStates.updateRegionState(hri, State.OFFLINE);
3610         }
3611       } finally {
3612         lock.unlock();
3613       }
3614     }
3615     return regions;
3616   }
3617 
3618   /**
3619    * @param plan Plan to execute.
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     // Move the region only if it's assigned
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(); // Stop executor service, etc
3653   }
3654 
3655   /**
3656    * Shutdown the threadpool executor service
3657    */
3658   public void shutdown() {
3659     // It's an immediate shutdown, so we're clearing the remaining tasks.
3660     synchronized (zkEventWorkerWaitingList){
3661       zkEventWorkerWaitingList.clear();
3662     }
3663 
3664     // Shutdown the threadpool executor service
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       // here we can abort as it is the start up flow
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    * Set region as OFFLINED up in zookeeper asynchronously.
3685    * @param state
3686    * @return True if we succeeded, false otherwise (State was incorrect or failed
3687    * updating zk).
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     // FindBugs: AT_OPERATION_SEQUENCE_ON_CONCURRENT_ABSTRACTION Worth fixing!!!
3749     AtomicInteger failedOpenCount = failedOpenTracker.get(encodedName);
3750     if (failedOpenCount == null) {
3751       failedOpenCount = new AtomicInteger();
3752       // No need to use putIfAbsent, or extra synchronization since
3753       // this whole handleRegion block is locked on the encoded region
3754       // name, and failedOpenTracker is updated only in this block
3755       // FindBugs: AT_OPERATION_SEQUENCE_ON_CONCURRENT_ABSTRACTION
3756       failedOpenTracker.put(encodedName, failedOpenCount);
3757     }
3758     if (failedOpenCount.incrementAndGet() >= maximumAttempts && !hri.isMetaRegion()) {
3759       // FindBugs: AT_OPERATION_SEQUENCE_ON_CONCURRENT_ABSTRACTION
3760       regionStates.updateRegionState(hri, State.FAILED_OPEN);
3761       // remove the tracking info to save memory, also reset
3762       // the count for next open initiative
3763       failedOpenTracker.remove(encodedName);
3764     } else {
3765       if (hri.isMetaRegion() && failedOpenCount.get() >= maximumAttempts) {
3766         // Log a warning message if a meta region failedOpenCount exceeds maximumAttempts
3767         // so that we are aware of potential problem if it persists for a long time.
3768         LOG.warn("Failed to open the hbase:meta region " +
3769             hri.getRegionNameAsString() + " after" +
3770             failedOpenCount.get() + " retries. Continue retrying.");
3771       }
3772 
3773       // Handle this the same as if it were opened and then closed.
3774       RegionState regionState = regionStates.updateRegionState(hri, State.CLOSED);
3775       if (regionState != null) {
3776         // When there are more than one region server a new RS is selected as the
3777         // destination and the same is updated in the region plan. (HBASE-5546)
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         // ZK Node is in CLOSED state, assign it.
3785          regionStates.updateRegionState(hri, RegionState.State.CLOSED);
3786         // This below has to do w/ online enable/disable of a table
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         // Delete the ZNode if exists
3803         ZKAssign.deleteNodeFailSilent(watcher, hri);
3804       } catch (KeeperException ke) {
3805         server.abort("Unexpected ZK exception deleting node " + hri, ke);
3806       }
3807     }
3808 
3809     // reset the count, if any
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     // This below has to do w/ online enable/disable of a table
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     // Always bring the parent back online. Even if it's not offline
3852     // There's no harm in making it online again.
3853     regionOnline(p, sn);
3854 
3855     // Only offline the region if they are known to exist.
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       // User could disable the table before master knows the new region.
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       // User could disable the table before master knows the new region.
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     // Always bring the children back online. Even if they are not offline
3976     // there's no harm in making them online again.
3977     regionOnline(a, sn);
3978     regionOnline(b, sn);
3979 
3980     // Only offline the merging region if it is known to exist.
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    * A helper to handle region merging transition event.
3996    * It transitions merging regions to MERGING state.
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; // return true so that the merging node stays
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       // Remove region from ZK
4085       try {
4086         boolean successful = false;
4087         while (!successful) {
4088           // It's possible that the RS tickles in between the reading of the
4089           // znode and the deleting, so it's safe to retry.
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       // User could disable the table before master knows the new region.
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    * A helper to handle region splitting transition event.
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       // Splitting region should be online
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       // The below is for testing ONLY!  We can't do fault injection easily, so
4196       // resort to this kinda uglyness -- St.Ack 02/25/2011.
4197       if (TEST_SKIP_SPLIT_HANDLING) {
4198         LOG.warn("Skipping split message, TEST_SKIP_SPLIT_HANDLING is set");
4199         return true; // return true so that the splitting node stays
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       // split replicas
4212       doSplittingOfReplicas(rs_p.getRegion(), hri_a, hri_b);
4213       LOG.debug("Handling SPLIT event for " + encodedName + "; deleting node");
4214       // Remove region from ZK
4215       try {
4216         boolean successful = false;
4217         while (!successful) {
4218           // It's possible that the RS tickles in between the reading of the
4219           // znode and the deleting, so it's safe to retry.
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       // User could disable the table before master knows the new region.
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     // Close replicas for the original unmerged regions. create/assign new replicas
4248     // for the merged parent.
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     // Remove merged region's replica from AM's memory
4285     clearReplicaRegions(c);
4286   }
4287 
4288   private void doSplittingOfReplicas(final HRegionInfo parentHri, final HRegionInfo hri_a,
4289       final HRegionInfo hri_b) {
4290     // create new regions for the replica, and assign them to match with the
4291     // current replica assignments. If replica1 of parent is assigned to RS1,
4292     // the replica1s of daughters will be on the same machine
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     // unassign the old replicas
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     // assign daughter replicas
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     // Remove parent region's replica from AM's memory
4330     clearReplicaRegions(c);
4331   }
4332 
4333   /*
4334    * Clear the replica regions after region split or merge.
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    * A region is offline.  The new state should be the specified one,
4368    * if not null.  If the specified state is null, the new state is Offline.
4369    * The specified state can be Split/Merged/Offline/null only.
4370    */
4371   private void regionOffline(final HRegionInfo regionInfo, final State state) {
4372     regionStates.regionOffline(regionInfo, state);
4373     removeClosedRegion(regionInfo);
4374     // remove the region plan as well just in case.
4375     clearRegionPlan(regionInfo);
4376     balancer.regionOffline(regionInfo);
4377 
4378     // Tell our listeners that a region was closed
4379     sendRegionClosedNotification(regionInfo);
4380     // also note that all the replicas of the primary should be closed
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    * Try to update some region states. If the state machine prevents
4420    * such update, an error message is returned to explain the reason.
4421    *
4422    * It's expected that in each transition there should have just one
4423    * region for opening/closing, 3 regions for splitting/merging.
4424    * These regions should be on the server that requested the change.
4425    *
4426    * Region state machine. Only these transitions
4427    * are expected to be triggered by a region server.
4428    *
4429    * On the state transition:
4430    *  (1) Open/Close should be initiated by master
4431    *      (a) Master sets the region to pending_open/pending_close
4432    *        in memory and hbase:meta after sending the request
4433    *        to the region server
4434    *      (b) Region server reports back to the master
4435    *        after open/close is done (either success/failure)
4436    *      (c) If region server has problem to report the status
4437    *        to master, it must be because the master is down or some
4438    *        temporary network issue. Otherwise, the region server should
4439    *        abort since it must be a bug. If the master is not accessible,
4440    *        the region server should keep trying until the server is
4441    *        stopped or till the status is reported to the (new) master
4442    *      (d) If region server dies in the middle of opening/closing
4443    *        a region, SSH picks it up and finishes it
4444    *      (e) If master dies in the middle, the new master recovers
4445    *        the state during initialization from hbase:meta. Region server
4446    *        can report any transition that has not been reported to
4447    *        the previous active master yet
4448    *  (2) Split/merge is initiated by region servers
4449    *      (a) To split a region, a region server sends a request
4450    *        to master to try to set a region to splitting, together with
4451    *        two daughters (to be created) to splitting new. If approved
4452    *        by the master, the splitting can then move ahead
4453    *      (b) To merge two regions, a region server sends a request to
4454    *        master to try to set the new merged region (to be created) to
4455    *        merging_new, together with two regions (to be merged) to merging.
4456    *        If it is ok with the master, the merge can then move ahead
4457    *      (c) Once the splitting/merging is done, the region server
4458    *        reports the status back to the master either success/failure.
4459    *      (d) Other scenarios should be handled similarly as for
4460    *        region open/close
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       // Break out only for errors, otherwise fall through
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       // Break out only for errors, otherwise fall through
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    * @return Instance of load balancer
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    * This is only used for unit-testing split failures.
4597    */
4598   @VisibleForTesting
4599   public static void setTestSkipSplitHandling(boolean skipSplitHandling) {
4600     TEST_SKIP_SPLIT_HANDLING = skipSplitHandling;
4601   }
4602 
4603   /*
4604    * This is only used for unit-testing merge failures.
4605    */
4606   @VisibleForTesting
4607   public static void setTestSkipMergeHandling(boolean skipMergeHandling) {
4608     TEST_SKIP_MERGE_HANDLING = skipMergeHandling;
4609   }
4610 }