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