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