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.Collections;
24  import java.util.HashMap;
25  import java.util.HashSet;
26  import java.util.Iterator;
27  import java.util.List;
28  import java.util.Map;
29  import java.util.Set;
30  import java.util.TreeMap;
31  
32  import com.google.common.annotations.VisibleForTesting;
33  import com.google.common.base.Preconditions;
34  import org.apache.commons.logging.Log;
35  import org.apache.commons.logging.LogFactory;
36  import org.apache.hadoop.hbase.classification.InterfaceAudience;
37  import org.apache.hadoop.conf.Configuration;
38  import org.apache.hadoop.hbase.HConstants;
39  import org.apache.hadoop.hbase.HRegionInfo;
40  import org.apache.hadoop.hbase.MetaTableAccessor;
41  import org.apache.hadoop.hbase.Server;
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.client.RegionReplicaUtil;
46  import org.apache.hadoop.hbase.master.RegionState.State;
47  import org.apache.hadoop.hbase.client.TableState;
48  import org.apache.hadoop.hbase.util.Bytes;
49  import org.apache.hadoop.hbase.util.Pair;
50  
51  /**
52   * Region state accountant. It holds the states of all regions in the memory.
53   * In normal scenario, it should match the meta table and the true region states.
54   *
55   * This map is used by AssignmentManager to track region states.
56   */
57  @InterfaceAudience.Private
58  public class RegionStates {
59    private static final Log LOG = LogFactory.getLog(RegionStates.class);
60  
61    /**
62     * Regions currently in transition.
63     */
64    final HashMap<String, RegionState> regionsInTransition =
65      new HashMap<String, RegionState>();
66  
67    /**
68     * Region encoded name to state map.
69     * All the regions should be in this map.
70     */
71    private final Map<String, RegionState> regionStates =
72      new HashMap<String, RegionState>();
73  
74    /**
75     * Server to regions assignment map.
76     * Contains the set of regions currently assigned to a given server.
77     */
78    private final Map<ServerName, Set<HRegionInfo>> serverHoldings =
79      new HashMap<ServerName, Set<HRegionInfo>>();
80  
81    /**
82     * Maintains the mapping from the default region to the replica regions.
83     */
84    private final Map<HRegionInfo, Set<HRegionInfo>> defaultReplicaToOtherReplicas =
85      new HashMap<HRegionInfo, Set<HRegionInfo>>();
86  
87    /**
88     * Region to server assignment map.
89     * Contains the server a given region is currently assigned to.
90     */
91    private final TreeMap<HRegionInfo, ServerName> regionAssignments =
92      new TreeMap<HRegionInfo, ServerName>();
93  
94    /**
95     * Encoded region name to server assignment map for re-assignment
96     * purpose. Contains the server a given region is last known assigned
97     * to, which has not completed log splitting, so not assignable.
98     * If a region is currently assigned, this server info in this
99     * map should be the same as that in regionAssignments.
100    * However the info in regionAssignments is cleared when the region
101    * is offline while the info in lastAssignments is cleared when
102    * the region is closed or the server is dead and processed.
103    */
104   private final HashMap<String, ServerName> lastAssignments =
105     new HashMap<String, ServerName>();
106 
107   /**
108    * Encoded region name to server assignment map for the
109    * purpose to clean up serverHoldings when a region is online
110    * on a new server. When the region is offline from the previous
111    * server, we cleaned up regionAssignments so that it has the
112    * latest assignment map. But we didn't clean up serverHoldings
113    * to match the meta. We need this map to find out the old server
114    * whose serverHoldings needs cleanup, given a moved region.
115    */
116   private final HashMap<String, ServerName> oldAssignments =
117     new HashMap<String, ServerName>();
118 
119   /**
120    * Map a host port pair string to the latest start code
121    * of a region server which is known to be dead. It is dead
122    * to us, but server manager may not know it yet.
123    */
124   private final HashMap<String, Long> deadServers =
125     new HashMap<String, Long>();
126 
127   /**
128    * Map a dead servers to the time when log split is done.
129    * Since log splitting is not ordered, we have to remember
130    * all processed instances. The map is cleaned up based
131    * on a configured time. By default, we assume a dead
132    * server should be done with log splitting in two hours.
133    */
134   private final HashMap<ServerName, Long> processedServers =
135     new HashMap<ServerName, Long>();
136   private long lastProcessedServerCleanTime;
137 
138   private final TableStateManager tableStateManager;
139   private final RegionStateStore regionStateStore;
140   private final ServerManager serverManager;
141   private final Server server;
142 
143   // The maximum time to keep a log split info in region states map
144   static final String LOG_SPLIT_TIME = "hbase.master.maximum.logsplit.keeptime";
145   static final long DEFAULT_LOG_SPLIT_TIME = 7200000L; // 2 hours
146 
147   RegionStates(final Server master, final TableStateManager tableStateManager,
148       final ServerManager serverManager, final RegionStateStore regionStateStore) {
149     this.tableStateManager = tableStateManager;
150     this.regionStateStore = regionStateStore;
151     this.serverManager = serverManager;
152     this.server = master;
153   }
154 
155   /**
156    * @return an unmodifiable the region assignment map
157    */
158   public synchronized Map<HRegionInfo, ServerName> getRegionAssignments() {
159     return Collections.unmodifiableMap(regionAssignments);
160   }
161 
162   /**
163    * Return the replicas (including default) for the regions grouped by ServerName
164    * @param regions
165    * @return a pair containing the groupings as a map
166    */
167   synchronized Map<ServerName, List<HRegionInfo>> getRegionAssignments(
168     Collection<HRegionInfo> regions) {
169     Map<ServerName, List<HRegionInfo>> map = new HashMap<ServerName, List<HRegionInfo>>();
170     for (HRegionInfo region : regions) {
171       HRegionInfo defaultReplica = RegionReplicaUtil.getRegionInfoForDefaultReplica(region);
172       Set<HRegionInfo> allReplicas = defaultReplicaToOtherReplicas.get(defaultReplica);
173       if (allReplicas != null) {
174         for (HRegionInfo hri : allReplicas) {
175           ServerName server = regionAssignments.get(hri);
176           if (server != null) {
177             List<HRegionInfo> regionsOnServer = map.get(server);
178             if (regionsOnServer == null) {
179               regionsOnServer = new ArrayList<HRegionInfo>(1);
180               map.put(server, regionsOnServer);
181             }
182             regionsOnServer.add(hri);
183           }
184         }
185       }
186     }
187     return map;
188   }
189 
190   public synchronized ServerName getRegionServerOfRegion(HRegionInfo hri) {
191     return regionAssignments.get(hri);
192   }
193 
194   /**
195    * Get regions in transition and their states
196    */
197   @SuppressWarnings("unchecked")
198   public synchronized Map<String, RegionState> getRegionsInTransition() {
199     return (Map<String, RegionState>)regionsInTransition.clone();
200   }
201 
202   /**
203    * @return True if specified region in transition.
204    */
205   public synchronized boolean isRegionInTransition(final HRegionInfo hri) {
206     return regionsInTransition.containsKey(hri.getEncodedName());
207   }
208 
209   /**
210    * @return True if specified region in transition.
211    */
212   public synchronized boolean isRegionInTransition(final String encodedName) {
213     return regionsInTransition.containsKey(encodedName);
214   }
215 
216   /**
217    * @return True if any region in transition.
218    */
219   public synchronized boolean isRegionsInTransition() {
220     return !regionsInTransition.isEmpty();
221   }
222 
223   /**
224    * @return True if specified region assigned, and not in transition.
225    */
226   public synchronized boolean isRegionOnline(final HRegionInfo hri) {
227     return !isRegionInTransition(hri) && regionAssignments.containsKey(hri);
228   }
229 
230   /**
231    * @return True if specified region offline/closed, but not in transition.
232    * If the region is not in the map, it is offline to us too.
233    */
234   public synchronized boolean isRegionOffline(final HRegionInfo hri) {
235     return getRegionState(hri) == null || (!isRegionInTransition(hri)
236       && isRegionInState(hri, State.OFFLINE, State.CLOSED));
237   }
238 
239   /**
240    * @return True if specified region is in one of the specified states.
241    */
242   public boolean isRegionInState(
243       final HRegionInfo hri, final State... states) {
244     return isRegionInState(hri.getEncodedName(), states);
245   }
246 
247   /**
248    * @return True if specified region is in one of the specified states.
249    */
250   public boolean isRegionInState(
251       final String encodedName, final State... states) {
252     RegionState regionState = getRegionState(encodedName);
253     return isOneOfStates(regionState, states);
254   }
255 
256   /**
257    * Wait for the state map to be updated by assignment manager.
258    */
259   public synchronized void waitForUpdate(
260       final long timeout) throws InterruptedException {
261     this.wait(timeout);
262   }
263 
264   /**
265    * Get region transition state
266    */
267   public RegionState getRegionTransitionState(final HRegionInfo hri) {
268     return getRegionTransitionState(hri.getEncodedName());
269   }
270 
271   /**
272    * Get region transition state
273    */
274   public synchronized RegionState
275       getRegionTransitionState(final String encodedName) {
276     return regionsInTransition.get(encodedName);
277   }
278 
279   /**
280    * Add a list of regions to RegionStates. If a region is split
281    * and offline, its state will be SPLIT. Otherwise, its state will
282    * be OFFLINE. Region already in RegionStates will be skipped.
283    */
284   public void createRegionStates(
285       final List<HRegionInfo> hris) {
286     for (HRegionInfo hri: hris) {
287       createRegionState(hri);
288     }
289   }
290 
291   /**
292    * Add a region to RegionStates. If the region is split
293    * and offline, its state will be SPLIT. Otherwise, its state will
294    * be OFFLINE. If it is already in RegionStates, this call has
295    * no effect, and the original state is returned.
296    */
297   public RegionState createRegionState(final HRegionInfo hri) {
298     return createRegionState(hri, null, null, null);
299   }
300 
301   /**
302    * Add a region to RegionStates with the specified state.
303    * If the region is already in RegionStates, this call has
304    * no effect, and the original state is returned.
305    *
306    * @param hri the region info to create a state for
307    * @param newState the state to the region in set to
308    * @param serverName the server the region is transitioning on
309    * @param lastHost the last server that hosts the region
310    * @return the current state
311    */
312   public synchronized RegionState createRegionState(final HRegionInfo hri,
313       State newState, ServerName serverName, ServerName lastHost) {
314     if (newState == null || (newState == State.OPEN && serverName == null)) {
315       newState =  State.OFFLINE;
316     }
317     if (hri.isOffline() && hri.isSplit()) {
318       newState = State.SPLIT;
319       serverName = null;
320     }
321     String encodedName = hri.getEncodedName();
322     RegionState regionState = regionStates.get(encodedName);
323     if (regionState != null) {
324       LOG.warn("Tried to create a state for a region already in RegionStates, "
325         + "used existing: " + regionState + ", ignored new: " + newState);
326     } else {
327       regionState = new RegionState(hri, newState, serverName);
328       regionStates.put(encodedName, regionState);
329       if (newState == State.OPEN) {
330         if (!serverName.equals(lastHost)) {
331           LOG.warn("Open region's last host " + lastHost
332             + " should be the same as the current one " + serverName
333             + ", ignored the last and used the current one");
334           lastHost = serverName;
335         }
336         lastAssignments.put(encodedName, lastHost);
337         regionAssignments.put(hri, lastHost);
338       } else if (!isOneOfStates(regionState, State.MERGED, State.SPLIT, State.OFFLINE)) {
339         regionsInTransition.put(encodedName, regionState);
340       }
341       if (lastHost != null && newState != State.SPLIT) {
342         addToServerHoldings(lastHost, hri);
343         if (newState != State.OPEN) {
344           oldAssignments.put(encodedName, lastHost);
345         }
346       }
347     }
348     return regionState;
349   }
350 
351   /**
352    * Update a region state. It will be put in transition if not already there.
353    */
354   public RegionState updateRegionState(
355       final HRegionInfo hri, final State state) {
356     RegionState regionState = getRegionState(hri.getEncodedName());
357     return updateRegionState(hri, state,
358       regionState == null ? null : regionState.getServerName());
359   }
360 
361   /**
362    * Update a region state. It will be put in transition if not already there.
363    */
364   public RegionState updateRegionState(
365       final HRegionInfo hri, final State state, final ServerName serverName) {
366     return updateRegionState(hri, state, serverName, HConstants.NO_SEQNUM);
367   }
368 
369   public void regionOnline(
370       final HRegionInfo hri, final ServerName serverName) {
371     regionOnline(hri, serverName, HConstants.NO_SEQNUM);
372   }
373 
374   /**
375    * A region is online, won't be in transition any more.
376    * We can't confirm it is really online on specified region server
377    * because it hasn't been put in region server's online region list yet.
378    */
379   public void regionOnline(final HRegionInfo hri,
380       final ServerName serverName, long openSeqNum) {
381     String encodedName = hri.getEncodedName();
382     if (!serverManager.isServerOnline(serverName)) {
383       // This is possible if the region server dies before master gets a
384       // chance to handle ZK event in time. At this time, if the dead server
385       // is already processed by SSH, we should ignore this event.
386       // If not processed yet, ignore and let SSH deal with it.
387       LOG.warn("Ignored, " + encodedName
388         + " was opened on a dead server: " + serverName);
389       return;
390     }
391     updateRegionState(hri, State.OPEN, serverName, openSeqNum);
392 
393     synchronized (this) {
394       regionsInTransition.remove(encodedName);
395       ServerName oldServerName = regionAssignments.put(hri, serverName);
396       if (!serverName.equals(oldServerName)) {
397         LOG.info("Onlined " + hri.getShortNameToLog() + " on " + serverName);
398         addToServerHoldings(serverName, hri);
399         addToReplicaMapping(hri);
400         if (oldServerName == null) {
401           oldServerName = oldAssignments.remove(encodedName);
402         }
403         if (oldServerName != null && serverHoldings.containsKey(oldServerName)) {
404           LOG.info("Offlined " + hri.getShortNameToLog() + " from " + oldServerName);
405           removeFromServerHoldings(oldServerName, hri);
406         }
407       }
408     }
409   }
410 
411   private void addToServerHoldings(ServerName serverName, HRegionInfo hri) {
412     Set<HRegionInfo> regions = serverHoldings.get(serverName);
413     if (regions == null) {
414       regions = new HashSet<HRegionInfo>();
415       serverHoldings.put(serverName, regions);
416     }
417     regions.add(hri);
418   }
419 
420   private void addToReplicaMapping(HRegionInfo hri) {
421     HRegionInfo defaultReplica = RegionReplicaUtil.getRegionInfoForDefaultReplica(hri);
422     Set<HRegionInfo> replicas =
423         defaultReplicaToOtherReplicas.get(defaultReplica);
424     if (replicas == null) {
425       replicas = new HashSet<HRegionInfo>();
426       defaultReplicaToOtherReplicas.put(defaultReplica, replicas);
427     }
428     replicas.add(hri);
429   }
430 
431   private void removeFromServerHoldings(ServerName serverName, HRegionInfo hri) {
432     Set<HRegionInfo> oldRegions = serverHoldings.get(serverName);
433     oldRegions.remove(hri);
434     if (oldRegions.isEmpty()) {
435       serverHoldings.remove(serverName);
436     }
437   }
438 
439   private void removeFromReplicaMapping(HRegionInfo hri) {
440     HRegionInfo defaultReplica = RegionReplicaUtil.getRegionInfoForDefaultReplica(hri);
441     Set<HRegionInfo> replicas = defaultReplicaToOtherReplicas.get(defaultReplica);
442     if (replicas != null) {
443       replicas.remove(hri);
444       if (replicas.isEmpty()) {
445         defaultReplicaToOtherReplicas.remove(defaultReplica);
446       }
447     }
448   }
449 
450   /**
451    * A dead server's wals have been split so that all the regions
452    * used to be open on it can be safely assigned now. Mark them assignable.
453    */
454   public synchronized void logSplit(final ServerName serverName) {
455     for (Iterator<Map.Entry<String, ServerName>> it
456         = lastAssignments.entrySet().iterator(); it.hasNext();) {
457       Map.Entry<String, ServerName> e = it.next();
458       if (e.getValue().equals(serverName)) {
459         it.remove();
460       }
461     }
462     long now = System.currentTimeMillis();
463     if (LOG.isDebugEnabled()) {
464       LOG.debug("Adding to processed servers " + serverName);
465     }
466     processedServers.put(serverName, Long.valueOf(now));
467     Configuration conf = server.getConfiguration();
468     long obsoleteTime = conf.getLong(LOG_SPLIT_TIME, DEFAULT_LOG_SPLIT_TIME);
469     // Doesn't have to be very accurate about the clean up time
470     if (now > lastProcessedServerCleanTime + obsoleteTime) {
471       lastProcessedServerCleanTime = now;
472       long cutoff = now - obsoleteTime;
473       for (Iterator<Map.Entry<ServerName, Long>> it
474           = processedServers.entrySet().iterator(); it.hasNext();) {
475         Map.Entry<ServerName, Long> e = it.next();
476         if (e.getValue().longValue() < cutoff) {
477           if (LOG.isDebugEnabled()) {
478             LOG.debug("Removed from processed servers " + e.getKey());
479           }
480           it.remove();
481         }
482       }
483     }
484   }
485 
486   /**
487    * Log split is done for a given region, so it is assignable now.
488    */
489   public void logSplit(final HRegionInfo region) {
490     clearLastAssignment(region);
491   }
492 
493   public synchronized void clearLastAssignment(final HRegionInfo region) {
494     lastAssignments.remove(region.getEncodedName());
495   }
496 
497   /**
498    * A region is offline, won't be in transition any more.
499    */
500   public void regionOffline(final HRegionInfo hri) {
501     regionOffline(hri, null);
502   }
503 
504   /**
505    * A region is offline, won't be in transition any more. Its state
506    * should be the specified expected state, which can only be
507    * Split/Merged/Offline/null(=Offline)/SplittingNew/MergingNew.
508    */
509   public void regionOffline(
510       final HRegionInfo hri, final State expectedState) {
511     Preconditions.checkArgument(expectedState == null
512       || RegionState.isUnassignable(expectedState),
513         "Offlined region should not be " + expectedState);
514     if (isRegionInState(hri, State.SPLITTING_NEW, State.MERGING_NEW)) {
515       // Remove it from all region maps
516       deleteRegion(hri);
517       return;
518     }
519     State newState =
520       expectedState == null ? State.OFFLINE : expectedState;
521     updateRegionState(hri, newState);
522     String encodedName = hri.getEncodedName();
523     synchronized (this) {
524       regionsInTransition.remove(encodedName);
525       ServerName oldServerName = regionAssignments.remove(hri);
526       if (oldServerName != null && serverHoldings.containsKey(oldServerName)) {
527         if (newState == State.MERGED || newState == State.SPLIT
528             || hri.isMetaRegion() || tableStateManager.isTableState(hri.getTable(),
529               TableState.State.DISABLED, TableState.State.DISABLING)) {
530           // Offline the region only if it's merged/split, or the table is disabled/disabling.
531           // Otherwise, offline it from this server only when it is online on a different server.
532           LOG.info("Offlined " + hri.getShortNameToLog() + " from " + oldServerName);
533           removeFromServerHoldings(oldServerName, hri);
534           removeFromReplicaMapping(hri);
535         } else {
536           // Need to remember it so that we can offline it from this
537           // server when it is online on a different server.
538           oldAssignments.put(encodedName, oldServerName);
539         }
540       }
541     }
542   }
543 
544   /**
545    * A server is offline, all regions on it are dead.
546    */
547   public synchronized List<HRegionInfo> serverOffline(final ServerName sn) {
548     // Offline all regions on this server not already in transition.
549     List<HRegionInfo> rits = new ArrayList<HRegionInfo>();
550     Set<HRegionInfo> assignedRegions = serverHoldings.get(sn);
551     if (assignedRegions == null) {
552       assignedRegions = new HashSet<HRegionInfo>();
553     }
554 
555     // Offline regions outside the loop to avoid ConcurrentModificationException
556     Set<HRegionInfo> regionsToOffline = new HashSet<HRegionInfo>();
557     for (HRegionInfo region : assignedRegions) {
558       // Offline open regions, no need to offline if SPLIT/MERGED/OFFLINE
559       if (isRegionOnline(region)) {
560         regionsToOffline.add(region);
561       } else if (isRegionInState(region, State.SPLITTING, State.MERGING)) {
562         LOG.debug("Offline splitting/merging region " + getRegionState(region));
563         regionsToOffline.add(region);
564       }
565     }
566 
567     for (HRegionInfo hri : regionsToOffline) {
568       regionOffline(hri);
569     }
570 
571     for (RegionState state : regionsInTransition.values()) {
572       HRegionInfo hri = state.getRegion();
573       if (assignedRegions.contains(hri)) {
574         // Region is open on this region server, but in transition.
575         // This region must be moving away from this server, or splitting/merging.
576         // SSH will handle it, either skip assigning, or re-assign.
577         LOG.info("Transitioning " + state + " will be handled by SSH for " + sn);
578       } else if (sn.equals(state.getServerName())) {
579         // Region is in transition on this region server, and this
580         // region is not open on this server. So the region must be
581         // moving to this server from another one (i.e. opening or
582         // pending open on this server, was open on another one.
583         // Offline state is also kind of pending open if the region is in
584         // transition. The region could be in failed_close state too if we have
585         // tried several times to open it while this region server is not reachable)
586         if (isOneOfStates(state, State.OPENING, State.PENDING_OPEN,
587             State.FAILED_OPEN, State.FAILED_CLOSE, State.OFFLINE)) {
588           LOG.info("Found region in " + state + " to be reassigned by SSH for " + sn);
589           rits.add(hri);
590         } else {
591           LOG.warn("THIS SHOULD NOT HAPPEN: unexpected " + state);
592         }
593       }
594     }
595 
596     this.notifyAll();
597     return rits;
598   }
599 
600   /**
601    * Gets the online regions of the specified table.
602    * This method looks at the in-memory state.  It does not go to <code>hbase:meta</code>.
603    * Only returns <em>online</em> regions.  If a region on this table has been
604    * closed during a disable, etc., it will be included in the returned list.
605    * So, the returned list may not necessarily be ALL regions in this table, its
606    * all the ONLINE regions in the table.
607    * @param tableName
608    * @return Online regions from <code>tableName</code>
609    */
610   public synchronized List<HRegionInfo> getRegionsOfTable(TableName tableName) {
611     List<HRegionInfo> tableRegions = new ArrayList<HRegionInfo>();
612     // boundary needs to have table's name but regionID 0 so that it is sorted
613     // before all table's regions.
614     HRegionInfo boundary = new HRegionInfo(tableName, null, null, false, 0L);
615     for (HRegionInfo hri: regionAssignments.tailMap(boundary).keySet()) {
616       if(!hri.getTable().equals(tableName)) break;
617       tableRegions.add(hri);
618     }
619     return tableRegions;
620   }
621 
622 
623   /**
624    * Wait on region to clear regions-in-transition.
625    * <p>
626    * If the region isn't in transition, returns immediately.  Otherwise, method
627    * blocks until the region is out of transition.
628    */
629   public synchronized void waitOnRegionToClearRegionsInTransition(
630       final HRegionInfo hri) throws InterruptedException {
631     if (!isRegionInTransition(hri)) return;
632 
633     while(!server.isStopped() && isRegionInTransition(hri)) {
634       RegionState rs = getRegionState(hri);
635       LOG.info("Waiting on " + rs + " to clear regions-in-transition");
636       waitForUpdate(100);
637     }
638 
639     if (server.isStopped()) {
640       LOG.info("Giving up wait on region in " +
641         "transition because stoppable.isStopped is set");
642     }
643   }
644 
645   /**
646    * A table is deleted. Remove its regions from all internal maps.
647    * We loop through all regions assuming we don't delete tables too much.
648    */
649   public void tableDeleted(final TableName tableName) {
650     Set<HRegionInfo> regionsToDelete = new HashSet<HRegionInfo>();
651     synchronized (this) {
652       for (RegionState state: regionStates.values()) {
653         HRegionInfo region = state.getRegion();
654         if (region.getTable().equals(tableName)) {
655           regionsToDelete.add(region);
656         }
657       }
658     }
659     for (HRegionInfo region: regionsToDelete) {
660       deleteRegion(region);
661     }
662   }
663 
664   /**
665    * Get a copy of all regions assigned to a server
666    */
667   public synchronized Set<HRegionInfo> getServerRegions(ServerName serverName) {
668     Set<HRegionInfo> regions = serverHoldings.get(serverName);
669     if (regions == null) return null;
670     return new HashSet<HRegionInfo>(regions);
671   }
672 
673   /**
674    * Remove a region from all state maps.
675    */
676   @VisibleForTesting
677   public synchronized void deleteRegion(final HRegionInfo hri) {
678     String encodedName = hri.getEncodedName();
679     regionsInTransition.remove(encodedName);
680     regionStates.remove(encodedName);
681     lastAssignments.remove(encodedName);
682     ServerName sn = regionAssignments.remove(hri);
683     if (sn != null) {
684       Set<HRegionInfo> regions = serverHoldings.get(sn);
685       regions.remove(hri);
686     }
687   }
688 
689   /**
690    * Checking if a region was assigned to a server which is not online now.
691    * If so, we should hold re-assign this region till SSH has split its wals.
692    * Once logs are split, the last assignment of this region will be reset,
693    * which means a null last assignment server is ok for re-assigning.
694    *
695    * A region server could be dead but we don't know it yet. We may
696    * think it's online falsely. Therefore if a server is online, we still
697    * need to confirm it reachable and having the expected start code.
698    */
699   synchronized boolean wasRegionOnDeadServer(final String encodedName) {
700     ServerName server = lastAssignments.get(encodedName);
701     return isServerDeadAndNotProcessed(server);
702   }
703 
704   synchronized boolean isServerDeadAndNotProcessed(ServerName server) {
705     if (server == null) return false;
706     if (serverManager.isServerOnline(server)) {
707       String hostAndPort = server.getHostAndPort();
708       long startCode = server.getStartcode();
709       Long deadCode = deadServers.get(hostAndPort);
710       if (deadCode == null || startCode > deadCode.longValue()) {
711         if (serverManager.isServerReachable(server)) {
712           return false;
713         }
714         // The size of deadServers won't grow unbounded.
715         deadServers.put(hostAndPort, Long.valueOf(startCode));
716       }
717       // Watch out! If the server is not dead, the region could
718       // remain unassigned. That's why ServerManager#isServerReachable
719       // should use some retry.
720       //
721       // We cache this info since it is very unlikely for that
722       // instance to come back up later on. We don't want to expire
723       // the server since we prefer to let it die naturally.
724       LOG.warn("Couldn't reach online server " + server);
725     }
726     // Now, we know it's dead. Check if it's processed
727     return !processedServers.containsKey(server);
728   }
729 
730  /**
731    * Get the last region server a region was on for purpose of re-assignment,
732    * i.e. should the re-assignment be held back till log split is done?
733    */
734   synchronized ServerName getLastRegionServerOfRegion(final String encodedName) {
735     return lastAssignments.get(encodedName);
736   }
737 
738   synchronized void setLastRegionServerOfRegions(
739       final ServerName serverName, final List<HRegionInfo> regionInfos) {
740     for (HRegionInfo hri: regionInfos) {
741       setLastRegionServerOfRegion(serverName, hri.getEncodedName());
742     }
743   }
744 
745   synchronized void setLastRegionServerOfRegion(
746       final ServerName serverName, final String encodedName) {
747     lastAssignments.put(encodedName, serverName);
748   }
749 
750   synchronized boolean isRegionOnServer(
751       final HRegionInfo hri, final ServerName serverName) {
752     Set<HRegionInfo> regions = serverHoldings.get(serverName);
753     return regions == null ? false : regions.contains(hri);
754   }
755 
756   void splitRegion(HRegionInfo p,
757       HRegionInfo a, HRegionInfo b, ServerName sn) throws IOException {
758     regionStateStore.splitRegion(p, a, b, sn);
759     synchronized (this) {
760       // After PONR, split is considered to be done.
761       // Update server holdings to be aligned with the meta.
762       Set<HRegionInfo> regions = serverHoldings.get(sn);
763       if (regions == null) {
764         throw new IllegalStateException(sn + " should host some regions");
765       }
766       regions.remove(p);
767       regions.add(a);
768       regions.add(b);
769     }
770   }
771 
772   void mergeRegions(HRegionInfo p,
773       HRegionInfo a, HRegionInfo b, ServerName sn) throws IOException {
774     regionStateStore.mergeRegions(p, a, b, sn);
775     synchronized (this) {
776       // After PONR, merge is considered to be done.
777       // Update server holdings to be aligned with the meta.
778       Set<HRegionInfo> regions = serverHoldings.get(sn);
779       if (regions == null) {
780         throw new IllegalStateException(sn + " should host some regions");
781       }
782       regions.remove(a);
783       regions.remove(b);
784       regions.add(p);
785     }
786   }
787 
788   /**
789    * At cluster clean re/start, mark all user regions closed except those of tables
790    * that are excluded, such as disabled/disabling/enabling tables. All user regions
791    * and their previous locations are returned.
792    */
793   synchronized Map<HRegionInfo, ServerName> closeAllUserRegions(Set<TableName> excludedTables) {
794     boolean noExcludeTables = excludedTables == null || excludedTables.isEmpty();
795     Set<HRegionInfo> toBeClosed = new HashSet<HRegionInfo>(regionStates.size());
796     for(RegionState state: regionStates.values()) {
797       HRegionInfo hri = state.getRegion();
798       if (state.isSplit() || hri.isSplit()) {
799         continue;
800       }
801       TableName tableName = hri.getTable();
802       if (!TableName.META_TABLE_NAME.equals(tableName)
803           && (noExcludeTables || !excludedTables.contains(tableName))) {
804         toBeClosed.add(hri);
805       }
806     }
807     Map<HRegionInfo, ServerName> allUserRegions =
808       new HashMap<HRegionInfo, ServerName>(toBeClosed.size());
809     for (HRegionInfo hri: toBeClosed) {
810       RegionState regionState = updateRegionState(hri, State.CLOSED);
811       allUserRegions.put(hri, regionState.getServerName());
812     }
813     return allUserRegions;
814   }
815 
816   /**
817    * Compute the average load across all region servers.
818    * Currently, this uses a very naive computation - just uses the number of
819    * regions being served, ignoring stats about number of requests.
820    * @return the average load
821    */
822   protected synchronized double getAverageLoad() {
823     int numServers = 0, totalLoad = 0;
824     for (Map.Entry<ServerName, Set<HRegionInfo>> e: serverHoldings.entrySet()) {
825       Set<HRegionInfo> regions = e.getValue();
826       ServerName serverName = e.getKey();
827       int regionCount = regions.size();
828       if (serverManager.isServerOnline(serverName)) {
829         totalLoad += regionCount;
830         numServers++;
831       }
832     }
833     if (numServers > 1) {
834       // The master region server holds only a couple regions.
835       // Don't consider this server in calculating the average load
836       // if there are other region servers to avoid possible confusion.
837       Set<HRegionInfo> hris = serverHoldings.get(server.getServerName());
838       if (hris != null) {
839         totalLoad -= hris.size();
840         numServers--;
841       }
842     }
843     return numServers == 0 ? 0.0 :
844       (double)totalLoad / (double)numServers;
845   }
846 
847   /**
848    * This is an EXPENSIVE clone.  Cloning though is the safest thing to do.
849    * Can't let out original since it can change and at least the load balancer
850    * wants to iterate this exported list.  We need to synchronize on regions
851    * since all access to this.servers is under a lock on this.regions.
852    *
853    * @return A clone of current assignments by table.
854    */
855   protected Map<TableName, Map<ServerName, List<HRegionInfo>>>
856       getAssignmentsByTable() {
857     Map<TableName, Map<ServerName, List<HRegionInfo>>> result =
858       new HashMap<TableName, Map<ServerName,List<HRegionInfo>>>();
859     synchronized (this) {
860       if (!server.getConfiguration().getBoolean("hbase.master.loadbalance.bytable", false)) {
861         Map<ServerName, List<HRegionInfo>> svrToRegions =
862           new HashMap<ServerName, List<HRegionInfo>>(serverHoldings.size());
863         for (Map.Entry<ServerName, Set<HRegionInfo>> e: serverHoldings.entrySet()) {
864           svrToRegions.put(e.getKey(), new ArrayList<HRegionInfo>(e.getValue()));
865         }
866         result.put(TableName.valueOf("ensemble"), svrToRegions);
867       } else {
868         for (Map.Entry<ServerName, Set<HRegionInfo>> e: serverHoldings.entrySet()) {
869           for (HRegionInfo hri: e.getValue()) {
870             if (hri.isMetaRegion()) continue;
871             TableName tablename = hri.getTable();
872             Map<ServerName, List<HRegionInfo>> svrToRegions = result.get(tablename);
873             if (svrToRegions == null) {
874               svrToRegions = new HashMap<ServerName, List<HRegionInfo>>(serverHoldings.size());
875               result.put(tablename, svrToRegions);
876             }
877             List<HRegionInfo> regions = svrToRegions.get(e.getKey());
878             if (regions == null) {
879               regions = new ArrayList<HRegionInfo>();
880               svrToRegions.put(e.getKey(), regions);
881             }
882             regions.add(hri);
883           }
884         }
885       }
886     }
887 
888     Map<ServerName, ServerLoad>
889       onlineSvrs = serverManager.getOnlineServers();
890     // Take care of servers w/o assignments.
891     for (Map<ServerName, List<HRegionInfo>> map: result.values()) {
892       for (ServerName svr: onlineSvrs.keySet()) {
893         if (!map.containsKey(svr)) {
894           map.put(svr, new ArrayList<HRegionInfo>());
895         }
896       }
897     }
898     return result;
899   }
900 
901   protected RegionState getRegionState(final HRegionInfo hri) {
902     return getRegionState(hri.getEncodedName());
903   }
904 
905   /**
906    * Returns a clone of region assignments per server
907    * @return a Map of ServerName to a List of HRegionInfo's
908    */
909   protected synchronized Map<ServerName, List<HRegionInfo>> getRegionAssignmentsByServer() {
910     Map<ServerName, List<HRegionInfo>> regionsByServer =
911         new HashMap<ServerName, List<HRegionInfo>>(serverHoldings.size());
912     for (Map.Entry<ServerName, Set<HRegionInfo>> e: serverHoldings.entrySet()) {
913       regionsByServer.put(e.getKey(), new ArrayList<HRegionInfo>(e.getValue()));
914     }
915     return regionsByServer;
916   }
917 
918   protected synchronized RegionState getRegionState(final String encodedName) {
919     return regionStates.get(encodedName);
920   }
921 
922   /**
923    * Get the HRegionInfo from cache, if not there, from the hbase:meta table
924    * @param  regionName
925    * @return HRegionInfo for the region
926    */
927   @SuppressWarnings("deprecation")
928   protected HRegionInfo getRegionInfo(final byte [] regionName) {
929     String encodedName = HRegionInfo.encodeRegionName(regionName);
930     RegionState regionState = getRegionState(encodedName);
931     if (regionState != null) {
932       return regionState.getRegion();
933     }
934 
935     try {
936       Pair<HRegionInfo, ServerName> p =
937         MetaTableAccessor.getRegion(server.getShortCircuitConnection(), regionName);
938       HRegionInfo hri = p == null ? null : p.getFirst();
939       if (hri != null) {
940         createRegionState(hri);
941       }
942       return hri;
943     } catch (IOException e) {
944       server.abort("Aborting because error occoured while reading "
945         + Bytes.toStringBinary(regionName) + " from hbase:meta", e);
946       return null;
947     }
948   }
949 
950   static boolean isOneOfStates(RegionState regionState, State... states) {
951     State s = regionState != null ? regionState.getState() : null;
952     for (State state: states) {
953       if (s == state) return true;
954     }
955     return false;
956   }
957 
958   /**
959    * Update a region state. It will be put in transition if not already there.
960    */
961   private RegionState updateRegionState(final HRegionInfo hri,
962       final RegionState.State state, final ServerName serverName, long openSeqNum) {
963     if (state == RegionState.State.FAILED_CLOSE || state == RegionState.State.FAILED_OPEN) {
964       LOG.warn("Failed to open/close " + hri.getShortNameToLog()
965         + " on " + serverName + ", set to " + state);
966     }
967 
968     String encodedName = hri.getEncodedName();
969     RegionState regionState = new RegionState(
970       hri, state, System.currentTimeMillis(), serverName);
971     RegionState oldState = getRegionState(encodedName);
972     if (!regionState.equals(oldState)) {
973       LOG.info("Transition " + oldState + " to " + regionState);
974       // Persist region state before updating in-memory info, if needed
975       regionStateStore.updateRegionState(openSeqNum, regionState, oldState);
976     }
977 
978     synchronized (this) {
979       regionsInTransition.put(encodedName, regionState);
980       regionStates.put(encodedName, regionState);
981 
982       // For these states, region should be properly closed.
983       // There should be no log splitting issue.
984       if ((state == State.CLOSED || state == State.MERGED
985           || state == State.SPLIT) && lastAssignments.containsKey(encodedName)) {
986         ServerName last = lastAssignments.get(encodedName);
987         if (last.equals(serverName)) {
988           lastAssignments.remove(encodedName);
989         } else {
990           LOG.warn(encodedName + " moved to " + state + " on "
991             + serverName + ", expected " + last);
992         }
993       }
994 
995       // Once a region is opened, record its last assignment right away.
996       if (serverName != null && state == State.OPEN) {
997         ServerName last = lastAssignments.get(encodedName);
998         if (!serverName.equals(last)) {
999           lastAssignments.put(encodedName, serverName);
1000           if (last != null && isServerDeadAndNotProcessed(last)) {
1001             LOG.warn(encodedName + " moved to " + serverName
1002               + ", while it's previous host " + last
1003               + " is dead but not processed yet");
1004           }
1005         }
1006       }
1007 
1008       // notify the change
1009       this.notifyAll();
1010     }
1011     return regionState;
1012   }
1013 }