001/*
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *     http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018package org.apache.hadoop.hbase.regionserver.handler;
019
020import edu.umd.cs.findbugs.annotations.Nullable;
021import java.io.IOException;
022import java.util.concurrent.TimeUnit;
023import org.apache.hadoop.hbase.HConstants;
024import org.apache.hadoop.hbase.ServerName;
025import org.apache.hadoop.hbase.executor.EventHandler;
026import org.apache.hadoop.hbase.executor.EventType;
027import org.apache.hadoop.hbase.regionserver.HRegion;
028import org.apache.hadoop.hbase.regionserver.HRegionServer;
029import org.apache.hadoop.hbase.regionserver.Region;
030import org.apache.hadoop.hbase.regionserver.RegionServerServices.RegionStateTransitionContext;
031import org.apache.hadoop.hbase.util.Bytes;
032import org.apache.hadoop.hbase.util.RetryCounter;
033import org.apache.yetus.audience.InterfaceAudience;
034import org.slf4j.Logger;
035import org.slf4j.LoggerFactory;
036import org.slf4j.MDC;
037
038import org.apache.hadoop.hbase.shaded.protobuf.generated.RegionServerStatusProtos.RegionStateTransition.TransitionCode;
039
040/**
041 * Handles closing of a region on a region server.
042 * <p/>
043 * Just done the same thing with the old {@link CloseRegionHandler}, with some modifications on
044 * fencing and retrying. But we need to keep the {@link CloseRegionHandler} as is to keep compatible
045 * with the zk less assignment for 1.x, otherwise it is not possible to do rolling upgrade.
046 */
047@InterfaceAudience.Private
048public class UnassignRegionHandler extends EventHandler {
049
050  private static final Logger LOG = LoggerFactory.getLogger(UnassignRegionHandler.class);
051
052  private final String encodedName;
053
054  private final long closeProcId;
055  // If true, the hosting server is aborting. Region close process is different
056  // when we are aborting.
057  // TODO: not used yet, we still use the old CloseRegionHandler when aborting
058  private final boolean abort;
059
060  private final ServerName destination;
061
062  private final RetryCounter retryCounter;
063
064  private boolean evictCache;
065
066  public UnassignRegionHandler(HRegionServer server, String encodedName, long closeProcId,
067    boolean abort, @Nullable ServerName destination, EventType eventType) {
068    this(server, encodedName, closeProcId, abort, destination, eventType, false);
069  }
070
071  public UnassignRegionHandler(HRegionServer server, String encodedName, long closeProcId,
072    boolean abort, @Nullable ServerName destination, EventType eventType, boolean evictCache) {
073    super(server, eventType);
074    this.encodedName = encodedName;
075    this.closeProcId = closeProcId;
076    this.abort = abort;
077    this.destination = destination;
078    this.retryCounter = HandlerUtil.getRetryCounter();
079    this.evictCache = evictCache;
080  }
081
082  private HRegionServer getServer() {
083    return (HRegionServer) server;
084  }
085
086  @Override
087  public void process() throws IOException {
088    MDC.put("pid", Long.toString(closeProcId));
089    HRegionServer rs = getServer();
090    byte[] encodedNameBytes = Bytes.toBytes(encodedName);
091    Boolean previous = rs.getRegionsInTransitionInRS().putIfAbsent(encodedNameBytes, Boolean.FALSE);
092    if (previous != null) {
093      if (previous) {
094        // This could happen as we will update the region state to OPEN when calling
095        // reportRegionStateTransition, so the HMaster will think the region is online, before we
096        // actually open the region, as reportRegionStateTransition is part of the opening process.
097        long backoff = retryCounter.getBackoffTimeAndIncrementAttempts();
098        LOG.warn(
099          "Received CLOSE for {} which we are already " + "trying to OPEN; try again after {}ms",
100          encodedName, backoff);
101        rs.getExecutorService().delayedSubmit(this, backoff, TimeUnit.MILLISECONDS);
102      } else {
103        LOG.info(
104          "Received CLOSE for {} which we are already trying to CLOSE," + " but not completed yet",
105          encodedName);
106      }
107      return;
108    }
109    HRegion region = rs.getRegion(encodedName);
110    if (region == null) {
111      LOG.debug("Received CLOSE for {} which is not ONLINE and we're not opening/closing.",
112        encodedName);
113      rs.getRegionsInTransitionInRS().remove(encodedNameBytes, Boolean.FALSE);
114      return;
115    }
116    String regionName = region.getRegionInfo().getEncodedName();
117    LOG.info("Close {}", regionName);
118    if (region.getCoprocessorHost() != null) {
119      // XXX: The behavior is a bit broken. At master side there is no FAILED_CLOSE state, so if
120      // there are exception thrown from the CP, we can not report the error to master, and if
121      // here we just return without calling reportRegionStateTransition, the TRSP at master side
122      // will hang there for ever. So here if the CP throws an exception out, the only way is to
123      // abort the RS...
124      region.getCoprocessorHost().preClose(abort);
125    }
126    // This should be true only in the case of splits/merges closing the parent regions, as
127    // there's no point on keep blocks for those region files. As hbase.rs.evictblocksonclose is
128    // false by default we don't bother overriding it if evictCache is false.
129    if (evictCache) {
130      region.getStores().forEach(s -> s.getCacheConfig().setEvictOnClose(true));
131    }
132    if (region.close(abort) == null) {
133      // XXX: Is this still possible? The old comment says about split, but now split is done at
134      // master side, so...
135      LOG.warn("Can't close {}, already closed during close()", regionName);
136      rs.getRegionsInTransitionInRS().remove(encodedNameBytes, Boolean.FALSE);
137      return;
138    }
139
140    rs.removeRegion(region, destination);
141    if (
142      !rs.reportRegionStateTransition(new RegionStateTransitionContext(TransitionCode.CLOSED,
143        HConstants.NO_SEQNUM, closeProcId, -1, region.getRegionInfo()))
144    ) {
145      throw new IOException("Failed to report close to master: " + regionName);
146    }
147    // Cache the close region procedure id after report region transition succeed.
148    rs.finishRegionProcedure(closeProcId);
149    rs.getRegionsInTransitionInRS().remove(encodedNameBytes, Boolean.FALSE);
150    LOG.info("Closed {}", regionName);
151  }
152
153  @Override
154  protected void handleException(Throwable t) {
155    LOG.warn("Fatal error occurred while closing region {}, aborting...", encodedName, t);
156    // Clear any reference in getServer().getRegionsInTransitionInRS() otherwise can hold up
157    // regionserver abort on cluster shutdown. HBASE-23984.
158    getServer().getRegionsInTransitionInRS().remove(Bytes.toBytes(this.encodedName));
159    getServer().abort("Failed to close region " + encodedName + " and can not recover", t);
160  }
161
162  public static UnassignRegionHandler create(HRegionServer server, String encodedName,
163    long closeProcId, boolean abort, @Nullable ServerName destination, boolean evictCache) {
164    // Just try our best to determine whether it is for closing meta. It is not the end of the world
165    // if we put the handler into a wrong executor.
166    Region region = server.getRegion(encodedName);
167    EventType eventType = region != null && region.getRegionInfo().isMetaRegion()
168      ? EventType.M_RS_CLOSE_META
169      : EventType.M_RS_CLOSE_REGION;
170    return new UnassignRegionHandler(server, encodedName, closeProcId, abort, destination,
171      eventType, evictCache);
172  }
173}