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.classification.InterfaceAudience;
31  import org.apache.hadoop.conf.Configuration;
32  import org.apache.hadoop.hbase.HConstants;
33  import org.apache.hadoop.hbase.HRegionInfo;
34  import org.apache.hadoop.hbase.Server;
35  import org.apache.hadoop.hbase.ServerName;
36  import org.apache.hadoop.hbase.catalog.CatalogTracker;
37  import org.apache.hadoop.hbase.catalog.MetaReader;
38  import org.apache.hadoop.hbase.executor.EventHandler;
39  import org.apache.hadoop.hbase.executor.EventType;
40  import org.apache.hadoop.hbase.master.AssignmentManager;
41  import org.apache.hadoop.hbase.master.DeadServer;
42  import org.apache.hadoop.hbase.master.MasterFileSystem;
43  import org.apache.hadoop.hbase.master.MasterServices;
44  import org.apache.hadoop.hbase.master.RegionState;
45  import org.apache.hadoop.hbase.master.RegionState.State;
46  import org.apache.hadoop.hbase.master.RegionStates;
47  import org.apache.hadoop.hbase.master.ServerManager;
48  import org.apache.hadoop.hbase.protobuf.generated.ZooKeeperProtos.SplitLogTask.RecoveryMode;
49  import org.apache.hadoop.hbase.regionserver.wal.HLogSplitter;
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 int regionAssignmentWaitTimeout;
66  
67    public ServerShutdownHandler(final Server server, final MasterServices services,
68        final DeadServer deadServers, final ServerName serverName,
69        final boolean shouldSplitHlog) {
70      this(server, services, deadServers, serverName, EventType.M_SERVER_SHUTDOWN,
71          shouldSplitHlog);
72    }
73  
74    ServerShutdownHandler(final Server server, final MasterServices services,
75        final DeadServer deadServers, final ServerName serverName, EventType type,
76        final boolean shouldSplitHlog) {
77      super(server, type);
78      this.serverName = serverName;
79      this.server = server;
80      this.services = services;
81      this.deadServers = deadServers;
82      if (!this.deadServers.isDeadServer(this.serverName)) {
83        LOG.warn(this.serverName + " is NOT in deadservers; it should be!");
84      }
85      this.shouldSplitHlog = shouldSplitHlog;
86      this.regionAssignmentWaitTimeout = server.getConfiguration().getInt(
87        HConstants.LOG_REPLAY_WAIT_REGION_TIMEOUT, 15000);
88    }
89  
90    @Override
91    public String getInformativeName() {
92      if (serverName != null) {
93        return this.getClass().getSimpleName() + " for " + serverName;
94      } else {
95        return super.getInformativeName();
96      }
97    }
98  
99    /**
100    * @return True if the server we are processing was carrying <code>hbase: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     boolean hasLogReplayWork = false;
118     final ServerName serverName = this.serverName;
119     try {
120 
121       // We don't want worker thread in the MetaServerShutdownHandler
122       // executor pool to block by waiting availability of hbase:meta
123       // Otherwise, it could run into the following issue:
124       // 1. The current MetaServerShutdownHandler instance For RS1 waits for the hbase:meta
125       //    to come online.
126       // 2. The newly assigned hbase:meta region server RS2 was shutdown right after
127       //    it opens the hbase:meta region. So the MetaServerShutdownHandler
128       //    instance For RS1 will still be blocked.
129       // 3. The new instance of MetaServerShutdownHandler for RS2 is queued.
130       // 4. The newly assigned hbase:meta region server RS3 was shutdown right after
131       //    it opens the hbase:meta region. So the MetaServerShutdownHandler
132       //    instance For RS1 and RS2 will still be blocked.
133       // 5. The new instance of MetaServerShutdownHandler for RS3 is queued.
134       // 6. Repeat until we run out of MetaServerShutdownHandler worker threads
135       // The solution here is to resubmit a ServerShutdownHandler request to process
136       // user regions on that server so that MetaServerShutdownHandler
137       // executor pool is always available.
138       //
139       // If AssignmentManager hasn't finished rebuilding user regions,
140       // we are not ready to assign dead regions either. So we re-queue up
141       // the dead server for further processing too.
142       AssignmentManager am = services.getAssignmentManager();
143       if (isCarryingMeta() // hbase:meta
144           || !am.isFailoverCleanupDone()) {
145         this.services.getServerManager().processDeadServer(serverName, this.shouldSplitHlog);
146         return;
147       }
148 
149       // Wait on meta to come online; we need it to progress.
150       // TODO: Best way to hold strictly here?  We should build this retry logic
151       // into the MetaReader operations themselves.
152       // TODO: Is the reading of hbase:meta necessary when the Master has state of
153       // cluster in its head?  It should be possible to do without reading hbase:meta
154       // in all but one case. On split, the RS updates the hbase:meta
155       // table and THEN informs the master of the split via zk nodes in
156       // 'unassigned' dir.  Currently the RS puts ephemeral nodes into zk so if
157       // the regionserver dies, these nodes do not stick around and this server
158       // shutdown processing does fixup (see the fixupDaughters method below).
159       // If we wanted to skip the hbase:meta scan, we'd have to change at least the
160       // final SPLIT message to be permanent in zk so in here we'd know a SPLIT
161       // completed (zk is updated after edits to hbase:meta have gone in).  See
162       // {@link SplitTransaction}.  We'd also have to be figure another way for
163       // doing the below hbase:meta daughters fixup.
164       Set<HRegionInfo> hris = null;
165       while (!this.server.isStopped()) {
166         try {
167           this.server.getCatalogTracker().waitForMeta();
168           // Skip getting user regions if the server is stopped.
169           if (!this.server.isStopped()) {
170             hris = MetaReader.getServerUserRegions(this.server.getCatalogTracker(),
171               this.serverName).keySet();
172           }
173           break;
174         } catch (InterruptedException e) {
175           Thread.currentThread().interrupt();
176           throw (InterruptedIOException)new InterruptedIOException().initCause(e);
177         } catch (IOException ioe) {
178           LOG.info("Received exception accessing hbase:meta during server shutdown of " +
179             serverName + ", retrying hbase:meta read", ioe);
180         }
181       }
182       if (this.server.isStopped()) {
183         throw new IOException("Server is stopped");
184       }
185 
186       // delayed to set recovery mode based on configuration only after all outstanding splitlogtask
187       // drained
188       this.services.getMasterFileSystem().setLogRecoveryMode();
189       boolean distributedLogReplay = 
190         (this.services.getMasterFileSystem().getLogRecoveryMode() == RecoveryMode.LOG_REPLAY);
191 
192       try {
193         if (this.shouldSplitHlog) {
194           LOG.info("Splitting logs for " + serverName + " before assignment.");
195           if (distributedLogReplay) {
196             LOG.info("Mark regions in recovery before assignment.");
197             MasterFileSystem mfs = this.services.getMasterFileSystem();
198             mfs.prepareLogReplay(serverName, hris);
199           } else {
200             this.services.getMasterFileSystem().splitLog(serverName);
201           }
202           am.getRegionStates().logSplit(serverName);
203         } else {
204           LOG.info("Skipping log splitting for " + serverName);
205         }
206       } catch (IOException ioe) {
207         resubmit(serverName, ioe);
208       }
209 
210       // Clean out anything in regions in transition.  Being conservative and
211       // doing after log splitting.  Could do some states before -- OPENING?
212       // OFFLINE? -- and then others after like CLOSING that depend on log
213       // splitting.
214       List<HRegionInfo> regionsInTransition = am.processServerShutdown(serverName);
215       LOG.info("Reassigning " + ((hris == null)? 0: hris.size()) +
216         " region(s) that " + (serverName == null? "null": serverName)  +
217         " was carrying (and " + regionsInTransition.size() +
218         " regions(s) that were opening on this server)");
219 
220       List<HRegionInfo> toAssignRegions = new ArrayList<HRegionInfo>();
221       toAssignRegions.addAll(regionsInTransition);
222 
223       // Iterate regions that were on this server and assign them
224       if (hris != null && !hris.isEmpty()) {
225         RegionStates regionStates = am.getRegionStates();
226         for (HRegionInfo hri: hris) {
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, 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.updateRegionState(hri, State.OFFLINE);
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 (InterruptedIOException)new InterruptedIOException().initCause(ie);
290       }
291 
292       if (this.shouldSplitHlog && 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 assignmentManager
334    * @param catalogTracker
335    * @return Returns true if specified region should be assigned, false if not.
336    * @throws IOException
337    */
338   public static boolean processDeadRegion(HRegionInfo hri,
339       AssignmentManager assignmentManager, CatalogTracker catalogTracker)
340   throws IOException {
341     boolean tablePresent = assignmentManager.getZKTable().isTablePresent(hri.getTable());
342     if (!tablePresent) {
343       LOG.info("The table " + hri.getTable()
344           + " was deleted.  Hence not proceeding.");
345       return false;
346     }
347     // If table is not disabled but the region is offlined,
348     boolean disabled = assignmentManager.getZKTable().isDisabledTable(hri.getTable());
349     if (disabled){
350       LOG.info("The table " + hri.getTable()
351           + " was disabled.  Hence not proceeding.");
352       return false;
353     }
354     if (hri.isOffline() && hri.isSplit()) {
355       //HBASE-7721: Split parent and daughters are inserted into hbase:meta as an atomic operation.
356       //If the meta scanner saw the parent split, then it should see the daughters as assigned
357       //to the dead server. We don't have to do anything.
358       return false;
359     }
360     boolean disabling = assignmentManager.getZKTable().isDisablingTable(hri.getTable());
361     if (disabling) {
362       LOG.info("The table " + hri.getTable()
363           + " is disabled.  Hence not assigning region" + hri.getEncodedName());
364       return false;
365     }
366     return true;
367   }
368 }