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.util.ArrayList;
23  import java.util.Collection;
24  import java.util.Collections;
25  import java.util.HashMap;
26  import java.util.HashSet;
27  import java.util.Iterator;
28  import java.util.List;
29  import java.util.Map;
30  import java.util.NavigableMap;
31  import java.util.Random;
32  import java.util.Set;
33  import java.util.TreeMap;
34  import java.util.concurrent.Callable;
35  import java.util.concurrent.ConcurrentHashMap;
36  import java.util.concurrent.CopyOnWriteArrayList;
37  import java.util.concurrent.TimeUnit;
38  import java.util.concurrent.atomic.AtomicBoolean;
39  import java.util.concurrent.atomic.AtomicInteger;
40  import java.util.concurrent.locks.Lock;
41  import java.util.concurrent.locks.ReentrantLock;
42  
43  import org.apache.commons.logging.Log;
44  import org.apache.commons.logging.LogFactory;
45  import org.apache.hadoop.hbase.classification.InterfaceAudience;
46  import org.apache.hadoop.conf.Configuration;
47  import org.apache.hadoop.fs.FileSystem;
48  import org.apache.hadoop.fs.Path;
49  import org.apache.hadoop.hbase.HBaseIOException;
50  import org.apache.hadoop.hbase.HConstants;
51  import org.apache.hadoop.hbase.HRegionInfo;
52  import org.apache.hadoop.hbase.HRegionLocation;
53  import org.apache.hadoop.hbase.HTableDescriptor;
54  import org.apache.hadoop.hbase.MetaTableAccessor;
55  import org.apache.hadoop.hbase.NotServingRegionException;
56  import org.apache.hadoop.hbase.RegionLocations;
57  import org.apache.hadoop.hbase.Server;
58  import org.apache.hadoop.hbase.ServerName;
59  import org.apache.hadoop.hbase.TableName;
60  import org.apache.hadoop.hbase.TableNotFoundException;
61  import org.apache.hadoop.hbase.client.RegionReplicaUtil;
62  import org.apache.hadoop.hbase.client.Result;
63  import org.apache.hadoop.hbase.client.TableState;
64  import org.apache.hadoop.hbase.executor.EventHandler;
65  import org.apache.hadoop.hbase.executor.EventType;
66  import org.apache.hadoop.hbase.executor.ExecutorService;
67  import org.apache.hadoop.hbase.ipc.RpcClient;
68  import org.apache.hadoop.hbase.ipc.RpcClient.FailedServerException;
69  import org.apache.hadoop.hbase.ipc.ServerNotRunningYetException;
70  import org.apache.hadoop.hbase.master.RegionState.State;
71  import org.apache.hadoop.hbase.master.balancer.FavoredNodeAssignmentHelper;
72  import org.apache.hadoop.hbase.master.balancer.FavoredNodeLoadBalancer;
73  import org.apache.hadoop.hbase.master.handler.DisableTableHandler;
74  import org.apache.hadoop.hbase.master.handler.EnableTableHandler;
75  import org.apache.hadoop.hbase.protobuf.generated.RegionServerStatusProtos.RegionStateTransition;
76  import org.apache.hadoop.hbase.protobuf.generated.RegionServerStatusProtos.RegionStateTransition.TransitionCode;
77  import org.apache.hadoop.hbase.regionserver.RegionOpeningState;
78  import org.apache.hadoop.hbase.regionserver.RegionServerStoppedException;
79  import org.apache.hadoop.hbase.wal.DefaultWALProvider;
80  import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
81  import org.apache.hadoop.hbase.util.FSUtils;
82  import org.apache.hadoop.hbase.util.KeyLocker;
83  import org.apache.hadoop.hbase.util.Pair;
84  import org.apache.hadoop.hbase.util.PairOfSameType;
85  import org.apache.hadoop.hbase.util.Threads;
86  import org.apache.hadoop.hbase.zookeeper.MetaTableLocator;
87  import org.apache.hadoop.ipc.RemoteException;
88  import org.apache.zookeeper.KeeperException;
89  
90  import com.google.common.annotations.VisibleForTesting;
91  
92  /**
93   * Manages and performs region assignment.
94   * Related communications with regionserver are all done over RPC.
95   */
96  @InterfaceAudience.Private
97  public class AssignmentManager {
98    private static final Log LOG = LogFactory.getLog(AssignmentManager.class);
99  
100   protected final Server server;
101 
102   private ServerManager serverManager;
103 
104   private boolean shouldAssignRegionsWithFavoredNodes;
105 
106   private LoadBalancer balancer;
107 
108   private final MetricsAssignmentManager metricsAssignmentManager;
109 
110   private final TableLockManager tableLockManager;
111 
112   private AtomicInteger numRegionsOpened = new AtomicInteger(0);
113 
114   final private KeyLocker<String> locker = new KeyLocker<String>();
115 
116   Set<HRegionInfo> replicasToClose = Collections.synchronizedSet(new HashSet<HRegionInfo>());
117 
118   /**
119    * Map of regions to reopen after the schema of a table is changed. Key -
120    * encoded region name, value - HRegionInfo
121    */
122   private final Map <String, HRegionInfo> regionsToReopen;
123 
124   /*
125    * Maximum times we recurse an assignment/unassignment.
126    * See below in {@link #assign()} and {@link #unassign()}.
127    */
128   private final int maximumAttempts;
129 
130   /**
131    * The sleep time for which the assignment will wait before retrying in case of hbase:meta assignment
132    * failure due to lack of availability of region plan
133    */
134   private final long sleepTimeBeforeRetryingMetaAssignment;
135 
136   /** Plans for region movement. Key is the encoded version of a region name*/
137   // TODO: When do plans get cleaned out?  Ever? In server open and in server
138   // shutdown processing -- St.Ack
139   // All access to this Map must be synchronized.
140   final NavigableMap<String, RegionPlan> regionPlans =
141     new TreeMap<String, RegionPlan>();
142 
143   private final TableStateManager tableStateManager;
144 
145   private final ExecutorService executorService;
146 
147   // Thread pool executor service. TODO, consolidate with executorService?
148   private java.util.concurrent.ExecutorService threadPoolExecutorService;
149 
150   private final RegionStates regionStates;
151 
152   // The threshold to use bulk assigning. Using bulk assignment
153   // only if assigning at least this many regions to at least this
154   // many servers. If assigning fewer regions to fewer servers,
155   // bulk assigning may be not as efficient.
156   private final int bulkAssignThresholdRegions;
157   private final int bulkAssignThresholdServers;
158 
159   // Should bulk assignment wait till all regions are assigned,
160   // or it is timed out?  This is useful to measure bulk assignment
161   // performance, but not needed in most use cases.
162   private final boolean bulkAssignWaitTillAllAssigned;
163 
164   /**
165    * Indicator that AssignmentManager has recovered the region states so
166    * that ServerShutdownHandler can be fully enabled and re-assign regions
167    * of dead servers. So that when re-assignment happens, AssignmentManager
168    * has proper region states.
169    *
170    * Protected to ease testing.
171    */
172   protected final AtomicBoolean failoverCleanupDone = new AtomicBoolean(false);
173 
174   /**
175    * A map to track the count a region fails to open in a row.
176    * So that we don't try to open a region forever if the failure is
177    * unrecoverable.  We don't put this information in region states
178    * because we don't expect this to happen frequently; we don't
179    * want to copy this information over during each state transition either.
180    */
181   private final ConcurrentHashMap<String, AtomicInteger>
182     failedOpenTracker = new ConcurrentHashMap<String, AtomicInteger>();
183 
184   // In case not using ZK for region assignment, region states
185   // are persisted in meta with a state store
186   private final RegionStateStore regionStateStore;
187 
188   /**
189    * For testing only!  Set to true to skip handling of split.
190    */
191   @edu.umd.cs.findbugs.annotations.SuppressWarnings(value="MS_SHOULD_BE_FINAL")
192   public static boolean TEST_SKIP_SPLIT_HANDLING = false;
193 
194   /** Listeners that are called on assignment events. */
195   private List<AssignmentListener> listeners = new CopyOnWriteArrayList<AssignmentListener>();
196 
197   /**
198    * Constructs a new assignment manager.
199    *
200    * @param server instance of HMaster this AM running inside
201    * @param serverManager serverManager for associated HMaster
202    * @param balancer implementation of {@link LoadBalancer}
203    * @param service Executor service
204    * @param metricsMaster metrics manager
205    * @param tableLockManager TableLock manager
206    * @throws IOException
207    */
208   public AssignmentManager(Server server, ServerManager serverManager,
209       final LoadBalancer balancer,
210       final ExecutorService service, MetricsMaster metricsMaster,
211       final TableLockManager tableLockManager,
212       final TableStateManager tableStateManager)
213           throws IOException {
214     this.server = server;
215     this.serverManager = serverManager;
216     this.executorService = service;
217     this.regionStateStore = new RegionStateStore(server);
218     this.regionsToReopen = Collections.synchronizedMap
219                            (new HashMap<String, HRegionInfo> ());
220     Configuration conf = server.getConfiguration();
221     // Only read favored nodes if using the favored nodes load balancer.
222     this.shouldAssignRegionsWithFavoredNodes = conf.getClass(
223            HConstants.HBASE_MASTER_LOADBALANCER_CLASS, Object.class).equals(
224            FavoredNodeLoadBalancer.class);
225 
226     this.tableStateManager = tableStateManager;
227 
228     // This is the max attempts, not retries, so it should be at least 1.
229     this.maximumAttempts = Math.max(1,
230       this.server.getConfiguration().getInt("hbase.assignment.maximum.attempts", 10));
231     this.sleepTimeBeforeRetryingMetaAssignment = this.server.getConfiguration().getLong(
232         "hbase.meta.assignment.retry.sleeptime", 1000l);
233     this.balancer = balancer;
234     int maxThreads = conf.getInt("hbase.assignment.threads.max", 30);
235     this.threadPoolExecutorService = Threads.getBoundedCachedThreadPool(
236       maxThreads, 60L, TimeUnit.SECONDS, Threads.newDaemonThreadFactory("AM."));
237     this.regionStates = new RegionStates(
238       server, tableStateManager, serverManager, regionStateStore);
239 
240     this.bulkAssignWaitTillAllAssigned =
241       conf.getBoolean("hbase.bulk.assignment.waittillallassigned", false);
242     this.bulkAssignThresholdRegions = conf.getInt("hbase.bulk.assignment.threshold.regions", 7);
243     this.bulkAssignThresholdServers = conf.getInt("hbase.bulk.assignment.threshold.servers", 3);
244 
245     this.metricsAssignmentManager = new MetricsAssignmentManager();
246     this.tableLockManager = tableLockManager;
247   }
248 
249   /**
250    * Add the listener to the notification list.
251    * @param listener The AssignmentListener to register
252    */
253   public void registerListener(final AssignmentListener listener) {
254     this.listeners.add(listener);
255   }
256 
257   /**
258    * Remove the listener from the notification list.
259    * @param listener The AssignmentListener to unregister
260    */
261   public boolean unregisterListener(final AssignmentListener listener) {
262     return this.listeners.remove(listener);
263   }
264 
265   /**
266    * @return Instance of ZKTableStateManager.
267    */
268   public TableStateManager getTableStateManager() {
269     // These are 'expensive' to make involving trip to zk ensemble so allow
270     // sharing.
271     return this.tableStateManager;
272   }
273 
274   /**
275    * This SHOULD not be public. It is public now
276    * because of some unit tests.
277    *
278    * TODO: make it package private and keep RegionStates in the master package
279    */
280   public RegionStates getRegionStates() {
281     return regionStates;
282   }
283 
284   /**
285    * Used in some tests to mock up region state in meta
286    */
287   @VisibleForTesting
288   RegionStateStore getRegionStateStore() {
289     return regionStateStore;
290   }
291 
292   public RegionPlan getRegionReopenPlan(HRegionInfo hri) {
293     return new RegionPlan(hri, null, regionStates.getRegionServerOfRegion(hri));
294   }
295 
296   /**
297    * Add a regionPlan for the specified region.
298    * @param encodedName
299    * @param plan
300    */
301   public void addPlan(String encodedName, RegionPlan plan) {
302     synchronized (regionPlans) {
303       regionPlans.put(encodedName, plan);
304     }
305   }
306 
307   /**
308    * Add a map of region plans.
309    */
310   public void addPlans(Map<String, RegionPlan> plans) {
311     synchronized (regionPlans) {
312       regionPlans.putAll(plans);
313     }
314   }
315 
316   /**
317    * Set the list of regions that will be reopened
318    * because of an update in table schema
319    *
320    * @param regions
321    *          list of regions that should be tracked for reopen
322    */
323   public void setRegionsToReopen(List <HRegionInfo> regions) {
324     for(HRegionInfo hri : regions) {
325       regionsToReopen.put(hri.getEncodedName(), hri);
326     }
327   }
328 
329   /**
330    * Used by the client to identify if all regions have the schema updates
331    *
332    * @param tableName
333    * @return Pair indicating the status of the alter command
334    * @throws IOException
335    */
336   public Pair<Integer, Integer> getReopenStatus(TableName tableName)
337       throws IOException {
338     List<HRegionInfo> hris;
339     if (TableName.META_TABLE_NAME.equals(tableName)) {
340       hris = new MetaTableLocator().getMetaRegions(server.getZooKeeper());
341     } else {
342       hris = MetaTableAccessor.getTableRegions(server.getShortCircuitConnection(), tableName, true);
343     }
344 
345     Integer pending = 0;
346     for (HRegionInfo hri : hris) {
347       String name = hri.getEncodedName();
348       // no lock concurrent access ok: sequential consistency respected.
349       if (regionsToReopen.containsKey(name)
350           || regionStates.isRegionInTransition(name)) {
351         pending++;
352       }
353     }
354     return new Pair<Integer, Integer>(pending, hris.size());
355   }
356 
357   /**
358    * Used by ServerShutdownHandler to make sure AssignmentManager has completed
359    * the failover cleanup before re-assigning regions of dead servers. So that
360    * when re-assignment happens, AssignmentManager has proper region states.
361    */
362   public boolean isFailoverCleanupDone() {
363     return failoverCleanupDone.get();
364   }
365 
366   /**
367    * To avoid racing with AM, external entities may need to lock a region,
368    * for example, when SSH checks what regions to skip re-assigning.
369    */
370   public Lock acquireRegionLock(final String encodedName) {
371     return locker.acquireLock(encodedName);
372   }
373 
374   /**
375    * Now, failover cleanup is completed. Notify server manager to
376    * process queued up dead servers processing, if any.
377    */
378   void failoverCleanupDone() {
379     failoverCleanupDone.set(true);
380     serverManager.processQueuedDeadServers();
381   }
382 
383   /**
384    * Called on startup.
385    * Figures whether a fresh cluster start of we are joining extant running cluster.
386    * @throws IOException
387    * @throws KeeperException
388    * @throws InterruptedException
389    */
390   void joinCluster() throws IOException,
391           KeeperException, InterruptedException {
392     long startTime = System.currentTimeMillis();
393     // Concurrency note: In the below the accesses on regionsInTransition are
394     // outside of a synchronization block where usually all accesses to RIT are
395     // synchronized.  The presumption is that in this case it is safe since this
396     // method is being played by a single thread on startup.
397 
398     // TODO: Regions that have a null location and are not in regionsInTransitions
399     // need to be handled.
400 
401     // Scan hbase:meta to build list of existing regions, servers, and assignment
402     // Returns servers who have not checked in (assumed dead) that some regions
403     // were assigned to (according to the meta)
404     Set<ServerName> deadServers = rebuildUserRegions();
405 
406     // This method will assign all user regions if a clean server startup or
407     // it will reconstruct master state and cleanup any leftovers from
408     // previous master process.
409     boolean failover = processDeadServersAndRegionsInTransition(deadServers);
410 
411     recoverTableInDisablingState();
412     recoverTableInEnablingState();
413     LOG.info("Joined the cluster in " + (System.currentTimeMillis()
414       - startTime) + "ms, failover=" + failover);
415   }
416 
417   /**
418    * Process all regions that are in transition in zookeeper and also
419    * processes the list of dead servers by scanning the META.
420    * Used by master joining an cluster.  If we figure this is a clean cluster
421    * startup, will assign all user regions.
422    * @param deadServers
423    *          Map of dead servers and their regions. Can be null.
424    * @throws IOException
425    * @throws InterruptedException
426    */
427   boolean processDeadServersAndRegionsInTransition(final Set<ServerName> deadServers)
428           throws IOException, InterruptedException {
429     boolean failover = !serverManager.getDeadServers().isEmpty();
430     if (failover) {
431       // This may not be a failover actually, especially if meta is on this master.
432       if (LOG.isDebugEnabled()) {
433         LOG.debug("Found dead servers out on cluster " + serverManager.getDeadServers());
434       }
435     } else {
436       // If any one region except meta is assigned, it's a failover.
437       Set<ServerName> onlineServers = serverManager.getOnlineServers().keySet();
438       for (Map.Entry<HRegionInfo, ServerName> en:
439           regionStates.getRegionAssignments().entrySet()) {
440         HRegionInfo hri = en.getKey();
441         if (!hri.isMetaTable()
442             && onlineServers.contains(en.getValue())) {
443           LOG.debug("Found " + hri + " out on cluster");
444           failover = true;
445           break;
446         }
447       }
448       if (!failover) {
449         // If any region except meta is in transition on a live server, it's a failover.
450         Map<String, RegionState> regionsInTransition = regionStates.getRegionsInTransition();
451         if (!regionsInTransition.isEmpty()) {
452           for (RegionState regionState: regionsInTransition.values()) {
453             if (!regionState.getRegion().isMetaRegion()
454                 && onlineServers.contains(regionState.getServerName())) {
455               LOG.debug("Found " + regionState + " in RITs");
456               failover = true;
457               break;
458             }
459           }
460         }
461       }
462     }
463     if (!failover) {
464       // If we get here, we have a full cluster restart. It is a failover only
465       // if there are some WALs are not split yet. For meta WALs, they should have
466       // been split already, if any. We can walk through those queued dead servers,
467       // if they don't have any WALs, this restart should be considered as a clean one
468       Set<ServerName> queuedDeadServers = serverManager.getRequeuedDeadServers().keySet();
469       if (!queuedDeadServers.isEmpty()) {
470         Configuration conf = server.getConfiguration();
471         Path rootdir = FSUtils.getRootDir(conf);
472         FileSystem fs = rootdir.getFileSystem(conf);
473         for (ServerName serverName: queuedDeadServers) {
474           // In the case of a clean exit, the shutdown handler would have presplit any WALs and
475           // removed empty directories.
476           Path logDir = new Path(rootdir,
477               DefaultWALProvider.getWALDirectoryName(serverName.toString()));
478           Path splitDir = logDir.suffix(DefaultWALProvider.SPLITTING_EXT);
479           if (fs.exists(logDir) || fs.exists(splitDir)) {
480             LOG.debug("Found queued dead server " + serverName);
481             failover = true;
482             break;
483           }
484         }
485         if (!failover) {
486           // We figured that it's not a failover, so no need to
487           // work on these re-queued dead servers any more.
488           LOG.info("AM figured that it's not a failover and cleaned up "
489             + queuedDeadServers.size() + " queued dead servers");
490           serverManager.removeRequeuedDeadServers();
491         }
492       }
493     }
494 
495     Set<TableName> disabledOrDisablingOrEnabling = null;
496     Map<HRegionInfo, ServerName> allRegions = null;
497 
498     if (!failover) {
499       disabledOrDisablingOrEnabling = tableStateManager.getTablesInStates(
500         TableState.State.DISABLED, TableState.State.DISABLING,
501         TableState.State.ENABLING);
502 
503       // Clean re/start, mark all user regions closed before reassignment
504       allRegions = regionStates.closeAllUserRegions(
505         disabledOrDisablingOrEnabling);
506     }
507 
508     // Now region states are restored
509     regionStateStore.start();
510 
511     if (failover) {
512       if (deadServers != null && !deadServers.isEmpty()) {
513         for (ServerName serverName: deadServers) {
514           if (!serverManager.isServerDead(serverName)) {
515             serverManager.expireServer(serverName); // Let SSH do region re-assign
516           }
517         }
518       }
519       processRegionsInTransition(regionStates.getRegionsInTransition().values());
520     }
521 
522     // Now we can safely claim failover cleanup completed and enable
523     // ServerShutdownHandler for further processing. The nodes (below)
524     // in transition, if any, are for regions not related to those
525     // dead servers at all, and can be done in parallel to SSH.
526     failoverCleanupDone();
527     if (!failover) {
528       // Fresh cluster startup.
529       LOG.info("Clean cluster startup. Assigning user regions");
530       assignAllUserRegions(allRegions);
531     }
532     // unassign replicas of the split parents and the merged regions
533     // the daughter replicas are opened in assignAllUserRegions if it was
534     // not already opened.
535     for (HRegionInfo h : replicasToClose) {
536       unassign(h);
537     }
538     replicasToClose.clear();
539     return failover;
540   }
541 
542   /**
543    * When a region is closed, it should be removed from the regionsToReopen
544    * @param hri HRegionInfo of the region which was closed
545    */
546   public void removeClosedRegion(HRegionInfo hri) {
547     if (regionsToReopen.remove(hri.getEncodedName()) != null) {
548       LOG.debug("Removed region from reopening regions because it was closed");
549     }
550   }
551 
552   // TODO: processFavoredNodes might throw an exception, for e.g., if the
553   // meta could not be contacted/updated. We need to see how seriously to treat
554   // this problem as. Should we fail the current assignment. We should be able
555   // to recover from this problem eventually (if the meta couldn't be updated
556   // things should work normally and eventually get fixed up).
557   void processFavoredNodes(List<HRegionInfo> regions) throws IOException {
558     if (!shouldAssignRegionsWithFavoredNodes) return;
559     // The AM gets the favored nodes info for each region and updates the meta
560     // table with that info
561     Map<HRegionInfo, List<ServerName>> regionToFavoredNodes =
562         new HashMap<HRegionInfo, List<ServerName>>();
563     for (HRegionInfo region : regions) {
564       regionToFavoredNodes.put(region,
565           ((FavoredNodeLoadBalancer)this.balancer).getFavoredNodes(region));
566     }
567     FavoredNodeAssignmentHelper.updateMetaWithFavoredNodesInfo(regionToFavoredNodes,
568       this.server.getShortCircuitConnection());
569   }
570 
571   /**
572    * Marks the region as online.  Removes it from regions in transition and
573    * updates the in-memory assignment information.
574    * <p>
575    * Used when a region has been successfully opened on a region server.
576    * @param regionInfo
577    * @param sn
578    */
579   void regionOnline(HRegionInfo regionInfo, ServerName sn) {
580     regionOnline(regionInfo, sn, HConstants.NO_SEQNUM);
581   }
582 
583   void regionOnline(HRegionInfo regionInfo, ServerName sn, long openSeqNum) {
584     numRegionsOpened.incrementAndGet();
585     regionStates.regionOnline(regionInfo, sn, openSeqNum);
586 
587     // Remove plan if one.
588     clearRegionPlan(regionInfo);
589     balancer.regionOnline(regionInfo, sn);
590 
591     // Tell our listeners that a region was opened
592     sendRegionOpenedNotification(regionInfo, sn);
593   }
594 
595   /**
596    * Marks the region as offline.  Removes it from regions in transition and
597    * removes in-memory assignment information.
598    * <p>
599    * Used when a region has been closed and should remain closed.
600    * @param regionInfo
601    */
602   public void regionOffline(final HRegionInfo regionInfo) {
603     regionOffline(regionInfo, null);
604   }
605 
606   public void offlineDisabledRegion(HRegionInfo regionInfo) {
607     replicasToClose.remove(regionInfo);
608     regionOffline(regionInfo);
609   }
610 
611   // Assignment methods
612 
613   /**
614    * Assigns the specified region.
615    * <p>
616    * If a RegionPlan is available with a valid destination then it will be used
617    * to determine what server region is assigned to.  If no RegionPlan is
618    * available, region will be assigned to a random available server.
619    * <p>
620    * Updates the RegionState and sends the OPEN RPC.
621    * <p>
622    * This will only succeed if the region is in transition and in a CLOSED or
623    * OFFLINE state or not in transition, and of course, the
624    * chosen server is up and running (It may have just crashed!).
625    *
626    * @param region server to be assigned
627    */
628   public void assign(HRegionInfo region) {
629     assign(region, false);
630   }
631 
632   /**
633    * Use care with forceNewPlan. It could cause double assignment.
634    */
635   public void assign(HRegionInfo region, boolean forceNewPlan) {
636     if (isDisabledorDisablingRegionInRIT(region)) {
637       return;
638     }
639     String encodedName = region.getEncodedName();
640     Lock lock = locker.acquireLock(encodedName);
641     try {
642       RegionState state = forceRegionStateToOffline(region, forceNewPlan);
643       if (state != null) {
644         if (regionStates.wasRegionOnDeadServer(encodedName)) {
645           LOG.info("Skip assigning " + region.getRegionNameAsString()
646             + ", it's host " + regionStates.getLastRegionServerOfRegion(encodedName)
647             + " is dead but not processed yet");
648           return;
649         }
650         assign(state, forceNewPlan);
651       }
652     } finally {
653       lock.unlock();
654     }
655   }
656 
657   /**
658    * Bulk assign regions to <code>destination</code>.
659    * @param destination
660    * @param regions Regions to assign.
661    * @return true if successful
662    */
663   boolean assign(final ServerName destination, final List<HRegionInfo> regions)
664     throws InterruptedException {
665     long startTime = EnvironmentEdgeManager.currentTime();
666     try {
667       int regionCount = regions.size();
668       if (regionCount == 0) {
669         return true;
670       }
671       LOG.info("Assigning " + regionCount + " region(s) to " + destination.toString());
672       Set<String> encodedNames = new HashSet<String>(regionCount);
673       for (HRegionInfo region : regions) {
674         encodedNames.add(region.getEncodedName());
675       }
676 
677       List<HRegionInfo> failedToOpenRegions = new ArrayList<HRegionInfo>();
678       Map<String, Lock> locks = locker.acquireLocks(encodedNames);
679       try {
680         Map<String, RegionPlan> plans = new HashMap<String, RegionPlan>(regionCount);
681         List<RegionState> states = new ArrayList<RegionState>(regionCount);
682         for (HRegionInfo region : regions) {
683           String encodedName = region.getEncodedName();
684           if (!isDisabledorDisablingRegionInRIT(region)) {
685             RegionState state = forceRegionStateToOffline(region, false);
686             boolean onDeadServer = false;
687             if (state != null) {
688               if (regionStates.wasRegionOnDeadServer(encodedName)) {
689                 LOG.info("Skip assigning " + region.getRegionNameAsString()
690                   + ", it's host " + regionStates.getLastRegionServerOfRegion(encodedName)
691                   + " is dead but not processed yet");
692                 onDeadServer = true;
693               } else {
694                 RegionPlan plan = new RegionPlan(region, state.getServerName(), destination);
695                 plans.put(encodedName, plan);
696                 states.add(state);
697                 continue;
698               }
699             }
700             // Reassign if the region wasn't on a dead server
701             if (!onDeadServer) {
702               LOG.info("failed to force region state to offline, "
703                 + "will reassign later: " + region);
704               failedToOpenRegions.add(region); // assign individually later
705             }
706           }
707           // Release the lock, this region is excluded from bulk assign because
708           // we can't update its state, or set its znode to offline.
709           Lock lock = locks.remove(encodedName);
710           lock.unlock();
711         }
712 
713         if (server.isStopped()) {
714           return false;
715         }
716 
717         // Add region plans, so we can updateTimers when one region is opened so
718         // that unnecessary timeout on RIT is reduced.
719         this.addPlans(plans);
720 
721         List<Pair<HRegionInfo, List<ServerName>>> regionOpenInfos =
722           new ArrayList<Pair<HRegionInfo, List<ServerName>>>(states.size());
723         for (RegionState state: states) {
724           HRegionInfo region = state.getRegion();
725           regionStates.updateRegionState(
726             region, State.PENDING_OPEN, destination);
727           List<ServerName> favoredNodes = ServerName.EMPTY_SERVER_LIST;
728           if (this.shouldAssignRegionsWithFavoredNodes) {
729             favoredNodes = ((FavoredNodeLoadBalancer)this.balancer).getFavoredNodes(region);
730           }
731           regionOpenInfos.add(new Pair<HRegionInfo, List<ServerName>>(
732             region, favoredNodes));
733         }
734 
735         // Move on to open regions.
736         try {
737           // Send OPEN RPC. If it fails on a IOE or RemoteException,
738           // regions will be assigned individually.
739           Configuration conf = server.getConfiguration();
740           long maxWaitTime = System.currentTimeMillis() +
741             conf.getLong("hbase.regionserver.rpc.startup.waittime", 60000);
742           for (int i = 1; i <= maximumAttempts && !server.isStopped(); i++) {
743             try {
744               List<RegionOpeningState> regionOpeningStateList = serverManager
745                 .sendRegionOpen(destination, regionOpenInfos);
746               for (int k = 0, n = regionOpeningStateList.size(); k < n; k++) {
747                 RegionOpeningState openingState = regionOpeningStateList.get(k);
748                 if (openingState != RegionOpeningState.OPENED) {
749                   HRegionInfo region = regionOpenInfos.get(k).getFirst();
750                   LOG.info("Got opening state " + openingState
751                     + ", will reassign later: " + region);
752                   // Failed opening this region, reassign it later
753                   forceRegionStateToOffline(region, true);
754                   failedToOpenRegions.add(region);
755                 }
756               }
757               break;
758             } catch (IOException e) {
759               if (e instanceof RemoteException) {
760                 e = ((RemoteException)e).unwrapRemoteException();
761               }
762               if (e instanceof RegionServerStoppedException) {
763                 LOG.warn("The region server was shut down, ", e);
764                 // No need to retry, the region server is a goner.
765                 return false;
766               } else if (e instanceof ServerNotRunningYetException) {
767                 long now = System.currentTimeMillis();
768                 if (now < maxWaitTime) {
769                   if (LOG.isDebugEnabled()) {
770                     LOG.debug("Server is not yet up; waiting up to " +
771                       (maxWaitTime - now) + "ms", e);
772                   }
773                   Thread.sleep(100);
774                   i--; // reset the try count
775                   continue;
776                 }
777               } else if (e instanceof java.net.SocketTimeoutException
778                   && this.serverManager.isServerOnline(destination)) {
779                 // In case socket is timed out and the region server is still online,
780                 // the openRegion RPC could have been accepted by the server and
781                 // just the response didn't go through.  So we will retry to
782                 // open the region on the same server.
783                 if (LOG.isDebugEnabled()) {
784                   LOG.debug("Bulk assigner openRegion() to " + destination
785                     + " has timed out, but the regions might"
786                     + " already be opened on it.", e);
787                 }
788                 // wait and reset the re-try count, server might be just busy.
789                 Thread.sleep(100);
790                 i--;
791                 continue;
792               } else if (e instanceof FailedServerException && i < maximumAttempts) {
793                 // In case the server is in the failed server list, no point to
794                 // retry too soon. Retry after the failed_server_expiry time
795                 long sleepTime = 1 + conf.getInt(RpcClient.FAILED_SERVER_EXPIRY_KEY,
796                   RpcClient.FAILED_SERVER_EXPIRY_DEFAULT);
797                 if (LOG.isDebugEnabled()) {
798                   LOG.debug(destination + " is on failed server list; waiting "
799                     + sleepTime + "ms", e);
800                 }
801                 Thread.sleep(sleepTime);
802                 continue;
803               }
804               throw e;
805             }
806           }
807         } catch (IOException e) {
808           // Can be a socket timeout, EOF, NoRouteToHost, etc
809           LOG.info("Unable to communicate with " + destination
810             + " in order to assign regions, ", e);
811           for (RegionState state: states) {
812             HRegionInfo region = state.getRegion();
813             forceRegionStateToOffline(region, true);
814           }
815           return false;
816         }
817       } finally {
818         for (Lock lock : locks.values()) {
819           lock.unlock();
820         }
821       }
822 
823       if (!failedToOpenRegions.isEmpty()) {
824         for (HRegionInfo region : failedToOpenRegions) {
825           if (!regionStates.isRegionOnline(region)) {
826             invokeAssign(region);
827           }
828         }
829       }
830       LOG.debug("Bulk assigning done for " + destination);
831       return true;
832     } finally {
833       metricsAssignmentManager.updateBulkAssignTime(EnvironmentEdgeManager.currentTime() - startTime);
834     }
835   }
836 
837   /**
838    * Send CLOSE RPC if the server is online, otherwise, offline the region.
839    *
840    * The RPC will be sent only to the region sever found in the region state
841    * if it is passed in, otherwise, to the src server specified. If region
842    * state is not specified, we don't update region state at all, instead
843    * we just send the RPC call. This is useful for some cleanup without
844    * messing around the region states (see handleRegion, on region opened
845    * on an unexpected server scenario, for an example)
846    */
847   private void unassign(final HRegionInfo region,
848       final ServerName server, final ServerName dest) {
849     for (int i = 1; i <= this.maximumAttempts; i++) {
850       if (this.server.isStopped() || this.server.isAborted()) {
851         LOG.debug("Server stopped/aborted; skipping unassign of " + region);
852         return;
853       }
854       if (!serverManager.isServerOnline(server)) {
855         LOG.debug("Offline " + region.getRegionNameAsString()
856           + ", no need to unassign since it's on a dead server: " + server);
857         regionStates.updateRegionState(region, State.OFFLINE);
858         return;
859       }
860       try {
861         // Send CLOSE RPC
862         if (serverManager.sendRegionClose(server, region, dest)) {
863           LOG.debug("Sent CLOSE to " + server + " for region " +
864             region.getRegionNameAsString());
865           return;
866         }
867         // This never happens. Currently regionserver close always return true.
868         // Todo; this can now happen (0.96) if there is an exception in a coprocessor
869         LOG.warn("Server " + server + " region CLOSE RPC returned false for " +
870           region.getRegionNameAsString());
871       } catch (Throwable t) {
872         if (t instanceof RemoteException) {
873           t = ((RemoteException)t).unwrapRemoteException();
874         }
875         if (t instanceof NotServingRegionException
876             || t instanceof RegionServerStoppedException
877             || t instanceof ServerNotRunningYetException) {
878           LOG.debug("Offline " + region.getRegionNameAsString()
879             + ", it's not any more on " + server, t);
880           regionStates.updateRegionState(region, State.OFFLINE);
881           return;
882         } else if (t instanceof FailedServerException && i < maximumAttempts) {
883           // In case the server is in the failed server list, no point to
884           // retry too soon. Retry after the failed_server_expiry time
885           try {
886             Configuration conf = this.server.getConfiguration();
887             long sleepTime = 1 + conf.getInt(RpcClient.FAILED_SERVER_EXPIRY_KEY,
888               RpcClient.FAILED_SERVER_EXPIRY_DEFAULT);
889             if (LOG.isDebugEnabled()) {
890               LOG.debug(server + " is on failed server list; waiting "
891                 + sleepTime + "ms", t);
892             }
893             Thread.sleep(sleepTime);
894           } catch (InterruptedException ie) {
895             LOG.warn("Failed to unassign "
896               + region.getRegionNameAsString() + " since interrupted", ie);
897             regionStates.updateRegionState(region, State.FAILED_CLOSE);
898             Thread.currentThread().interrupt();
899             return;
900           }
901         }
902 
903         LOG.info("Server " + server + " returned " + t + " for "
904           + region.getRegionNameAsString() + ", try=" + i
905           + " of " + this.maximumAttempts, t);
906       }
907     }
908     // Run out of attempts
909     regionStates.updateRegionState(region, State.FAILED_CLOSE);
910   }
911 
912   /**
913    * Set region to OFFLINE unless it is opening and forceNewPlan is false.
914    */
915   private RegionState forceRegionStateToOffline(
916       final HRegionInfo region, final boolean forceNewPlan) {
917     RegionState state = regionStates.getRegionState(region);
918     if (state == null) {
919       LOG.warn("Assigning a region not in region states: " + region);
920       state = regionStates.createRegionState(region);
921     }
922 
923     if (forceNewPlan && LOG.isDebugEnabled()) {
924       LOG.debug("Force region state offline " + state);
925     }
926 
927     switch (state.getState()) {
928     case OPEN:
929     case OPENING:
930     case PENDING_OPEN:
931     case CLOSING:
932     case PENDING_CLOSE:
933       if (!forceNewPlan) {
934         LOG.debug("Skip assigning " +
935           region + ", it is already " + state);
936         return null;
937       }
938     case FAILED_CLOSE:
939     case FAILED_OPEN:
940       regionStates.updateRegionState(region, State.PENDING_CLOSE);
941       unassign(region, state.getServerName(), null);
942       state = regionStates.getRegionState(region);
943       if (!state.isOffline() && !state.isClosed()) {
944         // If the region isn't offline, we can't re-assign
945         // it now. It will be assigned automatically after
946         // the regionserver reports it's closed.
947         return null;
948       }
949     case OFFLINE:
950     case CLOSED:
951       break;
952     default:
953       LOG.error("Trying to assign region " + region
954         + ", which is " + state);
955       return null;
956     }
957     return state;
958   }
959 
960   /**
961    * Caller must hold lock on the passed <code>state</code> object.
962    * @param state
963    * @param forceNewPlan
964    */
965   private void assign(RegionState state, boolean forceNewPlan) {
966     long startTime = EnvironmentEdgeManager.currentTime();
967     try {
968       Configuration conf = server.getConfiguration();
969       RegionPlan plan = null;
970       long maxWaitTime = -1;
971       HRegionInfo region = state.getRegion();
972       Throwable previousException = null;
973       for (int i = 1; i <= maximumAttempts; i++) {
974         if (server.isStopped() || server.isAborted()) {
975           LOG.info("Skip assigning " + region.getRegionNameAsString()
976             + ", the server is stopped/aborted");
977           return;
978         }
979         if (plan == null) { // Get a server for the region at first
980           try {
981             plan = getRegionPlan(region, forceNewPlan);
982           } catch (HBaseIOException e) {
983             LOG.warn("Failed to get region plan", e);
984           }
985         }
986         if (plan == null) {
987           LOG.warn("Unable to determine a plan to assign " + region);
988           if (region.isMetaRegion()) {
989             try {
990               Thread.sleep(this.sleepTimeBeforeRetryingMetaAssignment);
991               if (i == maximumAttempts) i = 1;
992               continue;
993             } catch (InterruptedException e) {
994               LOG.error("Got exception while waiting for hbase:meta assignment");
995               Thread.currentThread().interrupt();
996             }
997           }
998           regionStates.updateRegionState(region, State.FAILED_OPEN);
999           return;
1000         }
1001         // In case of assignment from EnableTableHandler table state is ENABLING. Any how
1002         // EnableTableHandler will set ENABLED after assigning all the table regions. If we
1003         // try to set to ENABLED directly then client API may think table is enabled.
1004         // When we have a case such as all the regions are added directly into hbase:meta and we call
1005         // assignRegion then we need to make the table ENABLED. Hence in such case the table
1006         // will not be in ENABLING or ENABLED state.
1007         TableName tableName = region.getTable();
1008         if (!tableStateManager.isTableState(tableName,
1009           TableState.State.ENABLED, TableState.State.ENABLING)) {
1010           LOG.debug("Setting table " + tableName + " to ENABLED state.");
1011           setEnabledTable(tableName);
1012         }
1013         LOG.info("Assigning " + region.getRegionNameAsString() +
1014             " to " + plan.getDestination().toString());
1015         // Transition RegionState to PENDING_OPEN
1016        regionStates.updateRegionState(region,
1017           State.PENDING_OPEN, plan.getDestination());
1018 
1019         boolean needNewPlan = false;
1020         final String assignMsg = "Failed assignment of " + region.getRegionNameAsString() +
1021             " to " + plan.getDestination();
1022         try {
1023           List<ServerName> favoredNodes = ServerName.EMPTY_SERVER_LIST;
1024           if (this.shouldAssignRegionsWithFavoredNodes) {
1025             favoredNodes = ((FavoredNodeLoadBalancer)this.balancer).getFavoredNodes(region);
1026           }
1027           serverManager.sendRegionOpen(plan.getDestination(), region, favoredNodes);
1028           return; // we're done
1029         } catch (Throwable t) {
1030           if (t instanceof RemoteException) {
1031             t = ((RemoteException) t).unwrapRemoteException();
1032           }
1033           previousException = t;
1034 
1035           // Should we wait a little before retrying? If the server is starting it's yes.
1036           boolean hold = (t instanceof ServerNotRunningYetException);
1037 
1038           // In case socket is timed out and the region server is still online,
1039           // the openRegion RPC could have been accepted by the server and
1040           // just the response didn't go through.  So we will retry to
1041           // open the region on the same server.
1042           boolean retry = !hold && (t instanceof java.net.SocketTimeoutException
1043               && this.serverManager.isServerOnline(plan.getDestination()));
1044 
1045           if (hold) {
1046             LOG.warn(assignMsg + ", waiting a little before trying on the same region server " +
1047               "try=" + i + " of " + this.maximumAttempts, t);
1048 
1049             if (maxWaitTime < 0) {
1050               maxWaitTime = EnvironmentEdgeManager.currentTime()
1051                 + this.server.getConfiguration().getLong(
1052                   "hbase.regionserver.rpc.startup.waittime", 60000);
1053             }
1054             try {
1055               long now = EnvironmentEdgeManager.currentTime();
1056               if (now < maxWaitTime) {
1057                 if (LOG.isDebugEnabled()) {
1058                   LOG.debug("Server is not yet up; waiting up to "
1059                     + (maxWaitTime - now) + "ms", t);
1060                 }
1061                 Thread.sleep(100);
1062                 i--; // reset the try count
1063               } else {
1064                 LOG.debug("Server is not up for a while; try a new one", t);
1065                 needNewPlan = true;
1066               }
1067             } catch (InterruptedException ie) {
1068               LOG.warn("Failed to assign "
1069                   + region.getRegionNameAsString() + " since interrupted", ie);
1070               regionStates.updateRegionState(region, State.FAILED_OPEN);
1071               Thread.currentThread().interrupt();
1072               return;
1073             }
1074           } else if (retry) {
1075             i--; // we want to retry as many times as needed as long as the RS is not dead.
1076             if (LOG.isDebugEnabled()) {
1077               LOG.debug(assignMsg + ", trying to assign to the same region server due ", t);
1078             }
1079           } else {
1080             needNewPlan = true;
1081             LOG.warn(assignMsg + ", trying to assign elsewhere instead;" +
1082                 " try=" + i + " of " + this.maximumAttempts, t);
1083           }
1084         }
1085 
1086         if (i == this.maximumAttempts) {
1087           // Don't reset the region state or get a new plan any more.
1088           // This is the last try.
1089           continue;
1090         }
1091 
1092         // If region opened on destination of present plan, reassigning to new
1093         // RS may cause double assignments. In case of RegionAlreadyInTransitionException
1094         // reassigning to same RS.
1095         if (needNewPlan) {
1096           // Force a new plan and reassign. Will return null if no servers.
1097           // The new plan could be the same as the existing plan since we don't
1098           // exclude the server of the original plan, which should not be
1099           // excluded since it could be the only server up now.
1100           RegionPlan newPlan = null;
1101           try {
1102             newPlan = getRegionPlan(region, true);
1103           } catch (HBaseIOException e) {
1104             LOG.warn("Failed to get region plan", e);
1105           }
1106           if (newPlan == null) {
1107             regionStates.updateRegionState(region, State.FAILED_OPEN);
1108             LOG.warn("Unable to find a viable location to assign region " +
1109                 region.getRegionNameAsString());
1110             return;
1111           }
1112 
1113           if (plan != newPlan && !plan.getDestination().equals(newPlan.getDestination())) {
1114             // Clean out plan we failed execute and one that doesn't look like it'll
1115             // succeed anyways; we need a new plan!
1116             // Transition back to OFFLINE
1117             regionStates.updateRegionState(region, State.OFFLINE);
1118             plan = newPlan;
1119           } else if(plan.getDestination().equals(newPlan.getDestination()) &&
1120               previousException instanceof FailedServerException) {
1121             try {
1122               LOG.info("Trying to re-assign " + region.getRegionNameAsString() +
1123                 " to the same failed server.");
1124               Thread.sleep(1 + conf.getInt(RpcClient.FAILED_SERVER_EXPIRY_KEY,
1125                 RpcClient.FAILED_SERVER_EXPIRY_DEFAULT));
1126             } catch (InterruptedException ie) {
1127               LOG.warn("Failed to assign "
1128                   + region.getRegionNameAsString() + " since interrupted", ie);
1129               regionStates.updateRegionState(region, State.FAILED_OPEN);
1130               Thread.currentThread().interrupt();
1131               return;
1132             }
1133           }
1134         }
1135       }
1136       // Run out of attempts
1137       regionStates.updateRegionState(region, State.FAILED_OPEN);
1138     } finally {
1139       metricsAssignmentManager.updateAssignmentTime(EnvironmentEdgeManager.currentTime() - startTime);
1140     }
1141   }
1142 
1143   private boolean isDisabledorDisablingRegionInRIT(final HRegionInfo region) {
1144     if (this.tableStateManager.isTableState(region.getTable(),
1145             TableState.State.DISABLED,
1146             TableState.State.DISABLING) || replicasToClose.contains(region)) {
1147       LOG.info("Table " + region.getTable() + " is disabled or disabling;"
1148         + " skipping assign of " + region.getRegionNameAsString());
1149       offlineDisabledRegion(region);
1150       return true;
1151     }
1152     return false;
1153   }
1154 
1155   /**
1156    * @param region the region to assign
1157    * @param forceNewPlan If true, then if an existing plan exists, a new plan
1158    * will be generated.
1159    * @return Plan for passed <code>region</code> (If none currently, it creates one or
1160    * if no servers to assign, it returns null).
1161    */
1162   private RegionPlan getRegionPlan(final HRegionInfo region,
1163       final boolean forceNewPlan) throws HBaseIOException {
1164     // Pickup existing plan or make a new one
1165     final String encodedName = region.getEncodedName();
1166     final List<ServerName> destServers =
1167       serverManager.createDestinationServersList();
1168 
1169     if (destServers.isEmpty()){
1170       LOG.warn("Can't move " + encodedName +
1171         ", there is no destination server available.");
1172       return null;
1173     }
1174 
1175     RegionPlan randomPlan = null;
1176     boolean newPlan = false;
1177     RegionPlan existingPlan;
1178 
1179     synchronized (this.regionPlans) {
1180       existingPlan = this.regionPlans.get(encodedName);
1181 
1182       if (existingPlan != null && existingPlan.getDestination() != null) {
1183         LOG.debug("Found an existing plan for " + region.getRegionNameAsString()
1184           + " destination server is " + existingPlan.getDestination() +
1185             " accepted as a dest server = " + destServers.contains(existingPlan.getDestination()));
1186       }
1187 
1188       if (forceNewPlan
1189           || existingPlan == null
1190           || existingPlan.getDestination() == null
1191           || !destServers.contains(existingPlan.getDestination())) {
1192         newPlan = true;
1193         randomPlan = new RegionPlan(region, null,
1194             balancer.randomAssignment(region, destServers));
1195         if (!region.isMetaTable() && shouldAssignRegionsWithFavoredNodes) {
1196           List<HRegionInfo> regions = new ArrayList<HRegionInfo>(1);
1197           regions.add(region);
1198           try {
1199             processFavoredNodes(regions);
1200           } catch (IOException ie) {
1201             LOG.warn("Ignoring exception in processFavoredNodes " + ie);
1202           }
1203         }
1204         this.regionPlans.put(encodedName, randomPlan);
1205       }
1206     }
1207 
1208     if (newPlan) {
1209       if (randomPlan.getDestination() == null) {
1210         LOG.warn("Can't find a destination for " + encodedName);
1211         return null;
1212       }
1213       if (LOG.isDebugEnabled()) {
1214         LOG.debug("No previous transition plan found (or ignoring " +
1215           "an existing plan) for " + region.getRegionNameAsString() +
1216           "; generated random plan=" + randomPlan + "; " + destServers.size() +
1217           " (online=" + serverManager.getOnlineServers().size() +
1218           ") available servers, forceNewPlan=" + forceNewPlan);
1219       }
1220       return randomPlan;
1221     }
1222     if (LOG.isDebugEnabled()) {
1223       LOG.debug("Using pre-existing plan for " +
1224         region.getRegionNameAsString() + "; plan=" + existingPlan);
1225     }
1226     return existingPlan;
1227   }
1228 
1229   /**
1230    * Unassigns the specified region.
1231    * <p>
1232    * Updates the RegionState and sends the CLOSE RPC unless region is being
1233    * split by regionserver; then the unassign fails (silently) because we
1234    * presume the region being unassigned no longer exists (its been split out
1235    * of existence). TODO: What to do if split fails and is rolled back and
1236    * parent is revivified?
1237    * <p>
1238    * If a RegionPlan is already set, it will remain.
1239    *
1240    * @param region server to be unassigned
1241    */
1242   public void unassign(HRegionInfo region) {
1243     unassign(region, null);
1244   }
1245 
1246 
1247   /**
1248    * Unassigns the specified region.
1249    * <p>
1250    * Updates the RegionState and sends the CLOSE RPC unless region is being
1251    * split by regionserver; then the unassign fails (silently) because we
1252    * presume the region being unassigned no longer exists (its been split out
1253    * of existence). TODO: What to do if split fails and is rolled back and
1254    * parent is revivified?
1255    * <p>
1256    * If a RegionPlan is already set, it will remain.
1257    *
1258    * @param region server to be unassigned
1259    * @param dest the destination server of the region
1260    */
1261   public void unassign(HRegionInfo region, ServerName dest) {
1262     // TODO: Method needs refactoring.  Ugly buried returns throughout.  Beware!
1263     LOG.debug("Starting unassign of " + region.getRegionNameAsString()
1264       + " (offlining), current state: " + regionStates.getRegionState(region));
1265 
1266     String encodedName = region.getEncodedName();
1267     // Grab the state of this region and synchronize on it
1268     // We need a lock here as we're going to do a put later and we don't want multiple states
1269     //  creation
1270     ReentrantLock lock = locker.acquireLock(encodedName);
1271     RegionState state = regionStates.getRegionTransitionState(encodedName);
1272     try {
1273       if (state == null || state.isFailedClose()) {
1274         if (state == null) {
1275           // Region is not in transition.
1276           // We can unassign it only if it's not SPLIT/MERGED.
1277           state = regionStates.getRegionState(encodedName);
1278           if (state != null && state.isUnassignable()) {
1279             LOG.info("Attempting to unassign " + state + ", ignored");
1280             // Offline region will be reassigned below
1281             return;
1282           }
1283           if (state == null || state.getServerName() == null) {
1284             // We don't know where the region is, offline it.
1285             // No need to send CLOSE RPC
1286             LOG.warn("Attempting to unassign a region not in RegionStates"
1287               + region.getRegionNameAsString() + ", offlined");
1288             regionOffline(region);
1289             return;
1290           }
1291         }
1292         state = regionStates.updateRegionState(
1293           region, State.PENDING_CLOSE);
1294       } else if (state.isFailedOpen()) {
1295         // The region is not open yet
1296         regionOffline(region);
1297         return;
1298       } else {
1299         LOG.debug("Attempting to unassign " +
1300           region.getRegionNameAsString() + " but it is " +
1301           "already in transition (" + state.getState());
1302         return;
1303       }
1304 
1305       unassign(region, state.getServerName(), dest);
1306     } finally {
1307       lock.unlock();
1308 
1309       // Region is expected to be reassigned afterwards
1310       if (!replicasToClose.contains(region)
1311           && regionStates.isRegionInState(region, State.OFFLINE)) {
1312         assign(region);
1313       }
1314     }
1315   }
1316 
1317   /**
1318    * Used by unit tests. Return the number of regions opened so far in the life
1319    * of the master. Increases by one every time the master opens a region
1320    * @return the counter value of the number of regions opened so far
1321    */
1322   public int getNumRegionsOpened() {
1323     return numRegionsOpened.get();
1324   }
1325 
1326   /**
1327    * Waits until the specified region has completed assignment.
1328    * <p>
1329    * If the region is already assigned, returns immediately.  Otherwise, method
1330    * blocks until the region is assigned.
1331    * @param regionInfo region to wait on assignment for
1332    * @throws InterruptedException
1333    */
1334   public boolean waitForAssignment(HRegionInfo regionInfo)
1335       throws InterruptedException {
1336     while (!regionStates.isRegionOnline(regionInfo)) {
1337       if (regionStates.isRegionInState(regionInfo, State.FAILED_OPEN)
1338           || this.server.isStopped()) {
1339         return false;
1340       }
1341 
1342       // We should receive a notification, but it's
1343       //  better to have a timeout to recheck the condition here:
1344       //  it lowers the impact of a race condition if any
1345       regionStates.waitForUpdate(100);
1346     }
1347     return true;
1348   }
1349 
1350   /**
1351    * Assigns the hbase:meta region.
1352    * <p>
1353    * Assumes that hbase:meta is currently closed and is not being actively served by
1354    * any RegionServer.
1355    */
1356   public void assignMeta() throws KeeperException {
1357     regionStates.updateRegionState(HRegionInfo.FIRST_META_REGIONINFO, State.OFFLINE);
1358     assign(HRegionInfo.FIRST_META_REGIONINFO);
1359   }
1360 
1361   /**
1362    * Assigns specified regions retaining assignments, if any.
1363    * <p>
1364    * This is a synchronous call and will return once every region has been
1365    * assigned.  If anything fails, an exception is thrown
1366    * @throws InterruptedException
1367    * @throws IOException
1368    */
1369   public void assign(Map<HRegionInfo, ServerName> regions)
1370         throws IOException, InterruptedException {
1371     if (regions == null || regions.isEmpty()) {
1372       return;
1373     }
1374     List<ServerName> servers = serverManager.createDestinationServersList();
1375     if (servers == null || servers.isEmpty()) {
1376       throw new IOException("Found no destination server to assign region(s)");
1377     }
1378 
1379     // Reuse existing assignment info
1380     Map<ServerName, List<HRegionInfo>> bulkPlan =
1381       balancer.retainAssignment(regions, servers);
1382     if (bulkPlan == null) {
1383       throw new IOException("Unable to determine a plan to assign region(s)");
1384     }
1385 
1386     assign(regions.size(), servers.size(),
1387       "retainAssignment=true", bulkPlan);
1388   }
1389 
1390   /**
1391    * Assigns specified regions round robin, if any.
1392    * <p>
1393    * This is a synchronous call and will return once every region has been
1394    * assigned.  If anything fails, an exception is thrown
1395    * @throws InterruptedException
1396    * @throws IOException
1397    */
1398   public void assign(List<HRegionInfo> regions)
1399         throws IOException, InterruptedException {
1400     if (regions == null || regions.isEmpty()) {
1401       return;
1402     }
1403 
1404     List<ServerName> servers = serverManager.createDestinationServersList();
1405     if (servers == null || servers.isEmpty()) {
1406       throw new IOException("Found no destination server to assign region(s)");
1407     }
1408 
1409     // Generate a round-robin bulk assignment plan
1410     Map<ServerName, List<HRegionInfo>> bulkPlan
1411       = balancer.roundRobinAssignment(regions, servers);
1412     if (bulkPlan == null) {
1413       throw new IOException("Unable to determine a plan to assign region(s)");
1414     }
1415 
1416     processFavoredNodes(regions);
1417     assign(regions.size(), servers.size(),
1418       "round-robin=true", bulkPlan);
1419   }
1420 
1421   private void assign(int regions, int totalServers,
1422       String message, Map<ServerName, List<HRegionInfo>> bulkPlan)
1423           throws InterruptedException, IOException {
1424 
1425     int servers = bulkPlan.size();
1426     if (servers == 1 || (regions < bulkAssignThresholdRegions
1427         && servers < bulkAssignThresholdServers)) {
1428 
1429       // Not use bulk assignment.  This could be more efficient in small
1430       // cluster, especially mini cluster for testing, so that tests won't time out
1431       if (LOG.isTraceEnabled()) {
1432         LOG.trace("Not using bulk assignment since we are assigning only " + regions +
1433           " region(s) to " + servers + " server(s)");
1434       }
1435       for (Map.Entry<ServerName, List<HRegionInfo>> plan: bulkPlan.entrySet()) {
1436         if (!assign(plan.getKey(), plan.getValue()) && !server.isStopped()) {
1437           for (HRegionInfo region: plan.getValue()) {
1438             if (!regionStates.isRegionOnline(region)) {
1439               invokeAssign(region);
1440             }
1441           }
1442         }
1443       }
1444     } else {
1445       LOG.info("Bulk assigning " + regions + " region(s) across "
1446         + totalServers + " server(s), " + message);
1447 
1448       // Use fixed count thread pool assigning.
1449       BulkAssigner ba = new GeneralBulkAssigner(
1450         this.server, bulkPlan, this, bulkAssignWaitTillAllAssigned);
1451       ba.bulkAssign();
1452       LOG.info("Bulk assigning done");
1453     }
1454   }
1455 
1456   /**
1457    * Assigns all user regions, if any exist.  Used during cluster startup.
1458    * <p>
1459    * This is a synchronous call and will return once every region has been
1460    * assigned.  If anything fails, an exception is thrown and the cluster
1461    * should be shutdown.
1462    * @throws InterruptedException
1463    * @throws IOException
1464    */
1465   private void assignAllUserRegions(Map<HRegionInfo, ServerName> allRegions)
1466       throws IOException, InterruptedException {
1467     if (allRegions == null || allRegions.isEmpty()) return;
1468 
1469     // Determine what type of assignment to do on startup
1470     boolean retainAssignment = server.getConfiguration().
1471       getBoolean("hbase.master.startup.retainassign", true);
1472 
1473     Set<HRegionInfo> regionsFromMetaScan = allRegions.keySet();
1474     if (retainAssignment) {
1475       assign(allRegions);
1476     } else {
1477       List<HRegionInfo> regions = new ArrayList<HRegionInfo>(regionsFromMetaScan);
1478       assign(regions);
1479     }
1480 
1481     for (HRegionInfo hri : regionsFromMetaScan) {
1482       TableName tableName = hri.getTable();
1483       if (!tableStateManager.isTableState(tableName,
1484               TableState.State.ENABLED)) {
1485         setEnabledTable(tableName);
1486       }
1487     }
1488     // assign all the replicas that were not recorded in the meta
1489     assign(replicaRegionsNotRecordedInMeta(regionsFromMetaScan, (MasterServices)server));
1490   }
1491 
1492   /**
1493    * Get a list of replica regions that are:
1494    * not recorded in meta yet. We might not have recorded the locations
1495    * for the replicas since the replicas may not have been online yet, master restarted
1496    * in the middle of assigning, ZK erased, etc.
1497    * @param regionsRecordedInMeta the list of regions we know are recorded in meta
1498    * either as a default, or, as the location of a replica
1499    * @param master
1500    * @return list of replica regions
1501    * @throws IOException
1502    */
1503   public static List<HRegionInfo> replicaRegionsNotRecordedInMeta(
1504       Set<HRegionInfo> regionsRecordedInMeta, MasterServices master)throws IOException {
1505     List<HRegionInfo> regionsNotRecordedInMeta = new ArrayList<HRegionInfo>();
1506     for (HRegionInfo hri : regionsRecordedInMeta) {
1507       TableName table = hri.getTable();
1508       HTableDescriptor htd = master.getTableDescriptors().get(table);
1509       // look at the HTD for the replica count. That's the source of truth
1510       int desiredRegionReplication = htd.getRegionReplication();
1511       for (int i = 0; i < desiredRegionReplication; i++) {
1512         HRegionInfo replica = RegionReplicaUtil.getRegionInfoForReplica(hri, i);
1513         if (regionsRecordedInMeta.contains(replica)) continue;
1514         regionsNotRecordedInMeta.add(replica);
1515       }
1516     }
1517     return regionsNotRecordedInMeta;
1518   }
1519 
1520   /**
1521    * Rebuild the list of user regions and assignment information.
1522    * <p>
1523    * Returns a set of servers that are not found to be online that hosted
1524    * some regions.
1525    * @return set of servers not online that hosted some regions per meta
1526    * @throws IOException
1527    */
1528   Set<ServerName> rebuildUserRegions() throws
1529           IOException, KeeperException {
1530     Set<TableName> disabledOrEnablingTables = tableStateManager.getTablesInStates(
1531             TableState.State.DISABLED, TableState.State.ENABLING);
1532 
1533     Set<TableName> disabledOrDisablingOrEnabling = tableStateManager.getTablesInStates(
1534             TableState.State.DISABLED,
1535             TableState.State.DISABLING,
1536             TableState.State.ENABLING);
1537 
1538     // Region assignment from META
1539     List<Result> results = MetaTableAccessor.fullScanOfMeta(server.getShortCircuitConnection());
1540     // Get any new but slow to checkin region server that joined the cluster
1541     Set<ServerName> onlineServers = serverManager.getOnlineServers().keySet();
1542     // Set of offline servers to be returned
1543     Set<ServerName> offlineServers = new HashSet<ServerName>();
1544     // Iterate regions in META
1545     for (Result result : results) {
1546       if (result == null && LOG.isDebugEnabled()){
1547         LOG.debug("null result from meta - ignoring but this is strange.");
1548         continue;
1549       }
1550       // keep a track of replicas to close. These were the replicas of the originally
1551       // unmerged regions. The master might have closed them before but it mightn't
1552       // maybe because it crashed.
1553       PairOfSameType<HRegionInfo> p = MetaTableAccessor.getMergeRegions(result);
1554       if (p.getFirst() != null && p.getSecond() != null) {
1555         int numReplicas = ((MasterServices)server).getTableDescriptors().get(p.getFirst().
1556             getTable()).getRegionReplication();
1557         for (HRegionInfo merge : p) {
1558           for (int i = 1; i < numReplicas; i++) {
1559             replicasToClose.add(RegionReplicaUtil.getRegionInfoForReplica(merge, i));
1560           }
1561         }
1562       }
1563       RegionLocations rl =  MetaTableAccessor.getRegionLocations(result);
1564       if (rl == null) continue;
1565       HRegionLocation[] locations = rl.getRegionLocations();
1566       if (locations == null) continue;
1567       for (HRegionLocation hrl : locations) {
1568         HRegionInfo regionInfo = hrl.getRegionInfo();
1569         if (regionInfo == null) continue;
1570         int replicaId = regionInfo.getReplicaId();
1571         State state = RegionStateStore.getRegionState(result, replicaId);
1572         // keep a track of replicas to close. These were the replicas of the split parents
1573         // from the previous life of the master. The master should have closed them before
1574         // but it couldn't maybe because it crashed
1575         if (replicaId == 0 && state.equals(State.SPLIT)) {
1576           for (HRegionLocation h : locations) {
1577             replicasToClose.add(h.getRegionInfo());
1578           }
1579         }
1580         ServerName lastHost = hrl.getServerName();
1581         ServerName regionLocation = RegionStateStore.getRegionServer(result, replicaId);
1582         regionStates.createRegionState(regionInfo, state, regionLocation, lastHost);
1583         if (!regionStates.isRegionInState(regionInfo, State.OPEN)) {
1584           // Region is not open (either offline or in transition), skip
1585           continue;
1586         }
1587         TableName tableName = regionInfo.getTable();
1588         if (!onlineServers.contains(regionLocation)) {
1589           // Region is located on a server that isn't online
1590           offlineServers.add(regionLocation);
1591         } else if (!disabledOrEnablingTables.contains(tableName)) {
1592           // Region is being served and on an active server
1593           // add only if region not in disabled or enabling table
1594           regionStates.regionOnline(regionInfo, regionLocation);
1595           balancer.regionOnline(regionInfo, regionLocation);
1596         }
1597         // need to enable the table if not disabled or disabling or enabling
1598         // this will be used in rolling restarts
1599         if (!disabledOrDisablingOrEnabling.contains(tableName)
1600           && !getTableStateManager().isTableState(tableName,
1601                 TableState.State.ENABLED)) {
1602           setEnabledTable(tableName);
1603         }
1604       }
1605     }
1606     return offlineServers;
1607   }
1608 
1609   /**
1610    * Recover the tables that were not fully moved to DISABLED state. These
1611    * tables are in DISABLING state when the master restarted/switched.
1612    *
1613    * @throws KeeperException
1614    * @throws TableNotFoundException
1615    * @throws IOException
1616    */
1617   private void recoverTableInDisablingState()
1618           throws KeeperException, IOException {
1619     Set<TableName> disablingTables =
1620             tableStateManager.getTablesInStates(TableState.State.DISABLING);
1621     if (disablingTables.size() != 0) {
1622       for (TableName tableName : disablingTables) {
1623         // Recover by calling DisableTableHandler
1624         LOG.info("The table " + tableName
1625             + " is in DISABLING state.  Hence recovering by moving the table"
1626             + " to DISABLED state.");
1627         new DisableTableHandler(this.server, tableName,
1628             this, tableLockManager, true).prepare().process();
1629       }
1630     }
1631   }
1632 
1633   /**
1634    * Recover the tables that are not fully moved to ENABLED state. These tables
1635    * are in ENABLING state when the master restarted/switched
1636    *
1637    * @throws KeeperException
1638    * @throws org.apache.hadoop.hbase.TableNotFoundException
1639    * @throws IOException
1640    */
1641   private void recoverTableInEnablingState()
1642           throws KeeperException, IOException {
1643     Set<TableName> enablingTables = tableStateManager.
1644             getTablesInStates(TableState.State.ENABLING);
1645     if (enablingTables.size() != 0) {
1646       for (TableName tableName : enablingTables) {
1647         // Recover by calling EnableTableHandler
1648         LOG.info("The table " + tableName
1649             + " is in ENABLING state.  Hence recovering by moving the table"
1650             + " to ENABLED state.");
1651         // enableTable in sync way during master startup,
1652         // no need to invoke coprocessor
1653         EnableTableHandler eth = new EnableTableHandler(this.server, tableName,
1654           this, tableLockManager, true);
1655         try {
1656           eth.prepare();
1657         } catch (TableNotFoundException e) {
1658           LOG.warn("Table " + tableName + " not found in hbase:meta to recover.");
1659           continue;
1660         }
1661         eth.process();
1662       }
1663     }
1664   }
1665 
1666   /**
1667    * Processes list of regions in transition at startup
1668    */
1669   void processRegionsInTransition(Collection<RegionState> regionStates) {
1670     // We need to send RPC call again for PENDING_OPEN/PENDING_CLOSE regions
1671     // in case the RPC call is not sent out yet before the master was shut down
1672     // since we update the state before we send the RPC call. We can't update
1673     // the state after the RPC call. Otherwise, we don't know what's happened
1674     // to the region if the master dies right after the RPC call is out.
1675     for (RegionState regionState: regionStates) {
1676       if (!serverManager.isServerOnline(regionState.getServerName())) {
1677         continue; // SSH will handle it
1678       }
1679       RegionState.State state = regionState.getState();
1680       LOG.info("Processing " + regionState);
1681       switch (state) {
1682       case CLOSED:
1683         invokeAssign(regionState.getRegion());
1684         break;
1685       case PENDING_OPEN:
1686         retrySendRegionOpen(regionState);
1687         break;
1688       case PENDING_CLOSE:
1689         retrySendRegionClose(regionState);
1690         break;
1691       default:
1692         // No process for other states
1693       }
1694     }
1695   }
1696 
1697   /**
1698    * At master failover, for pending_open region, make sure
1699    * sendRegionOpen RPC call is sent to the target regionserver
1700    */
1701   private void retrySendRegionOpen(final RegionState regionState) {
1702     this.executorService.submit(
1703       new EventHandler(server, EventType.M_MASTER_RECOVERY) {
1704         @Override
1705         public void process() throws IOException {
1706           HRegionInfo hri = regionState.getRegion();
1707           ServerName serverName = regionState.getServerName();
1708           ReentrantLock lock = locker.acquireLock(hri.getEncodedName());
1709           try {
1710             for (int i = 1; i <= maximumAttempts; i++) {
1711               if (!serverManager.isServerOnline(serverName)
1712                   || server.isStopped() || server.isAborted()) {
1713                 return; // No need any more
1714               }
1715               try {
1716                 if (!regionState.equals(regionStates.getRegionState(hri))) {
1717                   return; // Region is not in the expected state any more
1718                 }
1719                 List<ServerName> favoredNodes = ServerName.EMPTY_SERVER_LIST;
1720                 if (shouldAssignRegionsWithFavoredNodes) {
1721                   favoredNodes = ((FavoredNodeLoadBalancer)balancer).getFavoredNodes(hri);
1722                 }
1723                 serverManager.sendRegionOpen(serverName, hri, favoredNodes);
1724                 return; // we're done
1725               } catch (Throwable t) {
1726                 if (t instanceof RemoteException) {
1727                   t = ((RemoteException) t).unwrapRemoteException();
1728                 }
1729                 if (t instanceof FailedServerException && i < maximumAttempts) {
1730                   // In case the server is in the failed server list, no point to
1731                   // retry too soon. Retry after the failed_server_expiry time
1732                   try {
1733                     Configuration conf = this.server.getConfiguration();
1734                     long sleepTime = 1 + conf.getInt(RpcClient.FAILED_SERVER_EXPIRY_KEY,
1735                       RpcClient.FAILED_SERVER_EXPIRY_DEFAULT);
1736                     if (LOG.isDebugEnabled()) {
1737                       LOG.debug(serverName + " is on failed server list; waiting "
1738                         + sleepTime + "ms", t);
1739                     }
1740                     Thread.sleep(sleepTime);
1741                     continue;
1742                   } catch (InterruptedException ie) {
1743                     LOG.warn("Failed to assign "
1744                       + hri.getRegionNameAsString() + " since interrupted", ie);
1745                     regionStates.updateRegionState(hri, State.FAILED_OPEN);
1746                     Thread.currentThread().interrupt();
1747                     return;
1748                   }
1749                 }
1750                 if (serverManager.isServerOnline(serverName)
1751                     && t instanceof java.net.SocketTimeoutException) {
1752                   i--; // reset the try count
1753                 } else {
1754                   LOG.info("Got exception in retrying sendRegionOpen for "
1755                     + regionState + "; try=" + i + " of " + maximumAttempts, t);
1756                 }
1757                 Threads.sleep(100);
1758               }
1759             }
1760             // Run out of attempts
1761             regionStates.updateRegionState(hri, State.FAILED_OPEN);
1762           } finally {
1763             lock.unlock();
1764           }
1765         }
1766       });
1767   }
1768 
1769   /**
1770    * At master failover, for pending_close region, make sure
1771    * sendRegionClose RPC call is sent to the target regionserver
1772    */
1773   private void retrySendRegionClose(final RegionState regionState) {
1774     this.executorService.submit(
1775       new EventHandler(server, EventType.M_MASTER_RECOVERY) {
1776         @Override
1777         public void process() throws IOException {
1778           HRegionInfo hri = regionState.getRegion();
1779           ServerName serverName = regionState.getServerName();
1780           ReentrantLock lock = locker.acquireLock(hri.getEncodedName());
1781           try {
1782             for (int i = 1; i <= maximumAttempts; i++) {
1783               if (!serverManager.isServerOnline(serverName)
1784                   || server.isStopped() || server.isAborted()) {
1785                 return; // No need any more
1786               }
1787               try {
1788                 if (!regionState.equals(regionStates.getRegionState(hri))) {
1789                   return; // Region is not in the expected state any more
1790                 }
1791                 serverManager.sendRegionClose(serverName, hri, null);
1792                 return; // Done.
1793               } catch (Throwable t) {
1794                 if (t instanceof RemoteException) {
1795                   t = ((RemoteException) t).unwrapRemoteException();
1796                 }
1797                 if (t instanceof FailedServerException && i < maximumAttempts) {
1798                   // In case the server is in the failed server list, no point to
1799                   // retry too soon. Retry after the failed_server_expiry time
1800                   try {
1801                     Configuration conf = this.server.getConfiguration();
1802                     long sleepTime = 1 + conf.getInt(RpcClient.FAILED_SERVER_EXPIRY_KEY,
1803                       RpcClient.FAILED_SERVER_EXPIRY_DEFAULT);
1804                     if (LOG.isDebugEnabled()) {
1805                       LOG.debug(serverName + " is on failed server list; waiting "
1806                         + sleepTime + "ms", t);
1807                     }
1808                     Thread.sleep(sleepTime);
1809                     continue;
1810                   } catch (InterruptedException ie) {
1811                     LOG.warn("Failed to unassign "
1812                       + hri.getRegionNameAsString() + " since interrupted", ie);
1813                     regionStates.updateRegionState(hri, RegionState.State.FAILED_CLOSE);
1814                     Thread.currentThread().interrupt();
1815                     return;
1816                   }
1817                 }
1818                 if (serverManager.isServerOnline(serverName)
1819                     && t instanceof java.net.SocketTimeoutException) {
1820                   i--; // reset the try count
1821                 } else {
1822                   LOG.info("Got exception in retrying sendRegionClose for "
1823                     + regionState + "; try=" + i + " of " + maximumAttempts, t);
1824                 }
1825                 Threads.sleep(100);
1826               }
1827             }
1828             // Run out of attempts
1829             regionStates.updateRegionState(hri, State.FAILED_CLOSE);
1830           } finally {
1831             lock.unlock();
1832           }
1833         }
1834       });
1835   }
1836 
1837   /**
1838    * Set Regions in transitions metrics.
1839    * This takes an iterator on the RegionInTransition map (CLSM), and is not synchronized.
1840    * This iterator is not fail fast, which may lead to stale read; but that's better than
1841    * creating a copy of the map for metrics computation, as this method will be invoked
1842    * on a frequent interval.
1843    */
1844   public void updateRegionsInTransitionMetrics() {
1845     long currentTime = System.currentTimeMillis();
1846     int totalRITs = 0;
1847     int totalRITsOverThreshold = 0;
1848     long oldestRITTime = 0;
1849     int ritThreshold = this.server.getConfiguration().
1850       getInt(HConstants.METRICS_RIT_STUCK_WARNING_THRESHOLD, 60000);
1851     for (RegionState state: regionStates.getRegionsInTransition().values()) {
1852       totalRITs++;
1853       long ritTime = currentTime - state.getStamp();
1854       if (ritTime > ritThreshold) { // more than the threshold
1855         totalRITsOverThreshold++;
1856       }
1857       if (oldestRITTime < ritTime) {
1858         oldestRITTime = ritTime;
1859       }
1860     }
1861     if (this.metricsAssignmentManager != null) {
1862       this.metricsAssignmentManager.updateRITOldestAge(oldestRITTime);
1863       this.metricsAssignmentManager.updateRITCount(totalRITs);
1864       this.metricsAssignmentManager.updateRITCountOverThreshold(totalRITsOverThreshold);
1865     }
1866   }
1867 
1868   /**
1869    * @param region Region whose plan we are to clear.
1870    */
1871   private void clearRegionPlan(final HRegionInfo region) {
1872     synchronized (this.regionPlans) {
1873       this.regionPlans.remove(region.getEncodedName());
1874     }
1875   }
1876 
1877   /**
1878    * Wait on region to clear regions-in-transition.
1879    * @param hri Region to wait on.
1880    * @throws IOException
1881    */
1882   public void waitOnRegionToClearRegionsInTransition(final HRegionInfo hri)
1883       throws IOException, InterruptedException {
1884     waitOnRegionToClearRegionsInTransition(hri, -1L);
1885   }
1886 
1887   /**
1888    * Wait on region to clear regions-in-transition or time out
1889    * @param hri
1890    * @param timeOut Milliseconds to wait for current region to be out of transition state.
1891    * @return True when a region clears regions-in-transition before timeout otherwise false
1892    * @throws InterruptedException
1893    */
1894   public boolean waitOnRegionToClearRegionsInTransition(final HRegionInfo hri, long timeOut)
1895       throws InterruptedException {
1896     if (!regionStates.isRegionInTransition(hri)) return true;
1897     long end = (timeOut <= 0) ? Long.MAX_VALUE : EnvironmentEdgeManager.currentTime()
1898         + timeOut;
1899     // There is already a timeout monitor on regions in transition so I
1900     // should not have to have one here too?
1901     LOG.info("Waiting for " + hri.getEncodedName() +
1902         " to leave regions-in-transition, timeOut=" + timeOut + " ms.");
1903     while (!this.server.isStopped() && regionStates.isRegionInTransition(hri)) {
1904       regionStates.waitForUpdate(100);
1905       if (EnvironmentEdgeManager.currentTime() > end) {
1906         LOG.info("Timed out on waiting for " + hri.getEncodedName() + " to be assigned.");
1907         return false;
1908       }
1909     }
1910     if (this.server.isStopped()) {
1911       LOG.info("Giving up wait on regions in transition because stoppable.isStopped is set");
1912       return false;
1913     }
1914     return true;
1915   }
1916 
1917   void invokeAssign(HRegionInfo regionInfo) {
1918     threadPoolExecutorService.submit(new AssignCallable(this, regionInfo));
1919   }
1920 
1921   void invokeUnAssign(HRegionInfo regionInfo) {
1922     threadPoolExecutorService.submit(new UnAssignCallable(this, regionInfo));
1923   }
1924 
1925   public boolean isCarryingMeta(ServerName serverName) {
1926     return isCarryingRegion(serverName, HRegionInfo.FIRST_META_REGIONINFO);
1927   }
1928 
1929   /**
1930    * Check if the shutdown server carries the specific region.
1931    * @return whether the serverName currently hosts the region
1932    */
1933   private boolean isCarryingRegion(ServerName serverName, HRegionInfo hri) {
1934     RegionState regionState = regionStates.getRegionTransitionState(hri);
1935     ServerName transitionAddr = regionState != null? regionState.getServerName(): null;
1936     if (transitionAddr != null) {
1937       boolean matchTransitionAddr = transitionAddr.equals(serverName);
1938       LOG.debug("Checking region=" + hri.getRegionNameAsString()
1939         + ", transitioning on server=" + matchTransitionAddr
1940         + " server being checked: " + serverName
1941         + ", matches=" + matchTransitionAddr);
1942       return matchTransitionAddr;
1943     }
1944 
1945     ServerName assignedAddr = regionStates.getRegionServerOfRegion(hri);
1946     boolean matchAssignedAddr = serverName.equals(assignedAddr);
1947     LOG.debug("based on AM, current region=" + hri.getRegionNameAsString()
1948       + " is on server=" + assignedAddr + ", server being checked: "
1949       + serverName);
1950     return matchAssignedAddr;
1951   }
1952 
1953   /**
1954    * Process shutdown server removing any assignments.
1955    * @param sn Server that went down.
1956    * @return list of regions in transition on this server
1957    */
1958   public List<HRegionInfo> processServerShutdown(final ServerName sn) {
1959     // Clean out any existing assignment plans for this server
1960     synchronized (this.regionPlans) {
1961       for (Iterator <Map.Entry<String, RegionPlan>> i =
1962           this.regionPlans.entrySet().iterator(); i.hasNext();) {
1963         Map.Entry<String, RegionPlan> e = i.next();
1964         ServerName otherSn = e.getValue().getDestination();
1965         // The name will be null if the region is planned for a random assign.
1966         if (otherSn != null && otherSn.equals(sn)) {
1967           // Use iterator's remove else we'll get CME
1968           i.remove();
1969         }
1970       }
1971     }
1972     List<HRegionInfo> rits = regionStates.serverOffline(sn);
1973     for (Iterator<HRegionInfo> it = rits.iterator(); it.hasNext(); ) {
1974       HRegionInfo hri = it.next();
1975       String encodedName = hri.getEncodedName();
1976 
1977       // We need a lock on the region as we could update it
1978       Lock lock = locker.acquireLock(encodedName);
1979       try {
1980         RegionState regionState =
1981           regionStates.getRegionTransitionState(encodedName);
1982         if (regionState == null
1983             || (regionState.getServerName() != null && !regionState.isOnServer(sn))
1984             || !RegionStates.isOneOfStates(regionState, State.PENDING_OPEN,
1985                 State.OPENING, State.FAILED_OPEN, State.FAILED_CLOSE, State.OFFLINE)) {
1986           LOG.info("Skip " + regionState + " since it is not opening/failed_close"
1987             + " on the dead server any more: " + sn);
1988           it.remove();
1989         } else {
1990           if (tableStateManager.isTableState(hri.getTable(),
1991                   TableState.State.DISABLED, TableState.State.DISABLING)) {
1992             regionStates.regionOffline(hri);
1993             it.remove();
1994             continue;
1995           }
1996           // Mark the region offline and assign it again by SSH
1997           regionStates.updateRegionState(hri, State.OFFLINE);
1998         }
1999       } finally {
2000         lock.unlock();
2001       }
2002     }
2003     return rits;
2004   }
2005 
2006   /**
2007    * @param plan Plan to execute.
2008    */
2009   public void balance(final RegionPlan plan) {
2010     HRegionInfo hri = plan.getRegionInfo();
2011     TableName tableName = hri.getTable();
2012     if (tableStateManager.isTableState(tableName,
2013             TableState.State.DISABLED, TableState.State.DISABLING)) {
2014       LOG.info("Ignored moving region of disabling/disabled table "
2015         + tableName);
2016       return;
2017     }
2018 
2019     // Move the region only if it's assigned
2020     String encodedName = hri.getEncodedName();
2021     ReentrantLock lock = locker.acquireLock(encodedName);
2022     try {
2023       if (!regionStates.isRegionOnline(hri)) {
2024         RegionState state = regionStates.getRegionState(encodedName);
2025         LOG.info("Ignored moving region not assigned: " + hri + ", "
2026           + (state == null ? "not in region states" : state));
2027         return;
2028       }
2029       synchronized (this.regionPlans) {
2030         this.regionPlans.put(plan.getRegionName(), plan);
2031       }
2032       unassign(hri, plan.getDestination());
2033     } finally {
2034       lock.unlock();
2035     }
2036   }
2037 
2038   public void stop() {
2039     // Shutdown the threadpool executor service
2040     threadPoolExecutorService.shutdownNow();
2041     regionStateStore.stop();
2042   }
2043 
2044   protected void setEnabledTable(TableName tableName) {
2045     try {
2046       this.tableStateManager.setTableState(tableName,
2047               TableState.State.ENABLED);
2048     } catch (IOException e) {
2049       // here we can abort as it is the start up flow
2050       String errorMsg = "Unable to ensure that the table " + tableName
2051           + " will be" + " enabled because of a ZooKeeper issue";
2052       LOG.error(errorMsg);
2053       this.server.abort(errorMsg, e);
2054     }
2055   }
2056 
2057   private String onRegionFailedOpen(final RegionState current,
2058       final HRegionInfo hri, final ServerName serverName) {
2059     // The region must be opening on this server.
2060     // If current state is failed_open on the same server,
2061     // it could be a reportRegionTransition RPC retry.
2062     if (current == null || !current.isOpeningOrFailedOpenOnServer(serverName)) {
2063       return hri.getShortNameToLog() + " is not opening on " + serverName;
2064     }
2065 
2066     // Just return in case of retrying
2067     if (current.isFailedOpen()) {
2068       return null;
2069     }
2070 
2071     String encodedName = hri.getEncodedName();
2072     AtomicInteger failedOpenCount = failedOpenTracker.get(encodedName);
2073     if (failedOpenCount == null) {
2074       failedOpenCount = new AtomicInteger();
2075       // No need to use putIfAbsent, or extra synchronization since
2076       // this whole handleRegion block is locked on the encoded region
2077       // name, and failedOpenTracker is updated only in this block
2078       failedOpenTracker.put(encodedName, failedOpenCount);
2079     }
2080     if (failedOpenCount.incrementAndGet() >= maximumAttempts) {
2081       regionStates.updateRegionState(hri, State.FAILED_OPEN);
2082       // remove the tracking info to save memory, also reset
2083       // the count for next open initiative
2084       failedOpenTracker.remove(encodedName);
2085     } else {
2086       // Handle this the same as if it were opened and then closed.
2087       RegionState regionState = regionStates.updateRegionState(hri, State.CLOSED);
2088       if (regionState != null) {
2089         // When there are more than one region server a new RS is selected as the
2090         // destination and the same is updated in the region plan. (HBASE-5546)
2091         if (getTableStateManager().isTableState(hri.getTable(),
2092                 TableState.State.DISABLED, TableState.State.DISABLING) ||
2093                 replicasToClose.contains(hri)) {
2094           offlineDisabledRegion(hri);
2095           return null;
2096         }
2097         regionStates.updateRegionState(hri, RegionState.State.CLOSED);
2098         // This below has to do w/ online enable/disable of a table
2099         removeClosedRegion(hri);
2100         try {
2101           getRegionPlan(hri, true);
2102         } catch (HBaseIOException e) {
2103           LOG.warn("Failed to get region plan", e);
2104         }
2105         invokeAssign(hri);
2106       }
2107     }
2108     // Null means no error
2109     return null;
2110   }
2111 
2112   private String onRegionOpen(final RegionState current, final HRegionInfo hri,
2113       final ServerName serverName, final RegionStateTransition transition) {
2114     // The region must be opening on this server.
2115     // If current state is already opened on the same server,
2116     // it could be a reportRegionTransition RPC retry.
2117     if (current == null || !current.isOpeningOrOpenedOnServer(serverName)) {
2118       return hri.getShortNameToLog() + " is not opening on " + serverName;
2119     }
2120 
2121     // Just return in case of retrying
2122     if (current.isOpened()) {
2123       return null;
2124     }
2125 
2126     long openSeqNum = transition.hasOpenSeqNum()
2127       ? transition.getOpenSeqNum() : HConstants.NO_SEQNUM;
2128     if (openSeqNum < 0) {
2129       return "Newly opened region has invalid open seq num " + openSeqNum;
2130     }
2131     regionOnline(hri, serverName, openSeqNum);
2132 
2133     // reset the count, if any
2134     failedOpenTracker.remove(hri.getEncodedName());
2135     if (getTableStateManager().isTableState(hri.getTable(),
2136             TableState.State.DISABLED, TableState.State.DISABLING)) {
2137       invokeUnAssign(hri);
2138     }
2139     return null;
2140   }
2141 
2142   private String onRegionClosed(final RegionState current,
2143       final HRegionInfo hri, final ServerName serverName) {
2144     // Region will be usually assigned right after closed. When a RPC retry comes
2145     // in, the region may already have moved away from closed state. However, on the
2146     // region server side, we don't care much about the response for this transition.
2147     // We only make sure master has got and processed this report, either
2148     // successfully or not. So this is fine, not a problem at all.
2149     if (current == null || !current.isClosingOrClosedOnServer(serverName)) {
2150       return hri.getShortNameToLog() + " is not closing on " + serverName;
2151     }
2152 
2153     // Just return in case of retrying
2154     if (current.isClosed()) {
2155       return null;
2156     }
2157 
2158     if (getTableStateManager().isTableState(hri.getTable(), TableState.State.DISABLED,
2159         TableState.State.DISABLING) || replicasToClose.contains(hri)) {
2160       offlineDisabledRegion(hri);
2161       return null;
2162     }
2163 
2164     regionStates.updateRegionState(hri, RegionState.State.CLOSED);
2165     sendRegionClosedNotification(hri);
2166     // This below has to do w/ online enable/disable of a table
2167     removeClosedRegion(hri);
2168     invokeAssign(hri);
2169     return null;
2170   }
2171 
2172   private String onRegionReadyToSplit(final RegionState current, final HRegionInfo hri,
2173       final ServerName serverName, final RegionStateTransition transition) {
2174     // The region must be opened on this server.
2175     // If current state is already splitting on the same server,
2176     // it could be a reportRegionTransition RPC retry.
2177     if (current == null || !current.isSplittingOrOpenedOnServer(serverName)) {
2178       return hri.getShortNameToLog() + " is not opening on " + serverName;
2179     }
2180 
2181     // Just return in case of retrying
2182     if (current.isSplitting()) {
2183       return null;
2184     }
2185 
2186     final HRegionInfo a = HRegionInfo.convert(transition.getRegionInfo(1));
2187     final HRegionInfo b = HRegionInfo.convert(transition.getRegionInfo(2));
2188     RegionState rs_a = regionStates.getRegionState(a);
2189     RegionState rs_b = regionStates.getRegionState(b);
2190     if (rs_a != null || rs_b != null) {
2191       return "Some daughter is already existing. "
2192         + "a=" + rs_a + ", b=" + rs_b;
2193     }
2194 
2195     // Server holding is not updated at this stage.
2196     // It is done after PONR.
2197     regionStates.updateRegionState(hri, State.SPLITTING);
2198     regionStates.createRegionState(
2199       a, State.SPLITTING_NEW, serverName, null);
2200     regionStates.createRegionState(
2201       b, State.SPLITTING_NEW, serverName, null);
2202     return null;
2203   }
2204 
2205   private String onRegionSplitPONR(final RegionState current, final HRegionInfo hri,
2206       final ServerName serverName, final RegionStateTransition transition) {
2207     // The region must be splitting on this server, and the daughters must be in
2208     // splitting_new state. To check RPC retry, we use server holding info.
2209     if (current == null || !current.isSplittingOnServer(serverName)) {
2210       return hri.getShortNameToLog() + " is not splitting on " + serverName;
2211     }
2212 
2213     final HRegionInfo a = HRegionInfo.convert(transition.getRegionInfo(1));
2214     final HRegionInfo b = HRegionInfo.convert(transition.getRegionInfo(2));
2215     RegionState rs_a = regionStates.getRegionState(a);
2216     RegionState rs_b = regionStates.getRegionState(b);
2217 
2218     // Master could have restarted and lost the new region
2219     // states, if so, they must be lost together
2220     if (rs_a == null && rs_b == null) {
2221       rs_a = regionStates.createRegionState(
2222         a, State.SPLITTING_NEW, serverName, null);
2223       rs_b = regionStates.createRegionState(
2224         b, State.SPLITTING_NEW, serverName, null);
2225     }
2226 
2227     if (rs_a == null || !rs_a.isSplittingNewOnServer(serverName)
2228         || rs_b == null || !rs_b.isSplittingNewOnServer(serverName)) {
2229       return "Some daughter is not known to be splitting on " + serverName
2230         + ", a=" + rs_a + ", b=" + rs_b;
2231     }
2232 
2233     // Just return in case of retrying
2234     if (!regionStates.isRegionOnServer(hri, serverName)) {
2235       return null;
2236     }
2237 
2238     try {
2239       regionStates.splitRegion(hri, a, b, serverName);
2240     } catch (IOException ioe) {
2241       LOG.info("Failed to record split region " + hri.getShortNameToLog());
2242       return "Failed to record the splitting in meta";
2243     }
2244     return null;
2245   }
2246 
2247   private String onRegionSplit(final RegionState current, final HRegionInfo hri,
2248       final ServerName serverName, final RegionStateTransition transition) {
2249     // The region must be splitting on this server, and the daughters must be in
2250     // splitting_new state.
2251     // If current state is already split on the same server,
2252     // it could be a reportRegionTransition RPC retry.
2253     if (current == null || !current.isSplittingOrSplitOnServer(serverName)) {
2254       return hri.getShortNameToLog() + " is not splitting on " + serverName;
2255     }
2256 
2257     // Just return in case of retrying
2258     if (current.isSplit()) {
2259       return null;
2260     }
2261 
2262     final HRegionInfo a = HRegionInfo.convert(transition.getRegionInfo(1));
2263     final HRegionInfo b = HRegionInfo.convert(transition.getRegionInfo(2));
2264     RegionState rs_a = regionStates.getRegionState(a);
2265     RegionState rs_b = regionStates.getRegionState(b);
2266     if (rs_a == null || !rs_a.isSplittingNewOnServer(serverName)
2267         || rs_b == null || !rs_b.isSplittingNewOnServer(serverName)) {
2268       return "Some daughter is not known to be splitting on " + serverName
2269         + ", a=" + rs_a + ", b=" + rs_b;
2270     }
2271 
2272     if (TEST_SKIP_SPLIT_HANDLING) {
2273       return "Skipping split message, TEST_SKIP_SPLIT_HANDLING is set";
2274     }
2275     regionOffline(hri, State.SPLIT);
2276     regionOnline(a, serverName, 1);
2277     regionOnline(b, serverName, 1);
2278 
2279     // User could disable the table before master knows the new region.
2280     if (getTableStateManager().isTableState(hri.getTable(),
2281         TableState.State.DISABLED, TableState.State.DISABLING)) {
2282       invokeUnAssign(a);
2283       invokeUnAssign(b);
2284     } else {
2285       Callable<Object> splitReplicasCallable = new Callable<Object>() {
2286         @Override
2287         public Object call() {
2288           doSplittingOfReplicas(hri, a, b);
2289           return null;
2290         }
2291       };
2292       threadPoolExecutorService.submit(splitReplicasCallable);
2293     }
2294     return null;
2295   }
2296 
2297   private String onRegionSplitReverted(final RegionState current, final HRegionInfo hri,
2298       final ServerName serverName, final RegionStateTransition transition) {
2299     // The region must be splitting on this server, and the daughters must be in
2300     // splitting_new state.
2301     // If the region is in open state, it could be an RPC retry.
2302     if (current == null || !current.isSplittingOrOpenedOnServer(serverName)) {
2303       return hri.getShortNameToLog() + " is not splitting on " + serverName;
2304     }
2305 
2306     // Just return in case of retrying
2307     if (current.isOpened()) {
2308       return null;
2309     }
2310 
2311     final HRegionInfo a = HRegionInfo.convert(transition.getRegionInfo(1));
2312     final HRegionInfo b = HRegionInfo.convert(transition.getRegionInfo(2));
2313     RegionState rs_a = regionStates.getRegionState(a);
2314     RegionState rs_b = regionStates.getRegionState(b);
2315     if (rs_a == null || !rs_a.isSplittingNewOnServer(serverName)
2316         || rs_b == null || !rs_b.isSplittingNewOnServer(serverName)) {
2317       return "Some daughter is not known to be splitting on " + serverName
2318         + ", a=" + rs_a + ", b=" + rs_b;
2319     }
2320 
2321     regionOnline(hri, serverName);
2322     regionOffline(a);
2323     regionOffline(b);
2324     if (getTableStateManager().isTableState(hri.getTable(),
2325         TableState.State.DISABLED, TableState.State.DISABLING)) {
2326       invokeUnAssign(hri);
2327     }
2328     return null;
2329   }
2330 
2331   private String onRegionReadyToMerge(final RegionState current, final HRegionInfo hri,
2332       final ServerName serverName, final RegionStateTransition transition) {
2333     // The region must be new, and the daughters must be open on this server.
2334     // If the region is in merge_new state, it could be an RPC retry.
2335     if (current != null && !current.isMergingNewOnServer(serverName)) {
2336       return "Merging daughter region already exists, p=" + current;
2337     }
2338 
2339     // Just return in case of retrying
2340     if (current != null) {
2341       return null;
2342     }
2343 
2344     final HRegionInfo a = HRegionInfo.convert(transition.getRegionInfo(1));
2345     final HRegionInfo b = HRegionInfo.convert(transition.getRegionInfo(2));
2346     Set<String> encodedNames = new HashSet<String>(2);
2347     encodedNames.add(a.getEncodedName());
2348     encodedNames.add(b.getEncodedName());
2349     Map<String, Lock> locks = locker.acquireLocks(encodedNames);
2350     try {
2351       RegionState rs_a = regionStates.getRegionState(a);
2352       RegionState rs_b = regionStates.getRegionState(b);
2353       if (rs_a == null || !rs_a.isOpenedOnServer(serverName)
2354           || rs_b == null || !rs_b.isOpenedOnServer(serverName)) {
2355         return "Some daughter is not in a state to merge on " + serverName
2356           + ", a=" + rs_a + ", b=" + rs_b;
2357       }
2358 
2359       regionStates.updateRegionState(a, State.MERGING);
2360       regionStates.updateRegionState(b, State.MERGING);
2361       regionStates.createRegionState(
2362         hri, State.MERGING_NEW, serverName, null);
2363       return null;
2364     } finally {
2365       for (Lock lock: locks.values()) {
2366         lock.unlock();
2367       }
2368     }
2369   }
2370 
2371   private String onRegionMergePONR(final RegionState current, final HRegionInfo hri,
2372       final ServerName serverName, final RegionStateTransition transition) {
2373     // The region must be in merging_new state, and the daughters must be
2374     // merging. To check RPC retry, we use server holding info.
2375     if (current != null && !current.isMergingNewOnServer(serverName)) {
2376       return hri.getShortNameToLog() + " is not merging on " + serverName;
2377     }
2378 
2379     final HRegionInfo a = HRegionInfo.convert(transition.getRegionInfo(1));
2380     final HRegionInfo b = HRegionInfo.convert(transition.getRegionInfo(2));
2381     RegionState rs_a = regionStates.getRegionState(a);
2382     RegionState rs_b = regionStates.getRegionState(b);
2383     if (rs_a == null || !rs_a.isMergingOnServer(serverName)
2384         || rs_b == null || !rs_b.isMergingOnServer(serverName)) {
2385       return "Some daughter is not known to be merging on " + serverName
2386         + ", a=" + rs_a + ", b=" + rs_b;
2387     }
2388 
2389     // Master could have restarted and lost the new region state
2390     if (current == null) {
2391       regionStates.createRegionState(
2392         hri, State.MERGING_NEW, serverName, null);
2393     }
2394 
2395     // Just return in case of retrying
2396     if (regionStates.isRegionOnServer(hri, serverName)) {
2397       return null;
2398     }
2399 
2400     try {
2401       regionStates.mergeRegions(hri, a, b, serverName);
2402     } catch (IOException ioe) {
2403       LOG.info("Failed to record merged region " + hri.getShortNameToLog());
2404       return "Failed to record the merging in meta";
2405     }
2406     return null;
2407   }
2408 
2409   private String onRegionMerged(final RegionState current, final HRegionInfo hri,
2410       final ServerName serverName, final RegionStateTransition transition) {
2411     // The region must be in merging_new state, and the daughters must be
2412     // merging on this server.
2413     // If current state is already opened on the same server,
2414     // it could be a reportRegionTransition RPC retry.
2415     if (current == null || !current.isMergingNewOrOpenedOnServer(serverName)) {
2416       return hri.getShortNameToLog() + " is not merging on " + serverName;
2417     }
2418 
2419     // Just return in case of retrying
2420     if (current.isOpened()) {
2421       return null;
2422     }
2423 
2424     final HRegionInfo a = HRegionInfo.convert(transition.getRegionInfo(1));
2425     final HRegionInfo b = HRegionInfo.convert(transition.getRegionInfo(2));
2426     RegionState rs_a = regionStates.getRegionState(a);
2427     RegionState rs_b = regionStates.getRegionState(b);
2428     if (rs_a == null || !rs_a.isMergingOnServer(serverName)
2429         || rs_b == null || !rs_b.isMergingOnServer(serverName)) {
2430       return "Some daughter is not known to be merging on " + serverName
2431         + ", a=" + rs_a + ", b=" + rs_b;
2432     }
2433 
2434     regionOffline(a, State.MERGED);
2435     regionOffline(b, State.MERGED);
2436     regionOnline(hri, serverName, 1);
2437 
2438     // User could disable the table before master knows the new region.
2439     if (getTableStateManager().isTableState(hri.getTable(),
2440         TableState.State.DISABLED, TableState.State.DISABLING)) {
2441       invokeUnAssign(hri);
2442     } else {
2443       Callable<Object> mergeReplicasCallable = new Callable<Object>() {
2444         @Override
2445         public Object call() {
2446           doMergingOfReplicas(hri, a, b);
2447           return null;
2448         }
2449       };
2450       threadPoolExecutorService.submit(mergeReplicasCallable);
2451     }
2452     return null;
2453   }
2454 
2455   private String onRegionMergeReverted(final RegionState current, final HRegionInfo hri,
2456       final ServerName serverName, final RegionStateTransition transition) {
2457     // The region must be in merging_new state, and the daughters must be
2458     // merging on this server.
2459     // If the region is in offline state, it could be an RPC retry.
2460     if (current == null || !current.isMergingNewOrOfflineOnServer(serverName)) {
2461       return hri.getShortNameToLog() + " is not merging on " + serverName;
2462     }
2463 
2464     // Just return in case of retrying
2465     if (current.isOffline()) {
2466       return null;
2467     }
2468 
2469     final HRegionInfo a = HRegionInfo.convert(transition.getRegionInfo(1));
2470     final HRegionInfo b = HRegionInfo.convert(transition.getRegionInfo(2));
2471     RegionState rs_a = regionStates.getRegionState(a);
2472     RegionState rs_b = regionStates.getRegionState(b);
2473     if (rs_a == null || !rs_a.isMergingOnServer(serverName)
2474         || rs_b == null || !rs_b.isMergingOnServer(serverName)) {
2475       return "Some daughter is not known to be merging on " + serverName
2476         + ", a=" + rs_a + ", b=" + rs_b;
2477     }
2478 
2479     regionOnline(a, serverName);
2480     regionOnline(b, serverName);
2481     regionOffline(hri);
2482 
2483     if (getTableStateManager().isTableState(hri.getTable(),
2484         TableState.State.DISABLED, TableState.State.DISABLING)) {
2485       invokeUnAssign(a);
2486       invokeUnAssign(b);
2487     }
2488     return null;
2489   }
2490 
2491   private void doMergingOfReplicas(HRegionInfo mergedHri, final HRegionInfo hri_a,
2492       final HRegionInfo hri_b) {
2493     // Close replicas for the original unmerged regions. create/assign new replicas
2494     // for the merged parent.
2495     List<HRegionInfo> unmergedRegions = new ArrayList<HRegionInfo>();
2496     unmergedRegions.add(hri_a);
2497     unmergedRegions.add(hri_b);
2498     Map<ServerName, List<HRegionInfo>> map = regionStates.getRegionAssignments(unmergedRegions);
2499     Collection<List<HRegionInfo>> c = map.values();
2500     for (List<HRegionInfo> l : c) {
2501       for (HRegionInfo h : l) {
2502         if (!RegionReplicaUtil.isDefaultReplica(h)) {
2503           LOG.debug("Unassigning un-merged replica " + h);
2504           unassign(h);
2505         }
2506       }
2507     }
2508     int numReplicas = 1;
2509     try {
2510       numReplicas = ((MasterServices)server).getTableDescriptors().get(mergedHri.getTable()).
2511           getRegionReplication();
2512     } catch (IOException e) {
2513       LOG.warn("Couldn't get the replication attribute of the table " + mergedHri.getTable() +
2514           " due to " + e.getMessage() + ". The assignment of replicas for the merged region " +
2515           "will not be done");
2516     }
2517     List<HRegionInfo> regions = new ArrayList<HRegionInfo>();
2518     for (int i = 1; i < numReplicas; i++) {
2519       regions.add(RegionReplicaUtil.getRegionInfoForReplica(mergedHri, i));
2520     }
2521     try {
2522       assign(regions);
2523     } catch (IOException ioe) {
2524       LOG.warn("Couldn't assign all replica(s) of region " + mergedHri + " because of " +
2525                 ioe.getMessage());
2526     } catch (InterruptedException ie) {
2527       LOG.warn("Couldn't assign all replica(s) of region " + mergedHri+ " because of " +
2528                 ie.getMessage());
2529     }
2530   }
2531 
2532   private void doSplittingOfReplicas(final HRegionInfo parentHri, final HRegionInfo hri_a,
2533       final HRegionInfo hri_b) {
2534     // create new regions for the replica, and assign them to match with the
2535     // current replica assignments. If replica1 of parent is assigned to RS1,
2536     // the replica1s of daughters will be on the same machine
2537     int numReplicas = 1;
2538     try {
2539       numReplicas = ((MasterServices)server).getTableDescriptors().get(parentHri.getTable()).
2540           getRegionReplication();
2541     } catch (IOException e) {
2542       LOG.warn("Couldn't get the replication attribute of the table " + parentHri.getTable() +
2543           " due to " + e.getMessage() + ". The assignment of daughter replicas " +
2544           "replicas will not be done");
2545     }
2546     // unassign the old replicas
2547     List<HRegionInfo> parentRegion = new ArrayList<HRegionInfo>();
2548     parentRegion.add(parentHri);
2549     Map<ServerName, List<HRegionInfo>> currentAssign =
2550         regionStates.getRegionAssignments(parentRegion);
2551     Collection<List<HRegionInfo>> c = currentAssign.values();
2552     for (List<HRegionInfo> l : c) {
2553       for (HRegionInfo h : l) {
2554         if (!RegionReplicaUtil.isDefaultReplica(h)) {
2555           LOG.debug("Unassigning parent's replica " + h);
2556           unassign(h);
2557         }
2558       }
2559     }
2560     // assign daughter replicas
2561     Map<HRegionInfo, ServerName> map = new HashMap<HRegionInfo, ServerName>();
2562     for (int i = 1; i < numReplicas; i++) {
2563       prepareDaughterReplicaForAssignment(hri_a, parentHri, i, map);
2564       prepareDaughterReplicaForAssignment(hri_b, parentHri, i, map);
2565     }
2566     try {
2567       assign(map);
2568     } catch (IOException e) {
2569       LOG.warn("Caught exception " + e + " while trying to assign replica(s) of daughter(s)");
2570     } catch (InterruptedException e) {
2571       LOG.warn("Caught exception " + e + " while trying to assign replica(s) of daughter(s)");
2572     }
2573   }
2574 
2575   private void prepareDaughterReplicaForAssignment(HRegionInfo daughterHri, HRegionInfo parentHri,
2576       int replicaId, Map<HRegionInfo, ServerName> map) {
2577     HRegionInfo parentReplica = RegionReplicaUtil.getRegionInfoForReplica(parentHri, replicaId);
2578     HRegionInfo daughterReplica = RegionReplicaUtil.getRegionInfoForReplica(daughterHri,
2579         replicaId);
2580     LOG.debug("Created replica region for daughter " + daughterReplica);
2581     ServerName sn;
2582     if ((sn = regionStates.getRegionServerOfRegion(parentReplica)) != null) {
2583       map.put(daughterReplica, sn);
2584     } else {
2585       List<ServerName> servers = serverManager.getOnlineServersList();
2586       sn = servers.get((new Random(System.currentTimeMillis())).nextInt(servers.size()));
2587       map.put(daughterReplica, sn);
2588     }
2589   }
2590 
2591   public Set<HRegionInfo> getReplicasToClose() {
2592     return replicasToClose;
2593   }
2594 
2595   /**
2596    * A region is offline.  The new state should be the specified one,
2597    * if not null.  If the specified state is null, the new state is Offline.
2598    * The specified state can be Split/Merged/Offline/null only.
2599    */
2600   private void regionOffline(final HRegionInfo regionInfo, final State state) {
2601     regionStates.regionOffline(regionInfo, state);
2602     removeClosedRegion(regionInfo);
2603     // remove the region plan as well just in case.
2604     clearRegionPlan(regionInfo);
2605     balancer.regionOffline(regionInfo);
2606 
2607     // Tell our listeners that a region was closed
2608     sendRegionClosedNotification(regionInfo);
2609     // also note that all the replicas of the primary should be closed
2610     if (state != null && state.equals(State.SPLIT)) {
2611       Collection<HRegionInfo> c = new ArrayList<HRegionInfo>(1);
2612       c.add(regionInfo);
2613       Map<ServerName, List<HRegionInfo>> map = regionStates.getRegionAssignments(c);
2614       Collection<List<HRegionInfo>> allReplicas = map.values();
2615       for (List<HRegionInfo> list : allReplicas) {
2616         replicasToClose.addAll(list);
2617       }
2618     }
2619     else if (state != null && state.equals(State.MERGED)) {
2620       Collection<HRegionInfo> c = new ArrayList<HRegionInfo>(1);
2621       c.add(regionInfo);
2622       Map<ServerName, List<HRegionInfo>> map = regionStates.getRegionAssignments(c);
2623       Collection<List<HRegionInfo>> allReplicas = map.values();
2624       for (List<HRegionInfo> list : allReplicas) {
2625         replicasToClose.addAll(list);
2626       }
2627     }
2628   }
2629 
2630   private void sendRegionOpenedNotification(final HRegionInfo regionInfo,
2631       final ServerName serverName) {
2632     if (!this.listeners.isEmpty()) {
2633       for (AssignmentListener listener : this.listeners) {
2634         listener.regionOpened(regionInfo, serverName);
2635       }
2636     }
2637   }
2638 
2639   private void sendRegionClosedNotification(final HRegionInfo regionInfo) {
2640     if (!this.listeners.isEmpty()) {
2641       for (AssignmentListener listener : this.listeners) {
2642         listener.regionClosed(regionInfo);
2643       }
2644     }
2645   }
2646 
2647   /**
2648    * Try to update some region states. If the state machine prevents
2649    * such update, an error message is returned to explain the reason.
2650    *
2651    * It's expected that in each transition there should have just one
2652    * region for opening/closing, 3 regions for splitting/merging.
2653    * These regions should be on the server that requested the change.
2654    *
2655    * Region state machine. Only these transitions
2656    * are expected to be triggered by a region server.
2657    *
2658    * On the state transition:
2659    *  (1) Open/Close should be initiated by master
2660    *      (a) Master sets the region to pending_open/pending_close
2661    *        in memory and hbase:meta after sending the request
2662    *        to the region server
2663    *      (b) Region server reports back to the master
2664    *        after open/close is done (either success/failure)
2665    *      (c) If region server has problem to report the status
2666    *        to master, it must be because the master is down or some
2667    *        temporary network issue. Otherwise, the region server should
2668    *        abort since it must be a bug. If the master is not accessible,
2669    *        the region server should keep trying until the server is
2670    *        stopped or till the status is reported to the (new) master
2671    *      (d) If region server dies in the middle of opening/closing
2672    *        a region, SSH picks it up and finishes it
2673    *      (e) If master dies in the middle, the new master recovers
2674    *        the state during initialization from hbase:meta. Region server
2675    *        can report any transition that has not been reported to
2676    *        the previous active master yet
2677    *  (2) Split/merge is initiated by region servers
2678    *      (a) To split a region, a region server sends a request
2679    *        to master to try to set a region to splitting, together with
2680    *        two daughters (to be created) to splitting new. If approved
2681    *        by the master, the splitting can then move ahead
2682    *      (b) To merge two regions, a region server sends a request to
2683    *        master to try to set the new merged region (to be created) to
2684    *        merging_new, together with two regions (to be merged) to merging.
2685    *        If it is ok with the master, the merge can then move ahead
2686    *      (c) Once the splitting/merging is done, the region server
2687    *        reports the status back to the master either success/failure.
2688    *      (d) Other scenarios should be handled similarly as for
2689    *        region open/close
2690    */
2691   protected String onRegionTransition(final ServerName serverName,
2692       final RegionStateTransition transition) {
2693     TransitionCode code = transition.getTransitionCode();
2694     HRegionInfo hri = HRegionInfo.convert(transition.getRegionInfo(0));
2695     Lock lock = locker.acquireLock(hri.getEncodedName());
2696     try {
2697       RegionState current = regionStates.getRegionState(hri);
2698       if (LOG.isDebugEnabled()) {
2699         LOG.debug("Got transition " + code + " for "
2700           + (current != null ? current.toString() : hri.getShortNameToLog())
2701           + " from " + serverName);
2702       }
2703       String errorMsg = null;
2704       switch (code) {
2705       case OPENED:
2706         errorMsg = onRegionOpen(current, hri, serverName, transition);
2707         break;
2708       case FAILED_OPEN:
2709         errorMsg = onRegionFailedOpen(current, hri, serverName);
2710         break;
2711       case CLOSED:
2712         errorMsg = onRegionClosed(current, hri, serverName);
2713         break;
2714       case READY_TO_SPLIT:
2715         errorMsg = onRegionReadyToSplit(current, hri, serverName, transition);
2716         break;
2717       case SPLIT_PONR:
2718         errorMsg = onRegionSplitPONR(current, hri, serverName, transition);
2719         break;
2720       case SPLIT:
2721         errorMsg = onRegionSplit(current, hri, serverName, transition);
2722         break;
2723       case SPLIT_REVERTED:
2724         errorMsg = onRegionSplitReverted(current, hri, serverName, transition);
2725         break;
2726       case READY_TO_MERGE:
2727         errorMsg = onRegionReadyToMerge(current, hri, serverName, transition);
2728         break;
2729       case MERGE_PONR:
2730         errorMsg = onRegionMergePONR(current, hri, serverName, transition);
2731         break;
2732       case MERGED:
2733         errorMsg = onRegionMerged(current, hri, serverName, transition);
2734         break;
2735       case MERGE_REVERTED:
2736         errorMsg = onRegionMergeReverted(current, hri, serverName, transition);
2737         break;
2738 
2739       default:
2740         errorMsg = "Unexpected transition code " + code;
2741       }
2742       if (errorMsg != null) {
2743         LOG.info("Could not transition region from " + current + " on "
2744           + code + " by " + serverName + ": " + errorMsg);
2745       }
2746       return errorMsg;
2747     } finally {
2748       lock.unlock();
2749     }
2750   }
2751 
2752   /**
2753    * @return Instance of load balancer
2754    */
2755   public LoadBalancer getBalancer() {
2756     return this.balancer;
2757   }
2758 
2759   public Map<ServerName, List<HRegionInfo>>
2760     getSnapShotOfAssignment(Collection<HRegionInfo> infos) {
2761     return getRegionStates().getRegionAssignments(infos);
2762   }
2763 }