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