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           LOG.info("Reassigning meta replica" + metaHri + " that was on " + serverName);
230           toAssignRegions.add(metaHri);
231         }
232       }
233       // Clean out anything in regions in transition.  Being conservative and
234       // doing after log splitting.  Could do some states before -- OPENING?
235       // OFFLINE? -- and then others after like CLOSING that depend on log
236       // splitting.
237       List<HRegionInfo> regionsInTransition = am.processServerShutdown(serverName);
238       LOG.info("Reassigning " + ((hris == null)? 0: hris.size()) +
239         " region(s) that " + (serverName == null? "null": serverName)  +
240         " was carrying (and " + regionsInTransition.size() +
241         " regions(s) that were opening on this server)");
242       
243       toAssignRegions.addAll(regionsInTransition);
244 
245       // Iterate regions that were on this server and assign them
246       if (hris != null && !hris.isEmpty()) {
247         RegionStates regionStates = am.getRegionStates();
248         for (HRegionInfo hri: hris) {
249           if (regionsInTransition.contains(hri)) {
250             continue;
251           }
252           String encodedName = hri.getEncodedName();
253           Lock lock = am.acquireRegionLock(encodedName);
254           try {
255             RegionState rit = regionStates.getRegionTransitionState(hri);
256             if (processDeadRegion(hri, am)) { 
257               ServerName addressFromAM = regionStates.getRegionServerOfRegion(hri);
258               if (addressFromAM != null && !addressFromAM.equals(this.serverName)) {
259                 // If this region is in transition on the dead server, it must be
260                 // opening or pending_open, which should have been covered by AM#processServerShutdown
261                 LOG.info("Skip assigning region " + hri.getRegionNameAsString()
262                   + " because it has been opened in " + addressFromAM.getServerName());
263                 continue;
264               }
265               if (rit != null) {
266                 if (rit.getServerName() != null && !rit.isOnServer(serverName)) {
267                   // Skip regions that are in transition on other server
268                   LOG.info("Skip assigning region in transition on other server" + rit);
269                   continue;
270                 }
271                 try{
272                   //clean zk node
273                   LOG.info("Reassigning region with rs = " + rit + " and deleting zk node if exists");
274                   ZKAssign.deleteNodeFailSilent(services.getZooKeeper(), hri);
275                   regionStates.updateRegionState(hri, State.OFFLINE);
276                 } catch (KeeperException ke) {
277                   this.server.abort("Unexpected ZK exception deleting unassigned node " + hri, ke);
278                   return;
279                 }
280               } else if (regionStates.isRegionInState(
281                   hri, State.SPLITTING_NEW, State.MERGING_NEW)) {
282                 regionStates.updateRegionState(hri, State.OFFLINE);
283               }
284               toAssignRegions.add(hri);
285             } else if (rit != null) {
286               if ((rit.isPendingCloseOrClosing() || rit.isOffline())
287                   && am.getTableStateManager().isTableState(hri.getTable(),
288                   ZooKeeperProtos.Table.State.DISABLED, ZooKeeperProtos.Table.State.DISABLING) ||
289                   am.getReplicasToClose().contains(hri)) {
290                 // If the table was partially disabled and the RS went down, we should clear the RIT
291                 // and remove the node for the region.
292                 // The rit that we use may be stale in case the table was in DISABLING state
293                 // but though we did assign we will not be clearing the znode in CLOSING state.
294                 // Doing this will have no harm. See HBASE-5927
295                 regionStates.updateRegionState(hri, State.OFFLINE);
296                 am.deleteClosingOrClosedNode(hri, rit.getServerName());
297                 am.offlineDisabledRegion(hri);
298               } else {
299                 LOG.warn("THIS SHOULD NOT HAPPEN: unexpected region in transition "
300                   + rit + " not to be assigned by SSH of server " + serverName);
301               }
302             }
303           } finally {
304             lock.unlock();
305           }
306         }
307       }
308 
309       try {
310         am.assign(toAssignRegions);
311       } catch (InterruptedException ie) {
312         LOG.error("Caught " + ie + " during round-robin assignment");
313         throw (InterruptedIOException)new InterruptedIOException().initCause(ie);
314       } catch (IOException ioe) {
315         LOG.info("Caught " + ioe + " during region assignment, will retry");
316         // Only do wal splitting if shouldSplitWal and in DLR mode
317         serverManager.processDeadServer(serverName,
318           this.shouldSplitWal && distributedLogReplay);
319         return;
320       }
321 
322       if (this.shouldSplitWal && distributedLogReplay) {
323         // wait for region assignment completes
324         for (HRegionInfo hri : toAssignRegions) {
325           try {
326             if (!am.waitOnRegionToClearRegionsInTransition(hri, regionAssignmentWaitTimeout)) {
327               // Wait here is to avoid log replay hits current dead server and incur a RPC timeout
328               // when replay happens before region assignment completes.
329               LOG.warn("Region " + hri.getEncodedName()
330                   + " didn't complete assignment in time");
331             }
332           } catch (InterruptedException ie) {
333             throw new InterruptedIOException("Caught " + ie
334                 + " during waitOnRegionToClearRegionsInTransition");
335           }
336         }
337         // submit logReplay work
338         this.services.getExecutorService().submit(
339           new LogReplayHandler(this.server, this.services, this.deadServers, this.serverName));
340         hasLogReplayWork = true;
341       }
342     } finally {
343       this.deadServers.finish(serverName);
344     }
345 
346     if (!hasLogReplayWork) {
347       LOG.info("Finished processing of shutdown of " + serverName);
348     }
349   }
350 
351   private void resubmit(final ServerName serverName, IOException ex) throws IOException {
352     // typecast to SSH so that we make sure that it is the SSH instance that
353     // gets submitted as opposed to MSSH or some other derived instance of SSH
354     this.services.getExecutorService().submit((ServerShutdownHandler) this);
355     this.deadServers.add(serverName);
356     throw new IOException("failed log splitting for " + serverName + ", will retry", ex);
357   }
358 
359   /**
360    * Process a dead region from a dead RS. Checks if the region is disabled or
361    * disabling or if the region has a partially completed split.
362    * @param hri
363    * @param assignmentManager
364    * @return Returns true if specified region should be assigned, false if not.
365    * @throws IOException
366    */
367   public static boolean processDeadRegion(HRegionInfo hri,
368       AssignmentManager assignmentManager)
369   throws IOException {
370     boolean tablePresent = assignmentManager.getTableStateManager().isTablePresent(hri.getTable());
371     if (!tablePresent) {
372       LOG.info("The table " + hri.getTable()
373           + " was deleted.  Hence not proceeding.");
374       return false;
375     }
376     // If table is not disabled but the region is offlined,
377     boolean disabled = assignmentManager.getTableStateManager().isTableState(hri.getTable(),
378       ZooKeeperProtos.Table.State.DISABLED);
379     if (disabled){
380       LOG.info("The table " + hri.getTable()
381           + " was disabled.  Hence not proceeding.");
382       return false;
383     }
384     if (hri.isOffline() && hri.isSplit()) {
385       //HBASE-7721: Split parent and daughters are inserted into hbase:meta as an atomic operation.
386       //If the meta scanner saw the parent split, then it should see the daughters as assigned
387       //to the dead server. We don't have to do anything.
388       return false;
389     }
390     boolean disabling = assignmentManager.getTableStateManager().isTableState(hri.getTable(),
391       ZooKeeperProtos.Table.State.DISABLING);
392     if (disabling) {
393       LOG.info("The table " + hri.getTable()
394           + " is disabled.  Hence not assigning region" + hri.getEncodedName());
395       return false;
396     }
397     return true;
398   }
399 }