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