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