View Javadoc

1   /**
2    * Copyright 2010 The Apache Software Foundation
3    *
4    * Licensed to the Apache Software Foundation (ASF) under one
5    * or more contributor license agreements.  See the NOTICE file
6    * distributed with this work for additional information
7    * regarding copyright ownership.  The ASF licenses this file
8    * to you under the Apache License, Version 2.0 (the
9    * "License"); you may not use this file except in compliance
10   * with the License.  You may obtain a copy of the License at
11   *
12   *     http://www.apache.org/licenses/LICENSE-2.0
13   *
14   * Unless required by applicable law or agreed to in writing, software
15   * distributed under the License is distributed on an "AS IS" BASIS,
16   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17   * See the License for the specific language governing permissions and
18   * limitations under the License.
19   */
20  package org.apache.hadoop.hbase.master.handler;
21  
22  import java.io.IOException;
23  import java.util.ArrayList;
24  import java.util.List;
25  import java.util.Map;
26  import java.util.NavigableMap;
27  import java.util.Set;
28  
29  import org.apache.commons.logging.Log;
30  import org.apache.commons.logging.LogFactory;
31  import org.apache.hadoop.hbase.HConstants;
32  import org.apache.hadoop.hbase.HRegionInfo;
33  import org.apache.hadoop.hbase.Server;
34  import org.apache.hadoop.hbase.ServerName;
35  import org.apache.hadoop.hbase.catalog.CatalogTracker;
36  import org.apache.hadoop.hbase.catalog.MetaEditor;
37  import org.apache.hadoop.hbase.catalog.MetaReader;
38  import org.apache.hadoop.hbase.client.Result;
39  import org.apache.hadoop.hbase.executor.EventHandler;
40  import org.apache.hadoop.hbase.master.AssignmentManager;
41  import org.apache.hadoop.hbase.master.AssignmentManager.RegionState;
42  import org.apache.hadoop.hbase.master.DeadServer;
43  import org.apache.hadoop.hbase.master.MasterServices;
44  import org.apache.hadoop.hbase.master.ServerManager;
45  import org.apache.hadoop.hbase.util.Bytes;
46  import org.apache.hadoop.hbase.util.Pair;
47  import org.apache.hadoop.hbase.zookeeper.ZKAssign;
48  import org.apache.zookeeper.KeeperException;
49  
50  /**
51   * Process server shutdown.
52   * Server-to-handle must be already in the deadservers lists.  See
53   * {@link ServerManager#expireServer(ServerName)}
54   */
55  public class ServerShutdownHandler extends EventHandler {
56    private static final Log LOG = LogFactory.getLog(ServerShutdownHandler.class);
57    protected final ServerName serverName;
58    protected final MasterServices services;
59    protected final DeadServer deadServers;
60    protected final boolean shouldSplitHlog; // whether to split HLog or not
61  
62    public ServerShutdownHandler(final Server server, final MasterServices services,
63        final DeadServer deadServers, final ServerName serverName,
64        final boolean shouldSplitHlog) {
65      this(server, services, deadServers, serverName, EventType.M_SERVER_SHUTDOWN,
66          shouldSplitHlog);
67    }
68  
69    ServerShutdownHandler(final Server server, final MasterServices services,
70        final DeadServer deadServers, final ServerName serverName, EventType type,
71        final boolean shouldSplitHlog) {
72      super(server, type);
73      this.serverName = serverName;
74      this.server = server;
75      this.services = services;
76      this.deadServers = deadServers;
77      if (!this.deadServers.contains(this.serverName)) {
78        LOG.warn(this.serverName + " is NOT in deadservers; it should be!");
79      }
80      this.shouldSplitHlog = shouldSplitHlog;
81    }
82  
83    @Override
84    public String getInformativeName() {
85      if (serverName != null) {
86        return this.getClass().getSimpleName() + " for " + serverName;
87      } else {
88        return super.getInformativeName();
89      }
90    }
91    
92    /**
93     * @return True if the server we are processing was carrying <code>-ROOT-</code>
94     */
95    boolean isCarryingRoot() {
96      return false;
97    }
98  
99    /**
100    * @return True if the server we are processing was carrying <code>.META.</code>
101    */
102   boolean isCarryingMeta() {
103     return false;
104   }
105 
106   @Override
107   public String toString() {
108     String name = "UnknownServerName";
109     if(server != null && server.getServerName() != null) {
110       name = server.getServerName().toString();
111     }
112     return getClass().getSimpleName() + "-" + name + "-" + getSeqid();
113   }
114 
115   @Override
116   public void process() throws IOException {
117     final ServerName serverName = this.serverName;
118     try {
119       try {
120         if (this.shouldSplitHlog) {
121           LOG.info("Splitting logs for " + serverName);
122           this.services.getMasterFileSystem().splitLog(serverName);
123         } else {
124           LOG.info("Skipping log splitting for " + serverName);
125         }
126       } catch (IOException ioe) {
127         //typecast to SSH so that we make sure that it is the SSH instance that
128         //gets submitted as opposed to MSSH or some other derived instance of SSH
129         this.services.getExecutorService().submit((ServerShutdownHandler)this);
130         this.deadServers.add(serverName);
131         throw new IOException("failed log splitting for " +
132           serverName + ", will retry", ioe);
133       }
134 
135       // We don't want worker thread in the MetaServerShutdownHandler
136       // executor pool to block by waiting availability of -ROOT-
137       // and .META. server. Otherwise, it could run into the following issue:
138       // 1. The current MetaServerShutdownHandler instance For RS1 waits for the .META.
139       //    to come online.
140       // 2. The newly assigned .META. region server RS2 was shutdown right after
141       //    it opens the .META. region. So the MetaServerShutdownHandler
142       //    instance For RS1 will still be blocked.
143       // 3. The new instance of MetaServerShutdownHandler for RS2 is queued.
144       // 4. The newly assigned .META. region server RS3 was shutdown right after
145       //    it opens the .META. region. So the MetaServerShutdownHandler
146       //    instance For RS1 and RS2 will still be blocked.
147       // 5. The new instance of MetaServerShutdownHandler for RS3 is queued.
148       // 6. Repeat until we run out of MetaServerShutdownHandler worker threads
149       // The solution here is to resubmit a ServerShutdownHandler request to process
150       // user regions on that server so that MetaServerShutdownHandler
151       // executor pool is always available.
152       if (isCarryingRoot() || isCarryingMeta()) { // -ROOT- or .META.
153         this.services.getExecutorService().submit(new ServerShutdownHandler(
154           this.server, this.services, this.deadServers, serverName, false));
155         this.deadServers.add(serverName);
156         return;
157       }
158 
159 
160       // Wait on meta to come online; we need it to progress.
161       // TODO: Best way to hold strictly here?  We should build this retry logic
162       // into the MetaReader operations themselves.
163       // TODO: Is the reading of .META. necessary when the Master has state of
164       // cluster in its head?  It should be possible to do without reading .META.
165       // in all but one case. On split, the RS updates the .META.
166       // table and THEN informs the master of the split via zk nodes in
167       // 'unassigned' dir.  Currently the RS puts ephemeral nodes into zk so if
168       // the regionserver dies, these nodes do not stick around and this server
169       // shutdown processing does fixup (see the fixupDaughters method below).
170       // If we wanted to skip the .META. scan, we'd have to change at least the
171       // final SPLIT message to be permanent in zk so in here we'd know a SPLIT
172       // completed (zk is updated after edits to .META. have gone in).  See
173       // {@link SplitTransaction}.  We'd also have to be figure another way for
174       // doing the below .META. daughters fixup.
175       NavigableMap<HRegionInfo, Result> hris = null;
176       while (!this.server.isStopped()) {
177         try {
178           this.server.getCatalogTracker().waitForMeta();
179           hris = MetaReader.getServerUserRegions(this.server.getCatalogTracker(),
180             this.serverName);
181           break;
182         } catch (InterruptedException e) {
183           Thread.currentThread().interrupt();
184           throw new IOException("Interrupted", e);
185         } catch (IOException ioe) {
186           LOG.info("Received exception accessing META during server shutdown of " +
187               serverName + ", retrying META read", ioe);
188         }
189       }
190 
191       // Returns set of regions that had regionplans against the downed server and a list of
192       // the intersection of regions-in-transition and regions that were on the server that died.
193       Pair<Set<HRegionInfo>, List<RegionState>> p = this.services.getAssignmentManager()
194           .processServerShutdown(this.serverName);
195       Set<HRegionInfo> ritsGoingToServer = p.getFirst();
196       List<RegionState> ritsOnServer = p.getSecond();
197 
198       List<HRegionInfo> regionsToAssign = getRegionsToAssign(hris, ritsOnServer, ritsGoingToServer);
199       for (HRegionInfo hri : ritsGoingToServer) {
200         if (!this.services.getAssignmentManager().isRegionAssigned(hri)) {
201           if (!regionsToAssign.contains(hri)) {
202             regionsToAssign.add(hri);
203           }
204         }
205       }
206       for (HRegionInfo hri : regionsToAssign) {
207         this.services.getAssignmentManager().assign(hri, true);
208       }
209       LOG.info(regionsToAssign.size() + " regions which were planned to open on " + this.serverName
210           + " have been re-assigned.");
211     } finally {
212       this.deadServers.finish(serverName);
213     }
214     LOG.info("Finished processing of shutdown of " + serverName);
215   }
216 
217   /**
218    * Figure what to assign from the dead server considering state of RIT and whats up in .META.
219    * @param metaHRIs Regions that .META. says were assigned to the dead server
220    * @param ritsOnServer Regions that were in transition, and on the dead server.
221    * @param ritsGoingToServer Regions that were in transition to the dead server.
222    * @return List of regions to assign or null if aborting.
223    * @throws IOException
224    */
225   private List<HRegionInfo> getRegionsToAssign(final NavigableMap<HRegionInfo, Result> metaHRIs,
226       final List<RegionState> ritsOnServer, Set<HRegionInfo> ritsGoingToServer) throws IOException {
227     List<HRegionInfo> toAssign = new ArrayList<HRegionInfo>();
228     // If no regions on the server, then nothing to assign (Regions that were currently being
229     // assigned will be retried over in the AM#assign method).
230     if (metaHRIs == null || metaHRIs.isEmpty()) return toAssign;
231     // Remove regions that we do not want to reassign such as regions that are
232     // OFFLINE. If region is OFFLINE against this server, its probably being assigned over
233     // in the single region assign method in AM; do not assign it here too. TODO: VERIFY!!!
234     // TODO: Currently OFFLINE is too messy. Its done on single assign but bulk done when bulk
235     // assigning and then there is special handling when master joins a cluster.
236     //
237     // If split, the zk callback will have offlined. Daughters will be in the
238     // list of hris we got from scanning the .META. These should be reassigned. Not the parent.
239     for (RegionState rs : ritsOnServer) {
240       if (!rs.isClosing() && !rs.isPendingClose() && !rs.isSplitting()) {
241         LOG.debug("Removed " + rs.getRegion().getRegionNameAsString()
242             + " from list of regions to assign because region state: " + rs.getState());
243         metaHRIs.remove(rs.getRegion());
244       }
245     }
246 
247     for (Map.Entry<HRegionInfo, Result> e : metaHRIs.entrySet()) {
248       RegionState rit = services.getAssignmentManager().getRegionsInTransition().get(
249           e.getKey().getEncodedName());
250       AssignmentManager assignmentManager = this.services.getAssignmentManager();
251       if (processDeadRegion(e.getKey(), e.getValue(), assignmentManager,
252           this.server.getCatalogTracker())) {
253         ServerName addressFromAM = assignmentManager.getRegionServerOfRegion(e.getKey());
254         if (rit != null && !rit.isClosing() && !rit.isPendingClose() && !rit.isSplitting()
255             && !ritsGoingToServer.contains(e.getKey())) {
256           // Skip regions that were in transition unless CLOSING or
257           // PENDING_CLOSE
258           LOG.info("Skip assigning region " + rit.toString());
259         } else if (addressFromAM != null && !addressFromAM.equals(this.serverName)) {
260           LOG.debug("Skip assigning region " + e.getKey().getRegionNameAsString()
261               + " because it has been opened in " + addressFromAM.getServerName());
262           ritsGoingToServer.remove(e.getKey());
263         } else {
264           if (rit != null) {
265             // clean zk node
266             try {
267               LOG.info("Reassigning region with rs =" + rit + " and deleting zk node if exists");
268               ZKAssign.deleteNodeFailSilent(services.getZooKeeper(), e.getKey());
269             } catch (KeeperException ke) {
270               this.server.abort("Unexpected ZK exception deleting unassigned node " + e.getKey(),
271                   ke);
272               return null;
273             }
274           }
275           toAssign.add(e.getKey());
276         }
277       } else if (rit != null && (rit.isSplitting() || rit.isSplit())) {
278         // This will happen when the RS went down and the call back for the SPLIITING or SPLIT
279         // has not yet happened for node Deleted event. In that case if the region was actually
280         // split but the RS had gone down before completing the split process then will not try
281         // to assign the parent region again. In that case we should make the region offline
282         // and also delete the region from RIT.
283         HRegionInfo region = rit.getRegion();
284         AssignmentManager am = assignmentManager;
285         am.regionOffline(region);
286         ritsGoingToServer.remove(region);
287       }
288       // If the table was partially disabled and the RS went down, we should clear the RIT
289       // and remove the node for the region. The rit that we use may be stale in case the table
290       // was in DISABLING state but though we did assign we will not be clearing the znode in
291       // CLOSING state. Doing this will have no harm. See HBASE-5927
292       toAssign = checkForDisablingOrDisabledTables(ritsGoingToServer, toAssign, rit, assignmentManager);
293     }
294     return toAssign;
295   }
296 
297   private List<HRegionInfo> checkForDisablingOrDisabledTables(Set<HRegionInfo> regionsFromRIT,
298       List<HRegionInfo> toAssign, RegionState rit, AssignmentManager assignmentManager) {
299     if (rit == null) {
300       return toAssign;
301     }
302     if (!rit.isClosing() && !rit.isPendingClose()) {
303       return toAssign;
304     }
305     if (!assignmentManager.getZKTable().isDisablingOrDisabledTable(
306         rit.getRegion().getTableNameAsString())) {
307       return toAssign;
308     }
309     HRegionInfo hri = rit.getRegion();
310     AssignmentManager am = assignmentManager;
311     am.deleteClosingOrClosedNode(hri);
312     am.regionOffline(hri);
313     // To avoid region assignment if table is in disabling or disabled state.
314     toAssign.remove(hri);
315     regionsFromRIT.remove(hri);
316     return toAssign;
317   }
318 
319   /**
320    * Process a dead region from a dead RS. Checks if the region is disabled or
321    * disabling or if the region has a partially completed split.
322    * @param hri
323    * @param result
324    * @param assignmentManager
325    * @param catalogTracker
326    * @return Returns true if specified region should be assigned, false if not.
327    * @throws IOException
328    */
329   public static boolean processDeadRegion(HRegionInfo hri, Result result,
330       AssignmentManager assignmentManager, CatalogTracker catalogTracker)
331   throws IOException {
332     boolean tablePresent = assignmentManager.getZKTable().isTablePresent(
333         hri.getTableNameAsString());
334     if (!tablePresent) {
335       LOG.info("The table " + hri.getTableNameAsString()
336           + " was deleted.  Hence not proceeding.");
337       return false;
338     }
339     // If table is not disabled but the region is offlined,
340     boolean disabled = assignmentManager.getZKTable().isDisabledTable(
341         hri.getTableNameAsString());
342     if (disabled){
343       LOG.info("The table " + hri.getTableNameAsString()
344           + " was disabled.  Hence not proceeding.");
345       return false;
346     }
347     if (hri.isOffline() && hri.isSplit()) {
348       LOG.debug("Offlined and split region " + hri.getRegionNameAsString() +
349         "; checking daughter presence");
350       if (MetaReader.getRegion(catalogTracker, hri.getRegionName()) == null) {
351         return false;
352       }
353       fixupDaughters(result, assignmentManager, catalogTracker);
354       return false;
355     }
356     boolean disabling = assignmentManager.getZKTable().isDisablingTable(
357         hri.getTableNameAsString());
358     if (disabling) {
359       LOG.info("The table " + hri.getTableNameAsString()
360           + " is disabled.  Hence not assigning region" + hri.getEncodedName());
361       return false;
362     }
363     return true;
364   }
365 
366   /**
367    * Check that daughter regions are up in .META. and if not, add them.
368    * @param hris All regions for this server in meta.
369    * @param result The contents of the parent row in .META.
370    * @return the number of daughters missing and fixed
371    * @throws IOException
372    */
373   public static int fixupDaughters(final Result result,
374       final AssignmentManager assignmentManager,
375       final CatalogTracker catalogTracker)
376   throws IOException {
377     int fixedA = fixupDaughter(result, HConstants.SPLITA_QUALIFIER,
378       assignmentManager, catalogTracker);
379     int fixedB = fixupDaughter(result, HConstants.SPLITB_QUALIFIER,
380       assignmentManager, catalogTracker);
381     return fixedA + fixedB;
382   }
383 
384   /**
385    * Check individual daughter is up in .META.; fixup if its not.
386    * @param result The contents of the parent row in .META.
387    * @param qualifier Which daughter to check for.
388    * @return 1 if the daughter is missing and fixed. Otherwise 0
389    * @throws IOException
390    */
391   static int fixupDaughter(final Result result, final byte [] qualifier,
392       final AssignmentManager assignmentManager,
393       final CatalogTracker catalogTracker)
394   throws IOException {
395     HRegionInfo daughter =
396       MetaReader.parseHRegionInfoFromCatalogResult(result, qualifier);
397     if (daughter == null) return 0;
398     if (isDaughterMissing(catalogTracker, daughter)) {
399       LOG.info("Fixup; missing daughter " + daughter.getRegionNameAsString());
400       MetaEditor.addDaughter(catalogTracker, daughter, null);
401 
402       // TODO: Log WARN if the regiondir does not exist in the fs.  If its not
403       // there then something wonky about the split -- things will keep going
404       // but could be missing references to parent region.
405 
406       // And assign it.
407       assignmentManager.assign(daughter, true);
408       return 1;
409     } else {
410       LOG.debug("Daughter " + daughter.getRegionNameAsString() + " present");
411     }
412     return 0;
413   }
414 
415   /**
416    * Look for presence of the daughter OR of a split of the daughter in .META.
417    * Daughter could have been split over on regionserver before a run of the
418    * catalogJanitor had chance to clear reference from parent.
419    * @param daughter Daughter region to search for.
420    * @throws IOException 
421    */
422   private static boolean isDaughterMissing(final CatalogTracker catalogTracker,
423       final HRegionInfo daughter) throws IOException {
424     FindDaughterVisitor visitor = new FindDaughterVisitor(daughter);
425     // Start the scan at what should be the daughter's row in the .META.
426     // We will either 1., find the daughter or some derivative split of the
427     // daughter (will have same table name and start row at least but will sort
428     // after because has larger regionid -- the regionid is timestamp of region
429     // creation), OR, we will not find anything with same table name and start
430     // row.  If the latter, then assume daughter missing and do fixup.
431     byte [] startrow = daughter.getRegionName();
432     MetaReader.fullScan(catalogTracker, visitor, startrow);
433     return !visitor.foundDaughter();
434   }
435 
436   /**
437    * Looks for daughter.  Sets a flag if daughter or some progeny of daughter
438    * is found up in <code>.META.</code>.
439    */
440   static class FindDaughterVisitor implements MetaReader.Visitor {
441     private final HRegionInfo daughter;
442     private boolean found = false;
443 
444     FindDaughterVisitor(final HRegionInfo daughter) {
445       this.daughter = daughter;
446     }
447 
448     /**
449      * @return True if we found a daughter region during our visiting.
450      */
451     boolean foundDaughter() {
452       return this.found;
453     }
454 
455     @Override
456     public boolean visit(Result r) throws IOException {
457       HRegionInfo hri =
458         MetaReader.parseHRegionInfoFromCatalogResult(r, HConstants.REGIONINFO_QUALIFIER);
459       if (hri == null) {
460         LOG.warn("No serialized HRegionInfo in " + r);
461         return true;
462       }
463       byte [] value = r.getValue(HConstants.CATALOG_FAMILY,
464           HConstants.SERVER_QUALIFIER);
465       // See if daughter is assigned to some server
466       if (value == null) return false;
467 
468       // Now see if we have gone beyond the daughter's startrow.
469       if (!Bytes.equals(daughter.getTableName(),
470           hri.getTableName())) {
471         // We fell into another table.  Stop scanning.
472         return false;
473       }
474       // If our start rows do not compare, move on.
475       if (!Bytes.equals(daughter.getStartKey(), hri.getStartKey())) {
476         return false;
477       }
478       // Else, table name and start rows compare.  It means that the daughter
479       // or some derivative split of the daughter is up in .META.  Daughter
480       // exists.
481       this.found = true;
482       return false;
483     }
484   }
485 }