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