View Javadoc

1   /**
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *     http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
17   */
18  package org.apache.hadoop.hbase.master;
19  
20  import java.io.IOException;
21  import java.util.ArrayList;
22  import java.util.Collection;
23  import java.util.HashMap;
24  import java.util.HashSet;
25  import java.util.Iterator;
26  import java.util.List;
27  import java.util.Map;
28  import java.util.Set;
29  import java.util.Comparator;
30  import java.util.SortedSet;
31  import java.util.TreeMap;
32  import java.util.TreeSet;
33  
34  import org.apache.commons.logging.Log;
35  import org.apache.commons.logging.LogFactory;
36  import org.apache.hadoop.conf.Configuration;
37  import org.apache.hadoop.hbase.HConstants;
38  import org.apache.hadoop.hbase.HRegionInfo;
39  import org.apache.hadoop.hbase.HTableDescriptor;
40  import org.apache.hadoop.hbase.MetaTableAccessor;
41  import org.apache.hadoop.hbase.RegionTransition;
42  import org.apache.hadoop.hbase.ServerLoad;
43  import org.apache.hadoop.hbase.ServerName;
44  import org.apache.hadoop.hbase.TableName;
45  import org.apache.hadoop.hbase.TableStateManager;
46  import org.apache.hadoop.hbase.classification.InterfaceAudience;
47  import org.apache.hadoop.hbase.client.RegionReplicaUtil;
48  import org.apache.hadoop.hbase.master.RegionState.State;
49  import org.apache.hadoop.hbase.protobuf.generated.ZooKeeperProtos;
50  import org.apache.hadoop.hbase.util.Bytes;
51  import org.apache.hadoop.hbase.util.ConfigUtil;
52  import org.apache.hadoop.hbase.util.FSUtils;
53  import org.apache.hadoop.hbase.util.Pair;
54  import org.apache.hadoop.hbase.zookeeper.ZKAssign;
55  import org.apache.hadoop.hbase.zookeeper.ZooKeeperWatcher;
56  import org.apache.zookeeper.KeeperException;
57  
58  import com.google.common.annotations.VisibleForTesting;
59  import com.google.common.base.Preconditions;
60  
61  /**
62   * Region state accountant. It holds the states of all regions in the memory.
63   * In normal scenario, it should match the meta table and the true region states.
64   *
65   * This map is used by AssignmentManager to track region states.
66   */
67  @InterfaceAudience.Private
68  public class RegionStates {
69    private static final Log LOG = LogFactory.getLog(RegionStates.class);
70  
71    public final static RegionStateStampComparator REGION_STATE_COMPARATOR =
72      new RegionStateStampComparator();
73  
74    // This comparator sorts the RegionStates by time stamp then Region name.
75    // Comparing by timestamp alone can lead us to discard different RegionStates that happen
76    // to share a timestamp.
77    private static class RegionStateStampComparator implements Comparator<RegionState> {
78      @Override
79      public int compare(RegionState l, RegionState r) {
80        return Long.compare(l.getStamp(), r.getStamp()) == 0 ?
81            Bytes.compareTo(l.getRegion().getRegionName(), r.getRegion().getRegionName()) :
82            Long.compare(l.getStamp(), r.getStamp());
83      }
84    }
85  
86    /**
87     * Regions currently in transition.
88     */
89    final HashMap<String, RegionState> regionsInTransition =
90      new HashMap<String, RegionState>();
91  
92    /**
93     * Region encoded name to state map.
94     * All the regions should be in this map.
95     */
96    private final Map<String, RegionState> regionStates =
97      new HashMap<String, RegionState>();
98  
99    /**
100    * Holds mapping of table -> region state
101    */
102   private final Map<TableName, Map<String, RegionState>> regionStatesTableIndex =
103       new HashMap<TableName, Map<String, RegionState>>();
104 
105   /**
106    * Server to regions assignment map.
107    * Contains the set of regions currently assigned to a given server.
108    */
109   private final Map<ServerName, Set<HRegionInfo>> serverHoldings =
110     new HashMap<ServerName, Set<HRegionInfo>>();
111 
112   /**
113    * Maintains the mapping from the default region to the replica regions.
114    */
115   private final Map<HRegionInfo, Set<HRegionInfo>> defaultReplicaToOtherReplicas =
116     new HashMap<HRegionInfo, Set<HRegionInfo>>();
117 
118   /**
119    * Region to server assignment map.
120    * Contains the server a given region is currently assigned to.
121    */
122   private final TreeMap<HRegionInfo, ServerName> regionAssignments =
123     new TreeMap<HRegionInfo, ServerName>();
124 
125   /**
126    * Encoded region name to server assignment map for re-assignment
127    * purpose. Contains the server a given region is last known assigned
128    * to, which has not completed log splitting, so not assignable.
129    * If a region is currently assigned, this server info in this
130    * map should be the same as that in regionAssignments.
131    * However the info in regionAssignments is cleared when the region
132    * is offline while the info in lastAssignments is cleared when
133    * the region is closed or the server is dead and processed.
134    */
135   private final HashMap<String, ServerName> lastAssignments =
136     new HashMap<String, ServerName>();
137 
138   /**
139    * Encoded region name to server assignment map for the
140    * purpose to clean up serverHoldings when a region is online
141    * on a new server. When the region is offline from the previous
142    * server, we cleaned up regionAssignments so that it has the
143    * latest assignment map. But we didn't clean up serverHoldings
144    * to match the meta. We need this map to find out the old server
145    * whose serverHoldings needs cleanup, given a moved region.
146    */
147   private final HashMap<String, ServerName> oldAssignments =
148     new HashMap<String, ServerName>();
149 
150   /**
151    * Map a host port pair string to the latest start code
152    * of a region server which is known to be dead. It is dead
153    * to us, but server manager may not know it yet.
154    */
155   private final HashMap<String, Long> deadServers =
156     new HashMap<String, Long>();
157 
158   /**
159    * Map a dead servers to the time when log split is done.
160    * Since log splitting is not ordered, we have to remember
161    * all processed instances. The map is cleaned up based
162    * on a configured time. By default, we assume a dead
163    * server should be done with log splitting in two hours.
164    */
165   private final HashMap<ServerName, Long> processedServers =
166     new HashMap<ServerName, Long>();
167   private long lastProcessedServerCleanTime;
168 
169   private final TableStateManager tableStateManager;
170   private final RegionStateStore regionStateStore;
171   private final ServerManager serverManager;
172   private final MasterServices server;
173   private final boolean useZK; // Is it ZK based assignment?
174 
175   // The maximum time to keep a log split info in region states map
176   static final String LOG_SPLIT_TIME = "hbase.master.maximum.logsplit.keeptime";
177   static final long DEFAULT_LOG_SPLIT_TIME = 7200000L; // 2 hours
178 
179   RegionStates(final MasterServices master, final TableStateManager tableStateManager,
180       final ServerManager serverManager, final RegionStateStore regionStateStore) {
181     this.tableStateManager = tableStateManager;
182     this.regionStateStore = regionStateStore;
183     this.serverManager = serverManager;
184     this.server = master;
185     this.useZK = ConfigUtil.useZKForAssignment(server.getConfiguration());
186   }
187 
188   /**
189    * @return a copy of the region assignment map
190    */
191   public synchronized Map<HRegionInfo, ServerName> getRegionAssignments() {
192     return new TreeMap<HRegionInfo, ServerName>(regionAssignments);
193   }
194 
195   /**
196    * Return the replicas (including default) for the regions grouped by ServerName
197    * @param regions
198    * @return a pair containing the groupings as a map
199    */
200   synchronized Map<ServerName, List<HRegionInfo>> getRegionAssignments(
201     Collection<HRegionInfo> regions) {
202     Map<ServerName, List<HRegionInfo>> map = new HashMap<ServerName, List<HRegionInfo>>();
203     for (HRegionInfo region : regions) {
204       HRegionInfo defaultReplica = RegionReplicaUtil.getRegionInfoForDefaultReplica(region);
205       Set<HRegionInfo> allReplicas = defaultReplicaToOtherReplicas.get(defaultReplica);
206       if (allReplicas != null) {
207         for (HRegionInfo hri : allReplicas) {
208           ServerName server = regionAssignments.get(hri);
209           if (server != null) {
210             List<HRegionInfo> regionsOnServer = map.get(server);
211             if (regionsOnServer == null) {
212               regionsOnServer = new ArrayList<HRegionInfo>(1);
213               map.put(server, regionsOnServer);
214             }
215             regionsOnServer.add(hri);
216           }
217         }
218       }
219     }
220     return map;
221   }
222 
223   public synchronized ServerName getRegionServerOfRegion(HRegionInfo hri) {
224     return regionAssignments.get(hri);
225   }
226 
227   /**
228    * Get regions in transition and their states
229    */
230   public synchronized Set<RegionState> getRegionsInTransition() {
231     return new HashSet<RegionState>(regionsInTransition.values());
232   }
233 
234   /**
235    * @return a set of the regions in transition that are sorted by timestamp
236    */
237   public synchronized SortedSet<RegionState> getRegionsInTransitionOrderedByTimestamp() {
238     final TreeSet<RegionState> rit = new TreeSet<RegionState>(REGION_STATE_COMPARATOR);
239     for (RegionState rs: regionsInTransition.values()) {
240       rit.add(rs);
241     }
242     return rit;
243   }
244 
245   /**
246    * Get the number of regions in transition.
247    */
248   public synchronized int getRegionsInTransitionCount() {
249     return regionsInTransition.size();
250   }
251 
252   /**
253    * @return True if specified region in transition.
254    */
255   public synchronized boolean isRegionInTransition(final HRegionInfo hri) {
256     return regionsInTransition.containsKey(hri.getEncodedName());
257   }
258 
259   /**
260    * @return True if specified region in transition.
261    */
262   public synchronized boolean isRegionInTransition(final String encodedName) {
263     return regionsInTransition.containsKey(encodedName);
264   }
265 
266   /**
267    * @return True if any region in transition.
268    */
269   public synchronized boolean isRegionsInTransition() {
270     return !regionsInTransition.isEmpty();
271   }
272 
273   /**
274    * @return True if hbase:meta table region is in transition.
275    */
276   public synchronized boolean isMetaRegionInTransition() {
277     for (RegionState state : regionsInTransition.values()) {
278       if (state.getRegion().isMetaRegion()) return true;
279     }
280     return false;
281   }
282 
283   /**
284    * @return True if specified region assigned, and not in transition.
285    */
286   public synchronized boolean isRegionOnline(final HRegionInfo hri) {
287     return !isRegionInTransition(hri) && regionAssignments.containsKey(hri);
288   }
289 
290   /**
291    * @return True if specified region offline/closed, but not in transition.
292    * If the region is not in the map, it is offline to us too.
293    */
294   public synchronized boolean isRegionOffline(final HRegionInfo hri) {
295     return getRegionState(hri) == null || (!isRegionInTransition(hri)
296       && isRegionInState(hri, State.OFFLINE, State.CLOSED));
297   }
298 
299   /**
300    * @return True if specified region is in one of the specified states.
301    */
302   public boolean isRegionInState(
303       final HRegionInfo hri, final State... states) {
304     return isRegionInState(hri.getEncodedName(), states);
305   }
306 
307   /**
308    * @return True if specified region is in one of the specified states.
309    */
310   public boolean isRegionInState(
311       final String encodedName, final State... states) {
312     RegionState regionState = getRegionState(encodedName);
313     return isOneOfStates(regionState, states);
314   }
315 
316   /**
317    * Wait for the state map to be updated by assignment manager.
318    */
319   public synchronized void waitForUpdate(
320       final long timeout) throws InterruptedException {
321     this.wait(timeout);
322   }
323 
324   /**
325    * Get region transition state
326    */
327   public RegionState getRegionTransitionState(final HRegionInfo hri) {
328     return getRegionTransitionState(hri.getEncodedName());
329   }
330 
331   /**
332    * Get region transition state
333    */
334   public synchronized RegionState
335       getRegionTransitionState(final String encodedName) {
336     return regionsInTransition.get(encodedName);
337   }
338 
339   /**
340    * Add a list of regions to RegionStates. If a region is split
341    * and offline, its state will be SPLIT. Otherwise, its state will
342    * be OFFLINE. Region already in RegionStates will be skipped.
343    */
344   public void createRegionStates(
345       final List<HRegionInfo> hris) {
346     for (HRegionInfo hri: hris) {
347       createRegionState(hri);
348     }
349   }
350 
351   /**
352    * Add a region to RegionStates. If the region is split
353    * and offline, its state will be SPLIT. Otherwise, its state will
354    * be OFFLINE. If it is already in RegionStates, this call has
355    * no effect, and the original state is returned.
356    */
357   public RegionState createRegionState(final HRegionInfo hri) {
358     return createRegionState(hri, null, null, null);
359   }
360 
361   /**
362    * Add a region to RegionStates with the specified state.
363    * If the region is already in RegionStates, this call has
364    * no effect, and the original state is returned.
365    *
366    * @param hri the region info to create a state for
367    * @param newState the state to the region in set to
368    * @param serverName the server the region is transitioning on
369    * @param lastHost the last server that hosts the region
370    * @return the current state
371    */
372   public synchronized RegionState createRegionState(final HRegionInfo hri,
373       State newState, ServerName serverName, ServerName lastHost) {
374     if (newState == null || (newState == State.OPEN && serverName == null)) {
375       newState =  State.OFFLINE;
376     }
377     if (hri.isOffline() && hri.isSplit()) {
378       newState = State.SPLIT;
379       serverName = null;
380     }
381     String encodedName = hri.getEncodedName();
382     RegionState regionState = regionStates.get(encodedName);
383     if (regionState != null) {
384       LOG.warn("Tried to create a state for a region already in RegionStates, "
385         + "used existing: " + regionState + ", ignored new: " + newState);
386     } else {
387       regionState = new RegionState(hri, newState, serverName);
388       putRegionState(regionState);
389       if (newState == State.OPEN) {
390         if (!serverName.equals(lastHost)) {
391           LOG.warn("Open region's last host " + lastHost
392             + " should be the same as the current one " + serverName
393             + ", ignored the last and used the current one");
394           lastHost = serverName;
395         }
396         lastAssignments.put(encodedName, lastHost);
397         regionAssignments.put(hri, lastHost);
398       } else if (!regionState.isUnassignable()) {
399         regionsInTransition.put(encodedName, regionState);
400       }
401       if (lastHost != null && newState != State.SPLIT) {
402         addToServerHoldings(lastHost, hri);
403         if (newState != State.OPEN) {
404           oldAssignments.put(encodedName, lastHost);
405         }
406       }
407     }
408     return regionState;
409   }
410 
411   private RegionState putRegionState(RegionState regionState) {
412     HRegionInfo hri = regionState.getRegion();
413     String encodedName = hri.getEncodedName();
414     TableName table = hri.getTable();
415     RegionState oldState = regionStates.put(encodedName, regionState);
416     Map<String, RegionState> map = regionStatesTableIndex.get(table);
417     if (map == null) {
418       map = new HashMap<String, RegionState>();
419       regionStatesTableIndex.put(table, map);
420     }
421     map.put(encodedName, regionState);
422     return oldState;
423   }
424 
425   /**
426    * Set the region state to CLOSED
427    */
428   public RegionState setRegionStateTOCLOSED(
429       final byte[] regionName,
430       final ServerName serverName) {
431     HRegionInfo regionInfo = getRegionInfo(regionName);
432     return setRegionStateTOCLOSED(regionInfo, serverName);
433   }
434 
435   /**
436    * Set the region state to CLOSED
437    */
438   public RegionState setRegionStateTOCLOSED(
439       final HRegionInfo regionInfo,
440       final ServerName serverName) {
441     ServerName sn = serverName;
442     if (sn == null) {
443       RegionState regionState = getRegionState(regionInfo.getEncodedName());
444       if (regionState != null) {
445         sn = regionState.getServerName();
446       }
447       // TODO: if sn is null, should we dig into
448       // lastAssignments.get(regionInfo.getEncodedName() to get the server name?
449       // For now, I just keep the same logic that works in the past
450     }
451     // We have to make sure that the last region server is set to be the same as the
452     // current RS.  If we don't do that, we could run into situation that both AM and SSH
453     // think other would do the assignment work; at the end, neither does the work and
454     // region remains RIT.
455     // See HBASE-13330 and HBASE-17023
456     setLastRegionServerOfRegion(sn, regionInfo.getEncodedName());
457     return updateRegionState(regionInfo, State.CLOSED, sn);
458   }
459 
460   /**
461    * Update a region state. It will be put in transition if not already there.
462    */
463   public RegionState updateRegionState(
464       final HRegionInfo hri, final State state) {
465     RegionState regionState = getRegionState(hri.getEncodedName());
466     return updateRegionState(hri, state,
467       regionState == null ? null : regionState.getServerName());
468   }
469 
470   /**
471    * Update a region state. It will be put in transition if not already there.
472    *
473    * If we can't find the region info based on the region name in
474    * the transition, log a warning and return null.
475    */
476   public RegionState updateRegionState(
477       final RegionTransition transition, final State state) {
478     byte [] regionName = transition.getRegionName();
479     HRegionInfo regionInfo = getRegionInfo(regionName);
480     if (regionInfo == null) {
481       String prettyRegionName = HRegionInfo.prettyPrint(
482         HRegionInfo.encodeRegionName(regionName));
483       LOG.warn("Failed to find region " + prettyRegionName
484         + " in updating its state to " + state
485         + " based on region transition " + transition);
486       return null;
487     }
488     return updateRegionState(regionInfo, state,
489       transition.getServerName());
490   }
491 
492   /**
493    * Transition a region state to OPEN from OPENING/PENDING_OPEN
494    */
495   public synchronized RegionState transitionOpenFromPendingOpenOrOpeningOnServer(
496       final RegionTransition transition, final RegionState fromState, final ServerName sn) {
497     if(fromState.isPendingOpenOrOpeningOnServer(sn)){
498       return updateRegionState(transition, State.OPEN);
499     }
500     return null;
501   }
502 
503   /**
504    * Update a region state. It will be put in transition if not already there.
505    */
506   public RegionState updateRegionState(
507       final HRegionInfo hri, final State state, final ServerName serverName) {
508     return updateRegionState(hri, state, serverName, HConstants.NO_SEQNUM);
509   }
510 
511   public void regionOnline(final HRegionInfo hri, final ServerName serverName) {
512     regionOnline(hri, serverName, HConstants.NO_SEQNUM);
513   }
514 
515   /**
516    * A region is online, won't be in transition any more.
517    * We can't confirm it is really online on specified region server
518    * because it hasn't been put in region server's online region list yet.
519    */
520   public void regionOnline(final HRegionInfo hri, final ServerName serverName, long openSeqNum) {
521     String encodedName = hri.getEncodedName();
522     if (!serverManager.isServerOnline(serverName)) {
523       // This is possible if the region server dies before master gets a
524       // chance to handle ZK event in time. At this time, if the dead server
525       // is already processed by SSH, we should ignore this event.
526       // If not processed yet, ignore and let SSH deal with it.
527       LOG.warn("Ignored, " + encodedName + " was opened on a dead server: " + serverName);
528       return;
529     }
530     updateRegionState(hri, State.OPEN, serverName, openSeqNum);
531 
532     synchronized (this) {
533       RegionState regionState = regionsInTransition.remove(encodedName);
534       // When region is online and remove from regionsInTransition,
535       // update the RIT duration to assignment manager metrics
536       if (regionState != null && this.server.getAssignmentManager() != null) {
537         long ritDuration = System.currentTimeMillis() - regionState.getStamp()
538             + regionState.getRitDuration();
539         this.server.getAssignmentManager().getAssignmentManagerMetrics()
540             .updateRitDuration(ritDuration);
541       }
542       ServerName oldServerName = regionAssignments.put(hri, serverName);
543       if (!serverName.equals(oldServerName)) {
544         if (LOG.isDebugEnabled()) {
545           LOG.debug("Onlined " + hri.getShortNameToLog() + " on " + serverName);
546         }
547         addToServerHoldings(serverName, hri);
548         addToReplicaMapping(hri);
549         if (oldServerName == null) {
550           oldServerName = oldAssignments.remove(encodedName);
551         }
552         if (oldServerName != null
553             && !oldServerName.equals(serverName)
554             && serverHoldings.containsKey(oldServerName)) {
555           LOG.info("Offlined " + hri.getShortNameToLog() + " from " + oldServerName);
556           removeFromServerHoldings(oldServerName, hri);
557         }
558       }
559     }
560   }
561 
562   private void addToServerHoldings(ServerName serverName, HRegionInfo hri) {
563     Set<HRegionInfo> regions = serverHoldings.get(serverName);
564     if (regions == null) {
565       regions = new HashSet<HRegionInfo>();
566       serverHoldings.put(serverName, regions);
567     }
568     regions.add(hri);
569   }
570 
571   private void addToReplicaMapping(HRegionInfo hri) {
572     HRegionInfo defaultReplica = RegionReplicaUtil.getRegionInfoForDefaultReplica(hri);
573     Set<HRegionInfo> replicas =
574         defaultReplicaToOtherReplicas.get(defaultReplica);
575     if (replicas == null) {
576       replicas = new HashSet<HRegionInfo>();
577       defaultReplicaToOtherReplicas.put(defaultReplica, replicas);
578     }
579     replicas.add(hri);
580   }
581 
582   private void removeFromServerHoldings(ServerName serverName, HRegionInfo hri) {
583     Set<HRegionInfo> oldRegions = serverHoldings.get(serverName);
584     oldRegions.remove(hri);
585     if (oldRegions.isEmpty()) {
586       serverHoldings.remove(serverName);
587     }
588   }
589 
590   private void removeFromReplicaMapping(HRegionInfo hri) {
591     HRegionInfo defaultReplica = RegionReplicaUtil.getRegionInfoForDefaultReplica(hri);
592     Set<HRegionInfo> replicas = defaultReplicaToOtherReplicas.get(defaultReplica);
593     if (replicas != null) {
594       replicas.remove(hri);
595       if (replicas.isEmpty()) {
596         defaultReplicaToOtherReplicas.remove(defaultReplica);
597       }
598     }
599   }
600 
601   /**
602    * Used in some unit tests
603    */
604   @VisibleForTesting
605   synchronized boolean existsInServerHoldings(final ServerName serverName,
606       final HRegionInfo hri) {
607     Set<HRegionInfo> oldRegions = serverHoldings.get(serverName);
608     if (oldRegions != null) {
609       return oldRegions.contains(hri);
610     }
611     return false;
612   }
613 
614   /**
615    * A dead server's wals have been split so that all the regions
616    * used to be open on it can be safely assigned now. Mark them assignable.
617    */
618   public synchronized void logSplit(final ServerName serverName) {
619     for (Iterator<Map.Entry<String, ServerName>> it
620         = lastAssignments.entrySet().iterator(); it.hasNext();) {
621       Map.Entry<String, ServerName> e = it.next();
622       if (e.getValue().equals(serverName)) {
623         it.remove();
624       }
625     }
626     long now = System.currentTimeMillis();
627     if (LOG.isDebugEnabled()) {
628       LOG.debug("Adding to log splitting servers " + serverName);
629     }
630     processedServers.put(serverName, Long.valueOf(now));
631     Configuration conf = server.getConfiguration();
632     long obsoleteTime = conf.getLong(LOG_SPLIT_TIME, DEFAULT_LOG_SPLIT_TIME);
633     // Doesn't have to be very accurate about the clean up time
634     if (now > lastProcessedServerCleanTime + obsoleteTime) {
635       lastProcessedServerCleanTime = now;
636       long cutoff = now - obsoleteTime;
637       for (Iterator<Map.Entry<ServerName, Long>> it
638           = processedServers.entrySet().iterator(); it.hasNext();) {
639         Map.Entry<ServerName, Long> e = it.next();
640         if (e.getValue().longValue() < cutoff) {
641           if (LOG.isDebugEnabled()) {
642             LOG.debug("Removed from log splitting servers " + e.getKey());
643           }
644           it.remove();
645         }
646       }
647     }
648   }
649 
650   /**
651    * Log split is done for a given region, so it is assignable now.
652    */
653   public void logSplit(final HRegionInfo region) {
654     clearLastAssignment(region);
655   }
656 
657   public synchronized void clearLastAssignment(final HRegionInfo region) {
658     lastAssignments.remove(region.getEncodedName());
659   }
660 
661   /**
662    * A region is offline, won't be in transition any more.
663    */
664   public void regionOffline(final HRegionInfo hri) {
665     regionOffline(hri, null);
666   }
667 
668   /**
669    * A region is offline, won't be in transition any more. Its state
670    * should be the specified expected state, which can only be
671    * Split/Merged/Offline/null(=Offline)/SplittingNew/MergingNew.
672    */
673   public void regionOffline(
674       final HRegionInfo hri, final State expectedState) {
675     Preconditions.checkArgument(expectedState == null
676       || RegionState.isUnassignable(expectedState),
677         "Offlined region should not be " + expectedState);
678     if (isRegionInState(hri, State.SPLITTING_NEW, State.MERGING_NEW)) {
679       // Remove it from all region maps
680       deleteRegion(hri);
681       return;
682     }
683 
684     /*
685      * One tricky case, if region here is a replica region and its parent is at
686      * SPLIT state, its newState should be same as its parent, not OFFLINE.
687      */
688     State newState =
689         expectedState == null ? State.OFFLINE : expectedState;
690 
691     if ((expectedState == null) && !RegionReplicaUtil.isDefaultReplica(hri)) {
692       RegionState primateState = getRegionState(
693           RegionReplicaUtil.getRegionInfoForDefaultReplica(hri));
694       if ((primateState != null) && (primateState.getState() == State.SPLIT)) {
695         if (LOG.isDebugEnabled()) {
696           LOG.debug("Update region " + hri + "to SPLIT, from primary region " +
697               RegionReplicaUtil.getRegionInfoForDefaultReplica(hri));
698         }
699         newState = State.SPLIT;
700       }
701     }
702 
703     updateRegionState(hri, newState);
704     String encodedName = hri.getEncodedName();
705     synchronized (this) {
706       regionsInTransition.remove(encodedName);
707       ServerName oldServerName = regionAssignments.remove(hri);
708       if (oldServerName != null && serverHoldings.containsKey(oldServerName)) {
709         if (newState == State.MERGED || newState == State.SPLIT
710             || hri.isMetaRegion() || tableStateManager.isTableState(hri.getTable(),
711               ZooKeeperProtos.Table.State.DISABLED, ZooKeeperProtos.Table.State.DISABLING)) {
712           // Offline the region only if it's merged/split, or the table is disabled/disabling.
713           // Otherwise, offline it from this server only when it is online on a different server.
714           LOG.info("Offlined " + hri.getShortNameToLog() + " from " + oldServerName);
715           removeFromServerHoldings(oldServerName, hri);
716           removeFromReplicaMapping(hri);
717         } else {
718           // Need to remember it so that we can offline it from this
719           // server when it is online on a different server.
720           oldAssignments.put(encodedName, oldServerName);
721         }
722       }
723     }
724   }
725 
726   /**
727    * A server is offline, all regions on it are dead.
728    */
729   public List<HRegionInfo> serverOffline(final ZooKeeperWatcher watcher, final ServerName sn) {
730     // Offline all regions on this server not already in transition.
731     List<HRegionInfo> rits = new ArrayList<HRegionInfo>();
732     Set<HRegionInfo> regionsToClean = new HashSet<HRegionInfo>();
733     // Offline regions outside the loop and synchronized block to avoid
734     // ConcurrentModificationException and deadlock in case of meta anassigned,
735     // but RegionState a blocked.
736     Set<HRegionInfo> regionsToOffline = new HashSet<HRegionInfo>();
737     synchronized (this) {
738       Set<HRegionInfo> assignedRegions = serverHoldings.get(sn);
739       if (assignedRegions == null) {
740         assignedRegions = new HashSet<HRegionInfo>();
741       }
742 
743       for (HRegionInfo region : assignedRegions) {
744         // Offline open regions, no need to offline if SPLIT/MERGED/OFFLINE
745         if (isRegionOnline(region)) {
746           regionsToOffline.add(region);
747         } else if (isRegionInState(region, State.SPLITTING, State.MERGING)) {
748           LOG.debug("Offline splitting/merging region " + getRegionState(region));
749           try {
750             // Delete the ZNode if exists
751             ZKAssign.deleteNodeFailSilent(watcher, region);
752             regionsToOffline.add(region);
753           } catch (KeeperException ke) {
754             server.abort("Unexpected ZK exception deleting node " + region, ke);
755           }
756         }
757       }
758 
759       for (RegionState state : regionsInTransition.values()) {
760         HRegionInfo hri = state.getRegion();
761         if (assignedRegions.contains(hri)) {
762           // Region is open on this region server, but in transition.
763           // This region must be moving away from this server, or splitting/merging.
764           // SSH will handle it, either skip assigning, or re-assign.
765           LOG.info("Transitioning " + state + " will be handled by ServerCrashProcedure for " + sn);
766         } else if (sn.equals(state.getServerName())) {
767           // Region is in transition on this region server, and this
768           // region is not open on this server. So the region must be
769           // moving to this server from another one (i.e. opening or
770           // pending open on this server, was open on another one.
771           // Offline state is also kind of pending open if the region is in
772           // transition. The region could be in failed_close state too if we have
773           // tried several times to open it while this region server is not reachable)
774           if (state.isPendingOpenOrOpening() || state.isFailedClose() || state.isOffline()) {
775             LOG.info("Found region in " + state +
776               " to be reassigned by ServerCrashProcedure for " + sn);
777             rits.add(hri);
778           } else if(state.isSplittingNew() || state.isMergingNew()) {
779             LOG.info("Offline/Cleanup region if no meta entry exists, hri: " + hri +
780                 " state: " + state);
781             regionsToClean.add(state.getRegion());
782           } else {
783             LOG.warn("THIS SHOULD NOT HAPPEN: unexpected " + state);
784           }
785         }
786       }
787       this.notifyAll();
788     }
789 
790     for (HRegionInfo hri : regionsToOffline) {
791       regionOffline(hri);
792     }
793 
794     cleanFailedSplitMergeRegions(regionsToClean);
795     return rits;
796   }
797 
798   /**
799    * This method does an RPC to hbase:meta. Do not call this method with a lock/synchronize held.
800    * In ZK mode we rollback and hence cleanup daughters/merged region. We also cleanup if
801    * meta doesn't have these regions.
802    *
803    * @param hris The hris to check if empty in hbase:meta and if so, clean them up.
804    */
805   private void cleanFailedSplitMergeRegions(Set<HRegionInfo> hris) {
806     if (hris.isEmpty()) {
807       return;
808     }
809 
810     for (HRegionInfo hri : hris) {
811       // This is RPC to meta table. It is done while we have a synchronize on
812       // regionstates. No progress will be made if meta is not available at this time.
813       // This is a cleanup task. Not critical.
814       try {
815         Pair<HRegionInfo, ServerName> regionPair =
816             MetaTableAccessor.getRegion(server.getConnection(), hri.getRegionName());
817         if (regionPair == null || useZK) {
818           regionOffline(hri);
819 
820           // If we use ZK, then we can cleanup entries from meta, since we roll back.
821           if (regionPair != null) {
822             MetaTableAccessor.deleteRegion(this.server.getConnection(), hri);
823           }
824           LOG.debug("Cleaning up HDFS since no meta entry exists, hri: " + hri);
825           FSUtils.deleteRegionDir(server.getConfiguration(), hri);
826         }
827       } catch (IOException e) {
828         LOG.warn("Got exception while cleaning up region " + hri, e);
829       }
830     }
831   }
832 
833   /**
834    * Gets the online regions of the specified table.
835    * This method looks at the in-memory state.  It does not go to <code>hbase:meta</code>.
836    * Only returns <em>online</em> regions.  If a region on this table has been
837    * closed during a disable, etc., it will be included in the returned list.
838    * So, the returned list may not necessarily be ALL regions in this table, its
839    * all the ONLINE regions in the table.
840    * @param tableName
841    * @return Online regions from <code>tableName</code>
842    */
843   public synchronized List<HRegionInfo> getRegionsOfTable(TableName tableName) {
844     List<HRegionInfo> tableRegions = new ArrayList<HRegionInfo>();
845     // boundary needs to have table's name but regionID 0 so that it is sorted
846     // before all table's regions.
847     HRegionInfo boundary = new HRegionInfo(tableName, null, null, false, 0L);
848     for (HRegionInfo hri: regionAssignments.tailMap(boundary).keySet()) {
849       if(!hri.getTable().equals(tableName)) break;
850       tableRegions.add(hri);
851     }
852     return tableRegions;
853   }
854 
855   /**
856    * Gets current state of all regions of the table.
857    * This method looks at the in-memory state.  It does not go to <code>hbase:meta</code>.
858    * Method guaranteed to return keys for all states
859    * in {@link org.apache.hadoop.hbase.master.RegionState.State}
860    *
861    * @param tableName
862    * @return Online regions from <code>tableName</code>
863    */
864   public synchronized Map<RegionState.State, List<HRegionInfo>>
865   getRegionByStateOfTable(TableName tableName) {
866     Map<RegionState.State, List<HRegionInfo>> tableRegions =
867         new HashMap<State, List<HRegionInfo>>();
868     for (State state : State.values()) {
869       tableRegions.put(state, new ArrayList<HRegionInfo>());
870     }
871     Map<String, RegionState> indexMap = regionStatesTableIndex.get(tableName);
872     if (indexMap == null)
873       return tableRegions;
874     for (RegionState regionState : indexMap.values()) {
875       tableRegions.get(regionState.getState()).add(regionState.getRegion());
876     }
877     return tableRegions;
878   }
879 
880   /**
881    * Wait on region to clear regions-in-transition.
882    * <p>
883    * If the region isn't in transition, returns immediately.  Otherwise, method
884    * blocks until the region is out of transition.
885    */
886   public synchronized void waitOnRegionToClearRegionsInTransition(
887       final HRegionInfo hri) throws InterruptedException {
888     if (!isRegionInTransition(hri)) return;
889 
890     while(!server.isStopped() && isRegionInTransition(hri)) {
891       RegionState rs = getRegionState(hri);
892       LOG.info("Waiting on " + rs + " to clear regions-in-transition");
893       waitForUpdate(100);
894     }
895 
896     if (server.isStopped()) {
897       LOG.info("Giving up wait on region in " +
898         "transition because stoppable.isStopped is set");
899     }
900   }
901 
902   /**
903    * A table is deleted. Remove its regions from all internal maps.
904    * We loop through all regions assuming we don't delete tables too much.
905    */
906   public void tableDeleted(final TableName tableName) {
907     Set<HRegionInfo> regionsToDelete = new HashSet<HRegionInfo>();
908     synchronized (this) {
909       for (RegionState state: regionStates.values()) {
910         HRegionInfo region = state.getRegion();
911         if (region.getTable().equals(tableName)) {
912           regionsToDelete.add(region);
913         }
914       }
915     }
916     for (HRegionInfo region: regionsToDelete) {
917       deleteRegion(region);
918     }
919   }
920 
921   /**
922    * Get a copy of all regions assigned to a server
923    */
924   public synchronized Set<HRegionInfo> getServerRegions(ServerName serverName) {
925     Set<HRegionInfo> regions = serverHoldings.get(serverName);
926     if (regions == null) return null;
927     return new HashSet<HRegionInfo>(regions);
928   }
929 
930   /**
931    * Remove a region from all state maps.
932    */
933   @VisibleForTesting
934   public synchronized void deleteRegion(final HRegionInfo hri) {
935     String encodedName = hri.getEncodedName();
936     regionsInTransition.remove(encodedName);
937     regionStates.remove(encodedName);
938     TableName table = hri.getTable();
939     Map<String, RegionState> indexMap = regionStatesTableIndex.get(table);
940     indexMap.remove(encodedName);
941     if (indexMap.size() == 0)
942       regionStatesTableIndex.remove(table);
943     lastAssignments.remove(encodedName);
944     ServerName sn = regionAssignments.remove(hri);
945     if (sn != null) {
946       Set<HRegionInfo> regions = serverHoldings.get(sn);
947       regions.remove(hri);
948     }
949   }
950 
951   @VisibleForTesting
952   public boolean isRegionInRegionStates(final HRegionInfo hri) {
953     return (getRegionState(hri) != null || isRegionOnline(hri)) || isRegionInTransition(hri)
954         || isRegionInState(hri, State.OFFLINE, State.CLOSED);
955      }
956 
957   /**
958    * Checking if a region was assigned to a server which is not online now.
959    * If so, we should hold re-assign this region till SSH has split its wals.
960    * Once logs are split, the last assignment of this region will be reset,
961    * which means a null last assignment server is ok for re-assigning.
962    *
963    * A region server could be dead but we don't know it yet. We may
964    * think it's online falsely. Therefore if a server is online, we still
965    * need to confirm it reachable and having the expected start code.
966    */
967   synchronized boolean wasRegionOnDeadServer(final String encodedName) {
968     ServerName server = lastAssignments.get(encodedName);
969     return isServerDeadAndNotProcessed(server);
970   }
971 
972   synchronized boolean isServerDeadAndNotProcessed(ServerName server) {
973     if (server == null) return false;
974     if (serverManager.isServerOnline(server)) {
975       String hostAndPort = server.getHostAndPort();
976       long startCode = server.getStartcode();
977       Long deadCode = deadServers.get(hostAndPort);
978       if (deadCode == null || startCode > deadCode.longValue()) {
979         if (serverManager.isServerReachable(server)) {
980           return false;
981         }
982         // The size of deadServers won't grow unbounded.
983         deadServers.put(hostAndPort, Long.valueOf(startCode));
984       }
985       // Watch out! If the server is not dead, the region could
986       // remain unassigned. That's why ServerManager#isServerReachable
987       // should use some retry.
988       //
989       // We cache this info since it is very unlikely for that
990       // instance to come back up later on. We don't want to expire
991       // the server since we prefer to let it die naturally.
992       LOG.warn("Couldn't reach online server " + server);
993     }
994     // Now, we know it's dead. Check if it's processed
995     return !processedServers.containsKey(server);
996   }
997 
998  /**
999    * Get the last region server a region was on for purpose of re-assignment,
1000    * i.e. should the re-assignment be held back till log split is done?
1001    */
1002   synchronized ServerName getLastRegionServerOfRegion(final String encodedName) {
1003     return lastAssignments.get(encodedName);
1004   }
1005 
1006   synchronized void setLastRegionServerOfRegions(
1007       final ServerName serverName, final List<HRegionInfo> regionInfos) {
1008     for (HRegionInfo hri: regionInfos) {
1009       setLastRegionServerOfRegion(serverName, hri.getEncodedName());
1010     }
1011   }
1012 
1013   synchronized void setLastRegionServerOfRegion(
1014       final ServerName serverName, final String encodedName) {
1015     lastAssignments.put(encodedName, serverName);
1016   }
1017 
1018   void splitRegion(HRegionInfo p,
1019       HRegionInfo a, HRegionInfo b, ServerName sn) throws IOException {
1020 
1021     regionStateStore.splitRegion(p, a, b, sn, getRegionReplication(p));
1022     synchronized (this) {
1023       // After PONR, split is considered to be done.
1024       // Update server holdings to be aligned with the meta.
1025       Set<HRegionInfo> regions = serverHoldings.get(sn);
1026       if (regions == null) {
1027         throw new IllegalStateException(sn + " should host some regions");
1028       }
1029       regions.remove(p);
1030       regions.add(a);
1031       regions.add(b);
1032     }
1033   }
1034 
1035   void mergeRegions(HRegionInfo p,
1036       HRegionInfo a, HRegionInfo b, ServerName sn) throws IOException {
1037     regionStateStore.mergeRegions(p, a, b, sn, getRegionReplication(a));
1038     synchronized (this) {
1039       // After PONR, merge is considered to be done.
1040       // Update server holdings to be aligned with the meta.
1041       Set<HRegionInfo> regions = serverHoldings.get(sn);
1042       if (regions == null) {
1043         throw new IllegalStateException(sn + " should host some regions");
1044       }
1045       regions.remove(a);
1046       regions.remove(b);
1047       regions.add(p);
1048     }
1049   }
1050 
1051   private int getRegionReplication(HRegionInfo r) throws IOException {
1052     if (tableStateManager != null) {
1053       HTableDescriptor htd = ((MasterServices)server).getTableDescriptors().get(r.getTable());
1054       if (htd != null) {
1055         return htd.getRegionReplication();
1056       }
1057     }
1058     return 1;
1059   }
1060 
1061   /**
1062    * At cluster clean re/start, mark all user regions closed except those of tables
1063    * that are excluded, such as disabled/disabling/enabling tables. All user regions
1064    * and their previous locations are returned.
1065    */
1066   synchronized Map<HRegionInfo, ServerName> closeAllUserRegions(Set<TableName> excludedTables) {
1067     boolean noExcludeTables = excludedTables == null || excludedTables.isEmpty();
1068     Set<HRegionInfo> toBeClosed = new HashSet<HRegionInfo>(regionStates.size());
1069     for(RegionState state: regionStates.values()) {
1070       HRegionInfo hri = state.getRegion();
1071       if (state.isSplit() || hri.isSplit()) {
1072         continue;
1073       }
1074       TableName tableName = hri.getTable();
1075       if (!TableName.META_TABLE_NAME.equals(tableName)
1076           && (noExcludeTables || !excludedTables.contains(tableName))) {
1077         toBeClosed.add(hri);
1078       }
1079     }
1080     Map<HRegionInfo, ServerName> allUserRegions =
1081       new HashMap<HRegionInfo, ServerName>(toBeClosed.size());
1082     for (HRegionInfo hri: toBeClosed) {
1083       RegionState regionState = updateRegionState(hri, State.CLOSED);
1084       allUserRegions.put(hri, regionState.getServerName());
1085     }
1086     return allUserRegions;
1087   }
1088 
1089   /**
1090    * Compute the average load across all region servers.
1091    * Currently, this uses a very naive computation - just uses the number of
1092    * regions being served, ignoring stats about number of requests.
1093    * @return the average load
1094    */
1095   protected synchronized double getAverageLoad() {
1096     int numServers = 0, totalLoad = 0;
1097     for (Map.Entry<ServerName, Set<HRegionInfo>> e: serverHoldings.entrySet()) {
1098       Set<HRegionInfo> regions = e.getValue();
1099       ServerName serverName = e.getKey();
1100       int regionCount = regions.size();
1101       if (serverManager.isServerOnline(serverName)) {
1102         totalLoad += regionCount;
1103         numServers++;
1104       }
1105     }
1106     if (numServers > 1) {
1107       // The master region server holds only a couple regions.
1108       // Don't consider this server in calculating the average load
1109       // if there are other region servers to avoid possible confusion.
1110       Set<HRegionInfo> hris = serverHoldings.get(server.getServerName());
1111       if (hris != null) {
1112         totalLoad -= hris.size();
1113         numServers--;
1114       }
1115     }
1116     return numServers == 0 ? 0.0 :
1117       (double)totalLoad / (double)numServers;
1118   }
1119 
1120   /**
1121    * This is an EXPENSIVE clone.  Cloning though is the safest thing to do.
1122    * Can't let out original since it can change and at least the load balancer
1123    * wants to iterate this exported list.  We need to synchronize on regions
1124    * since all access to this.servers is under a lock on this.regions.
1125    *
1126    * @return A clone of current assignments by table.
1127    */
1128   protected Map<TableName, Map<ServerName, List<HRegionInfo>>>
1129       getAssignmentsByTable() {
1130     Map<TableName, Map<ServerName, List<HRegionInfo>>> result =
1131       new HashMap<TableName, Map<ServerName,List<HRegionInfo>>>();
1132     synchronized (this) {
1133       if (!server.getConfiguration().getBoolean(
1134             HConstants.HBASE_MASTER_LOADBALANCE_BYTABLE, false)) {
1135         Map<ServerName, List<HRegionInfo>> svrToRegions =
1136           new HashMap<ServerName, List<HRegionInfo>>(serverHoldings.size());
1137         for (Map.Entry<ServerName, Set<HRegionInfo>> e: serverHoldings.entrySet()) {
1138           svrToRegions.put(e.getKey(), new ArrayList<HRegionInfo>(e.getValue()));
1139         }
1140         result.put(TableName.valueOf(HConstants.ENSEMBLE_TABLE_NAME), svrToRegions);
1141       } else {
1142         for (Map.Entry<ServerName, Set<HRegionInfo>> e: serverHoldings.entrySet()) {
1143           for (HRegionInfo hri: e.getValue()) {
1144             if (hri.isMetaRegion()) continue;
1145             TableName tablename = hri.getTable();
1146             Map<ServerName, List<HRegionInfo>> svrToRegions = result.get(tablename);
1147             if (svrToRegions == null) {
1148               svrToRegions = new HashMap<ServerName, List<HRegionInfo>>(serverHoldings.size());
1149               result.put(tablename, svrToRegions);
1150             }
1151             List<HRegionInfo> regions = svrToRegions.get(e.getKey());
1152             if (regions == null) {
1153               regions = new ArrayList<HRegionInfo>();
1154               svrToRegions.put(e.getKey(), regions);
1155             }
1156             regions.add(hri);
1157           }
1158         }
1159       }
1160     }
1161 
1162     Map<ServerName, ServerLoad>
1163       onlineSvrs = serverManager.getOnlineServers();
1164     // Take care of servers w/o assignments, and remove servers in draining mode
1165     List<ServerName> drainingServers = this.serverManager.getDrainingServersList();
1166     for (Map<ServerName, List<HRegionInfo>> map: result.values()) {
1167       for (ServerName svr: onlineSvrs.keySet()) {
1168         if (!map.containsKey(svr)) {
1169           map.put(svr, new ArrayList<HRegionInfo>());
1170         }
1171       }
1172       map.keySet().removeAll(drainingServers);
1173     }
1174     return result;
1175   }
1176 
1177   protected RegionState getRegionState(final HRegionInfo hri) {
1178     return getRegionState(hri.getEncodedName());
1179   }
1180 
1181   /**
1182    * Returns a clone of region assignments per server
1183    * @return a Map of ServerName to a List of HRegionInfo's
1184    */
1185   protected synchronized Map<ServerName, List<HRegionInfo>> getRegionAssignmentsByServer() {
1186     Map<ServerName, List<HRegionInfo>> regionsByServer =
1187         new HashMap<ServerName, List<HRegionInfo>>(serverHoldings.size());
1188     for (Map.Entry<ServerName, Set<HRegionInfo>> e: serverHoldings.entrySet()) {
1189       regionsByServer.put(e.getKey(), new ArrayList<HRegionInfo>(e.getValue()));
1190     }
1191     return regionsByServer;
1192   }
1193 
1194   protected synchronized RegionState getRegionState(final String encodedName) {
1195     return regionStates.get(encodedName);
1196   }
1197 
1198   /**
1199    * Get the HRegionInfo from cache, if not there, from the hbase:meta table
1200    * @param  regionName
1201    * @return HRegionInfo for the region
1202    */
1203   @SuppressWarnings("deprecation")
1204   protected HRegionInfo getRegionInfo(final byte [] regionName) {
1205     String encodedName = HRegionInfo.encodeRegionName(regionName);
1206     RegionState regionState = getRegionState(encodedName);
1207     if (regionState != null) {
1208       return regionState.getRegion();
1209     }
1210 
1211     try {
1212       Pair<HRegionInfo, ServerName> p =
1213         MetaTableAccessor.getRegion(server.getConnection(), regionName);
1214       HRegionInfo hri = p == null ? null : p.getFirst();
1215       if (hri != null) {
1216         createRegionState(hri);
1217       }
1218       return hri;
1219     } catch (IOException e) {
1220       server.abort("Aborting because error occurred while reading "
1221         + Bytes.toStringBinary(regionName) + " from hbase:meta", e);
1222       return null;
1223     }
1224   }
1225 
1226   static boolean isOneOfStates(RegionState regionState, State... states) {
1227     State s = regionState != null ? regionState.getState() : null;
1228     for (State state: states) {
1229       if (s == state) return true;
1230     }
1231     return false;
1232   }
1233 
1234   /**
1235    * Update a region state. It will be put in transition if not already there.
1236    */
1237   private RegionState updateRegionState(final HRegionInfo hri,
1238       final State state, final ServerName serverName, long openSeqNum) {
1239     if (state == State.FAILED_CLOSE || state == State.FAILED_OPEN) {
1240       LOG.warn("Failed to open/close " + hri.getShortNameToLog()
1241         + " on " + serverName + ", set to " + state);
1242     }
1243 
1244     String encodedName = hri.getEncodedName();
1245     RegionState regionState = new RegionState(
1246       hri, state, System.currentTimeMillis(), serverName);
1247     RegionState oldState = getRegionState(encodedName);
1248     if (!regionState.equals(oldState)) {
1249       LOG.info("Transition " + oldState + " to " + regionState);
1250       // Persist region state before updating in-memory info, if needed
1251       regionStateStore.updateRegionState(openSeqNum, regionState, oldState);
1252     }
1253 
1254     synchronized (this) {
1255       RegionState oldRegionState = regionsInTransition.put(encodedName, regionState);
1256       // When region transform old region state to new region state,
1257       // accumulate the RIT duration to new region state.
1258       if (oldRegionState != null) {
1259         regionState.updateRitDuration(oldRegionState.getStamp());
1260       }
1261       putRegionState(regionState);
1262 
1263       // For these states, region should be properly closed.
1264       // There should be no log splitting issue.
1265       if ((state == State.CLOSED || state == State.MERGED
1266           || state == State.SPLIT) && lastAssignments.containsKey(encodedName)) {
1267         ServerName last = lastAssignments.get(encodedName);
1268         if (last.equals(serverName)) {
1269           lastAssignments.remove(encodedName);
1270         } else {
1271           LOG.warn(encodedName + " moved to " + state + " on "
1272             + serverName + ", expected " + last);
1273         }
1274       }
1275 
1276       // Once a region is opened, record its last assignment right away.
1277       if (serverName != null && state == State.OPEN) {
1278         ServerName last = lastAssignments.get(encodedName);
1279         if (!serverName.equals(last)) {
1280           lastAssignments.put(encodedName, serverName);
1281           if (last != null && isServerDeadAndNotProcessed(last)) {
1282             LOG.warn(encodedName + " moved to " + serverName
1283               + ", while it's previous host " + last
1284               + " is dead but not processed yet");
1285           }
1286         }
1287       }
1288 
1289       // notify the change
1290       this.notifyAll();
1291     }
1292     return regionState;
1293   }
1294 }