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