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.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.executor.EventHandler;
36  import org.apache.hadoop.hbase.executor.EventType;
37  import org.apache.hadoop.hbase.master.AssignmentManager;
38  import org.apache.hadoop.hbase.master.DeadServer;
39  import org.apache.hadoop.hbase.master.MasterFileSystem;
40  import org.apache.hadoop.hbase.master.MasterServices;
41  import org.apache.hadoop.hbase.master.RegionState;
42  import org.apache.hadoop.hbase.master.RegionState.State;
43  import org.apache.hadoop.hbase.master.RegionStates;
44  import org.apache.hadoop.hbase.master.ServerManager;
45  import org.apache.hadoop.hbase.protobuf.generated.ZooKeeperProtos;
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 shouldSplitHlog; // whether to split HLog 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 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.isDeadServer(this.serverName)) {
78        LOG.warn(this.serverName + " is NOT in deadservers; it should be!");
79      }
80      this.shouldSplitHlog = shouldSplitHlog;
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       if (isCarryingMeta() // hbase:meta
135           || !am.isFailoverCleanupDone()) {
136         this.services.getServerManager().processDeadServer(serverName, this.shouldSplitHlog);
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       while (!this.server.isStopped()) {
157         try {
158           server.getMetaTableLocator().waitMetaRegionLocation(server.getZooKeeper());
159           hris = am.getRegionStates().getServerRegions(serverName);
160           break;
161         } catch (InterruptedException e) {
162           Thread.currentThread().interrupt();
163           throw (InterruptedIOException)new InterruptedIOException().initCause(e);
164         }
165       }
166       if (this.server.isStopped()) {
167         throw new IOException("Server is stopped");
168       }
169 
170       // delayed to set recovery mode based on configuration only after all outstanding splitlogtask
171       // drained
172       this.services.getMasterFileSystem().setLogRecoveryMode();
173       boolean distributedLogReplay = 
174         (this.services.getMasterFileSystem().getLogRecoveryMode() == RecoveryMode.LOG_REPLAY);
175 
176       try {
177         if (this.shouldSplitHlog) {
178           LOG.info("Splitting logs for " + serverName + " before assignment.");
179           if (distributedLogReplay) {
180             LOG.info("Mark regions in recovery before assignment.");
181             MasterFileSystem mfs = this.services.getMasterFileSystem();
182             mfs.prepareLogReplay(serverName, hris);
183           } else {
184             this.services.getMasterFileSystem().splitLog(serverName);
185           }
186           am.getRegionStates().logSplit(serverName);
187         } else {
188           LOG.info("Skipping log splitting for " + serverName);
189         }
190       } catch (IOException ioe) {
191         resubmit(serverName, ioe);
192       }
193 
194       // Clean out anything in regions in transition.  Being conservative and
195       // doing after log splitting.  Could do some states before -- OPENING?
196       // OFFLINE? -- and then others after like CLOSING that depend on log
197       // splitting.
198       List<HRegionInfo> regionsInTransition = am.processServerShutdown(serverName);
199       LOG.info("Reassigning " + ((hris == null)? 0: hris.size()) +
200         " region(s) that " + (serverName == null? "null": serverName)  +
201         " was carrying (and " + regionsInTransition.size() +
202         " regions(s) that were opening on this server)");
203 
204       List<HRegionInfo> toAssignRegions = new ArrayList<HRegionInfo>();
205       toAssignRegions.addAll(regionsInTransition);
206 
207       // Iterate regions that were on this server and assign them
208       if (hris != null && !hris.isEmpty()) {
209         RegionStates regionStates = am.getRegionStates();
210         for (HRegionInfo hri: hris) {
211           if (regionsInTransition.contains(hri)) {
212             continue;
213           }
214           String encodedName = hri.getEncodedName();
215           Lock lock = am.acquireRegionLock(encodedName);
216           try {
217             RegionState rit = regionStates.getRegionTransitionState(hri);
218             if (processDeadRegion(hri, am)) {
219               ServerName addressFromAM = regionStates.getRegionServerOfRegion(hri);
220               if (addressFromAM != null && !addressFromAM.equals(this.serverName)) {
221                 // If this region is in transition on the dead server, it must be
222                 // opening or pending_open, which should have been covered by AM#processServerShutdown
223                 LOG.info("Skip assigning region " + hri.getRegionNameAsString()
224                   + " because it has been opened in " + addressFromAM.getServerName());
225                 continue;
226               }
227               if (rit != null) {
228                 if (rit.getServerName() != null && !rit.isOnServer(serverName)) {
229                   // Skip regions that are in transition on other server
230                   LOG.info("Skip assigning region in transition on other server" + rit);
231                   continue;
232                 }
233                 LOG.info("Reassigning region with rs = " + rit);
234                 regionStates.updateRegionState(hri, State.OFFLINE);
235               } else if (regionStates.isRegionInState(
236                   hri, State.SPLITTING_NEW, State.MERGING_NEW)) {
237                 regionStates.updateRegionState(hri, State.OFFLINE);
238               }
239               toAssignRegions.add(hri);
240             } else if (rit != null) {
241               if ((rit.isClosing() || rit.isFailedClose() || rit.isOffline())
242                   && am.getTableStateManager().isTableState(hri.getTable(),
243                   ZooKeeperProtos.Table.State.DISABLED, ZooKeeperProtos.Table.State.DISABLING) ||
244                   am.getReplicasToClose().contains(hri)) {
245                 // If the table was partially disabled and the RS went down, we should clear the RIT
246                 // and remove the node for the region.
247                 // The rit that we use may be stale in case the table was in DISABLING state
248                 // but though we did assign we will not be clearing the znode in CLOSING state.
249                 // Doing this will have no harm. See HBASE-5927
250                 regionStates.updateRegionState(hri, State.OFFLINE);
251                 am.offlineDisabledRegion(hri);
252               } else {
253                 LOG.warn("THIS SHOULD NOT HAPPEN: unexpected region in transition "
254                   + rit + " not to be assigned by SSH of server " + serverName);
255               }
256             }
257           } finally {
258             lock.unlock();
259           }
260         }
261       }
262 
263       try {
264         am.assign(toAssignRegions);
265       } catch (InterruptedException ie) {
266         LOG.error("Caught " + ie + " during round-robin assignment");
267         throw (InterruptedIOException)new InterruptedIOException().initCause(ie);
268       }
269 
270       if (this.shouldSplitHlog && distributedLogReplay) {
271         // wait for region assignment completes
272         for (HRegionInfo hri : toAssignRegions) {
273           try {
274             if (!am.waitOnRegionToClearRegionsInTransition(hri, regionAssignmentWaitTimeout)) {
275               // Wait here is to avoid log replay hits current dead server and incur a RPC timeout
276               // when replay happens before region assignment completes.
277               LOG.warn("Region " + hri.getEncodedName()
278                   + " didn't complete assignment in time");
279             }
280           } catch (InterruptedException ie) {
281             throw new InterruptedIOException("Caught " + ie
282                 + " during waitOnRegionToClearRegionsInTransition");
283           }
284         }
285         // submit logReplay work
286         this.services.getExecutorService().submit(
287           new LogReplayHandler(this.server, this.services, this.deadServers, this.serverName));
288         hasLogReplayWork = true;
289       }
290     } finally {
291       this.deadServers.finish(serverName);
292     }
293 
294     if (!hasLogReplayWork) {
295       LOG.info("Finished processing of shutdown of " + serverName);
296     }
297   }
298 
299   private void resubmit(final ServerName serverName, IOException ex) throws IOException {
300     // typecast to SSH so that we make sure that it is the SSH instance that
301     // gets submitted as opposed to MSSH or some other derived instance of SSH
302     this.services.getExecutorService().submit((ServerShutdownHandler) this);
303     this.deadServers.add(serverName);
304     throw new IOException("failed log splitting for " + serverName + ", will retry", ex);
305   }
306 
307   /**
308    * Process a dead region from a dead RS. Checks if the region is disabled or
309    * disabling or if the region has a partially completed split.
310    * @param hri
311    * @param assignmentManager
312    * @return Returns true if specified region should be assigned, false if not.
313    * @throws IOException
314    */
315   public static boolean processDeadRegion(HRegionInfo hri,
316       AssignmentManager assignmentManager)
317   throws IOException {
318     boolean tablePresent = assignmentManager.getTableStateManager().isTablePresent(hri.getTable());
319     if (!tablePresent) {
320       LOG.info("The table " + hri.getTable()
321           + " was deleted.  Hence not proceeding.");
322       return false;
323     }
324     // If table is not disabled but the region is offlined,
325     boolean disabled = assignmentManager.getTableStateManager().isTableState(hri.getTable(),
326       ZooKeeperProtos.Table.State.DISABLED);
327     if (disabled){
328       LOG.info("The table " + hri.getTable()
329           + " was disabled.  Hence not proceeding.");
330       return false;
331     }
332     if (hri.isOffline() && hri.isSplit()) {
333       //HBASE-7721: Split parent and daughters are inserted into hbase:meta as an atomic operation.
334       //If the meta scanner saw the parent split, then it should see the daughters as assigned
335       //to the dead server. We don't have to do anything.
336       return false;
337     }
338     boolean disabling = assignmentManager.getTableStateManager().isTableState(hri.getTable(),
339       ZooKeeperProtos.Table.State.DISABLING);
340     if (disabling) {
341       LOG.info("The table " + hri.getTable()
342           + " is disabled.  Hence not assigning region" + hri.getEncodedName());
343       return false;
344     }
345     return true;
346   }
347 }