View Javadoc

1   /**
2    *
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *     http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing, software
14   * distributed under the License is distributed on an "AS IS" BASIS,
15   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16   * See the License for the specific language governing permissions and
17   * limitations under the License.
18   */
19  package org.apache.hadoop.hbase.master.handler;
20  
21  import java.io.IOException;
22  import java.io.InterruptedIOException;
23  import java.util.ArrayList;
24  import java.util.HashSet;
25  import java.util.List;
26  import java.util.Map;
27  import java.util.NavigableMap;
28  import java.util.Set;
29  import java.util.concurrent.locks.Lock;
30  
31  import org.apache.commons.logging.Log;
32  import org.apache.commons.logging.LogFactory;
33  import org.apache.hadoop.classification.InterfaceAudience;
34  import org.apache.hadoop.hbase.HConstants;
35  import org.apache.hadoop.hbase.HRegionInfo;
36  import org.apache.hadoop.hbase.Server;
37  import org.apache.hadoop.hbase.ServerName;
38  import org.apache.hadoop.hbase.catalog.CatalogTracker;
39  import org.apache.hadoop.hbase.catalog.MetaReader;
40  import org.apache.hadoop.hbase.client.Result;
41  import org.apache.hadoop.hbase.executor.EventHandler;
42  import org.apache.hadoop.hbase.executor.EventType;
43  import org.apache.hadoop.hbase.master.AssignmentManager;
44  import org.apache.hadoop.hbase.master.DeadServer;
45  import org.apache.hadoop.hbase.master.MasterServices;
46  import org.apache.hadoop.hbase.master.RegionState;
47  import org.apache.hadoop.hbase.master.RegionState.State;
48  import org.apache.hadoop.hbase.master.RegionStates;
49  import org.apache.hadoop.hbase.master.ServerManager;
50  import org.apache.hadoop.hbase.zookeeper.ZKAssign;
51  import org.apache.zookeeper.KeeperException;
52  
53  /**
54   * Process server shutdown.
55   * Server-to-handle must be already in the deadservers lists.  See
56   * {@link ServerManager#expireServer(ServerName)}
57   */
58  @InterfaceAudience.Private
59  public class ServerShutdownHandler extends EventHandler {
60    private static final Log LOG = LogFactory.getLog(ServerShutdownHandler.class);
61    protected final ServerName serverName;
62    protected final MasterServices services;
63    protected final DeadServer deadServers;
64    protected final boolean shouldSplitHlog; // whether to split HLog or not
65    protected final boolean distributedLogReplay;
66    protected final int regionAssignmentWaitTimeout;
67  
68    public ServerShutdownHandler(final Server server, final MasterServices services,
69        final DeadServer deadServers, final ServerName serverName,
70        final boolean shouldSplitHlog) {
71      this(server, services, deadServers, serverName, EventType.M_SERVER_SHUTDOWN,
72          shouldSplitHlog);
73    }
74  
75    ServerShutdownHandler(final Server server, final MasterServices services,
76        final DeadServer deadServers, final ServerName serverName, EventType type,
77        final boolean shouldSplitHlog) {
78      super(server, type);
79      this.serverName = serverName;
80      this.server = server;
81      this.services = services;
82      this.deadServers = deadServers;
83      if (!this.deadServers.isDeadServer(this.serverName)) {
84        LOG.warn(this.serverName + " is NOT in deadservers; it should be!");
85      }
86      this.shouldSplitHlog = shouldSplitHlog;
87      this.distributedLogReplay = server.getConfiguration().getBoolean(
88            HConstants.DISTRIBUTED_LOG_REPLAY_KEY, 
89            HConstants.DEFAULT_DISTRIBUTED_LOG_REPLAY_CONFIG);
90      this.regionAssignmentWaitTimeout = server.getConfiguration().getInt(
91        HConstants.LOG_REPLAY_WAIT_REGION_TIMEOUT, 15000);
92    }
93  
94    @Override
95    public String getInformativeName() {
96      if (serverName != null) {
97        return this.getClass().getSimpleName() + " for " + serverName;
98      } else {
99        return super.getInformativeName();
100     }
101   }
102 
103   /**
104    * @return True if the server we are processing was carrying <code>hbase:meta</code>
105    */
106   boolean isCarryingMeta() {
107     return false;
108   }
109 
110   @Override
111   public String toString() {
112     String name = "UnknownServerName";
113     if(server != null && server.getServerName() != null) {
114       name = server.getServerName().toString();
115     }
116     return getClass().getSimpleName() + "-" + name + "-" + getSeqid();
117   }
118 
119   @Override
120   public void process() throws IOException {
121     boolean hasLogReplayWork = false;
122     final ServerName serverName = this.serverName;
123     try {
124 
125       // We don't want worker thread in the MetaServerShutdownHandler
126       // executor pool to block by waiting availability of hbase:meta
127       // Otherwise, it could run into the following issue:
128       // 1. The current MetaServerShutdownHandler instance For RS1 waits for the hbase:meta
129       //    to come online.
130       // 2. The newly assigned hbase:meta region server RS2 was shutdown right after
131       //    it opens the hbase:meta region. So the MetaServerShutdownHandler
132       //    instance For RS1 will still be blocked.
133       // 3. The new instance of MetaServerShutdownHandler for RS2 is queued.
134       // 4. The newly assigned hbase:meta region server RS3 was shutdown right after
135       //    it opens the hbase:meta region. So the MetaServerShutdownHandler
136       //    instance For RS1 and RS2 will still be blocked.
137       // 5. The new instance of MetaServerShutdownHandler for RS3 is queued.
138       // 6. Repeat until we run out of MetaServerShutdownHandler worker threads
139       // The solution here is to resubmit a ServerShutdownHandler request to process
140       // user regions on that server so that MetaServerShutdownHandler
141       // executor pool is always available.
142       //
143       // If AssignmentManager hasn't finished rebuilding user regions,
144       // we are not ready to assign dead regions either. So we re-queue up
145       // the dead server for further processing too.
146       AssignmentManager am = services.getAssignmentManager();
147       if (isCarryingMeta() // hbase:meta
148           || !am.isFailoverCleanupDone()) {
149         this.services.getServerManager().processDeadServer(serverName, this.shouldSplitHlog);
150         return;
151       }
152 
153       // Wait on meta to come online; we need it to progress.
154       // TODO: Best way to hold strictly here?  We should build this retry logic
155       // into the MetaReader operations themselves.
156       // TODO: Is the reading of hbase:meta necessary when the Master has state of
157       // cluster in its head?  It should be possible to do without reading hbase:meta
158       // in all but one case. On split, the RS updates the hbase:meta
159       // table and THEN informs the master of the split via zk nodes in
160       // 'unassigned' dir.  Currently the RS puts ephemeral nodes into zk so if
161       // the regionserver dies, these nodes do not stick around and this server
162       // shutdown processing does fixup (see the fixupDaughters method below).
163       // If we wanted to skip the hbase:meta scan, we'd have to change at least the
164       // final SPLIT message to be permanent in zk so in here we'd know a SPLIT
165       // completed (zk is updated after edits to hbase:meta have gone in).  See
166       // {@link SplitTransaction}.  We'd also have to be figure another way for
167       // doing the below hbase:meta daughters fixup.
168       NavigableMap<HRegionInfo, Result> hris = null;
169       while (!this.server.isStopped()) {
170         try {
171           this.server.getCatalogTracker().waitForMeta();
172           // Skip getting user regions if the server is stopped.
173           if (!this.server.isStopped()) {
174             hris = MetaReader.getServerUserRegions(this.server.getCatalogTracker(),
175                 this.serverName);
176           }
177           break;
178         } catch (InterruptedException e) {
179           Thread.currentThread().interrupt();
180           throw new IOException("Interrupted", e);
181         } catch (IOException ioe) {
182           LOG.info("Received exception accessing hbase:meta during server shutdown of " +
183             serverName + ", retrying hbase:meta read", ioe);
184         }
185       }
186       if (this.server.isStopped()) {
187         throw new IOException("Server is stopped");
188       }
189 
190       try {
191         if (this.shouldSplitHlog) {
192           LOG.info("Splitting logs for " + serverName + " before assignment.");
193           if (this.distributedLogReplay) {
194             LOG.info("Mark regions in recovery before assignment.");
195             Set<ServerName> serverNames = new HashSet<ServerName>();
196             serverNames.add(serverName);
197             this.services.getMasterFileSystem().prepareLogReplay(serverNames);
198           } else {
199             this.services.getMasterFileSystem().splitLog(serverName);
200           }
201           am.getRegionStates().logSplit(serverName);
202         } else {
203           LOG.info("Skipping log splitting for " + serverName);
204         }
205       } catch (IOException ioe) {
206         resubmit(serverName, ioe);
207       }
208 
209       // Clean out anything in regions in transition.  Being conservative and
210       // doing after log splitting.  Could do some states before -- OPENING?
211       // OFFLINE? -- and then others after like CLOSING that depend on log
212       // splitting.
213       List<HRegionInfo> regionsInTransition = am.processServerShutdown(serverName);
214       LOG.info("Reassigning " + ((hris == null)? 0: hris.size()) +
215         " region(s) that " + (serverName == null? "null": serverName)  +
216         " was carrying (and " + regionsInTransition.size() +
217         " regions(s) that were opening on this server)");
218 
219       List<HRegionInfo> toAssignRegions = new ArrayList<HRegionInfo>();
220       toAssignRegions.addAll(regionsInTransition);
221 
222       // Iterate regions that were on this server and assign them
223       if (hris != null) {
224         RegionStates regionStates = am.getRegionStates();
225         for (Map.Entry<HRegionInfo, Result> e: hris.entrySet()) {
226           HRegionInfo hri = e.getKey();
227           if (regionsInTransition.contains(hri)) {
228             continue;
229           }
230           String encodedName = hri.getEncodedName();
231           Lock lock = am.acquireRegionLock(encodedName);
232           try {
233             RegionState rit = regionStates.getRegionTransitionState(hri);
234             if (processDeadRegion(hri, e.getValue(), am, server.getCatalogTracker())) {
235               ServerName addressFromAM = regionStates.getRegionServerOfRegion(hri);
236               if (addressFromAM != null && !addressFromAM.equals(this.serverName)) {
237                 // If this region is in transition on the dead server, it must be
238                 // opening or pending_open, which should have been covered by AM#processServerShutdown
239                 LOG.info("Skip assigning region " + hri.getRegionNameAsString()
240                   + " because it has been opened in " + addressFromAM.getServerName());
241                 continue;
242               }
243               if (rit != null) {
244                 if (rit.getServerName() != null && !rit.isOnServer(serverName)) {
245                   // Skip regions that are in transition on other server
246                   LOG.info("Skip assigning region in transition on other server" + rit);
247                   continue;
248                 }
249                 try{
250                   //clean zk node
251                   LOG.info("Reassigning region with rs = " + rit + " and deleting zk node if exists");
252                   ZKAssign.deleteNodeFailSilent(services.getZooKeeper(), hri);
253                   regionStates.updateRegionState(hri, State.OFFLINE);
254                 } catch (KeeperException ke) {
255                   this.server.abort("Unexpected ZK exception deleting unassigned node " + hri, ke);
256                   return;
257                 }
258               } else if (regionStates.isRegionInState(
259                   hri, State.SPLITTING_NEW, State.MERGING_NEW)) {
260                 regionStates.regionOffline(hri);
261               }
262               toAssignRegions.add(hri);
263             } else if (rit != null) {
264               if (rit.isPendingCloseOrClosing()
265                   && am.getZKTable().isDisablingOrDisabledTable(hri.getTable())) {
266                 // If the table was partially disabled and the RS went down, we should clear the RIT
267                 // and remove the node for the region.
268                 // The rit that we use may be stale in case the table was in DISABLING state
269                 // but though we did assign we will not be clearing the znode in CLOSING state.
270                 // Doing this will have no harm. See HBASE-5927
271                 regionStates.updateRegionState(hri, State.OFFLINE);
272                 am.deleteClosingOrClosedNode(hri, rit.getServerName());
273                 am.offlineDisabledRegion(hri);
274               } else {
275                 LOG.warn("THIS SHOULD NOT HAPPEN: unexpected region in transition "
276                   + rit + " not to be assigned by SSH of server " + serverName);
277               }
278             }
279           } finally {
280             lock.unlock();
281           }
282         }
283       }
284 
285       try {
286         am.assign(toAssignRegions);
287       } catch (InterruptedException ie) {
288         LOG.error("Caught " + ie + " during round-robin assignment");
289         throw new IOException(ie);
290       }
291 
292       if (this.shouldSplitHlog && this.distributedLogReplay) {
293         // wait for region assignment completes
294         for (HRegionInfo hri : toAssignRegions) {
295           try {
296             if (!am.waitOnRegionToClearRegionsInTransition(hri, regionAssignmentWaitTimeout)) {
297               // Wait here is to avoid log replay hits current dead server and incur a RPC timeout
298               // when replay happens before region assignment completes.
299               LOG.warn("Region " + hri.getEncodedName()
300                   + " didn't complete assignment in time");
301             }
302           } catch (InterruptedException ie) {
303             throw new InterruptedIOException("Caught " + ie
304                 + " during waitOnRegionToClearRegionsInTransition");
305           }
306         }
307         // submit logReplay work
308         this.services.getExecutorService().submit(
309           new LogReplayHandler(this.server, this.services, this.deadServers, this.serverName));
310         hasLogReplayWork = true;
311       }
312     } finally {
313       this.deadServers.finish(serverName);
314     }
315 
316     if (!hasLogReplayWork) {
317       LOG.info("Finished processing of shutdown of " + serverName);
318     }
319   }
320 
321   private void resubmit(final ServerName serverName, IOException ex) throws IOException {
322     // typecast to SSH so that we make sure that it is the SSH instance that
323     // gets submitted as opposed to MSSH or some other derived instance of SSH
324     this.services.getExecutorService().submit((ServerShutdownHandler) this);
325     this.deadServers.add(serverName);
326     throw new IOException("failed log splitting for " + serverName + ", will retry", ex);
327   }
328 
329   /**
330    * Process a dead region from a dead RS. Checks if the region is disabled or
331    * disabling or if the region has a partially completed split.
332    * @param hri
333    * @param result
334    * @param assignmentManager
335    * @param catalogTracker
336    * @return Returns true if specified region should be assigned, false if not.
337    * @throws IOException
338    */
339   public static boolean processDeadRegion(HRegionInfo hri, Result result,
340       AssignmentManager assignmentManager, CatalogTracker catalogTracker)
341   throws IOException {
342     boolean tablePresent = assignmentManager.getZKTable().isTablePresent(hri.getTable());
343     if (!tablePresent) {
344       LOG.info("The table " + hri.getTable()
345           + " was deleted.  Hence not proceeding.");
346       return false;
347     }
348     // If table is not disabled but the region is offlined,
349     boolean disabled = assignmentManager.getZKTable().isDisabledTable(hri.getTable());
350     if (disabled){
351       LOG.info("The table " + hri.getTable()
352           + " was disabled.  Hence not proceeding.");
353       return false;
354     }
355     if (hri.isOffline() && hri.isSplit()) {
356       //HBASE-7721: Split parent and daughters are inserted into hbase:meta as an atomic operation.
357       //If the meta scanner saw the parent split, then it should see the daughters as assigned
358       //to the dead server. We don't have to do anything.
359       return false;
360     }
361     boolean disabling = assignmentManager.getZKTable().isDisablingTable(hri.getTable());
362     if (disabling) {
363       LOG.info("The table " + hri.getTable()
364           + " is disabled.  Hence not assigning region" + hri.getEncodedName());
365       return false;
366     }
367     return true;
368   }
369 }