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