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.conf.Configuration;
024import org.apache.hadoop.hbase.HConstants;
025import org.apache.hadoop.hbase.client.RegionInfo;
026import org.apache.hadoop.hbase.client.TableDescriptor;
027import org.apache.hadoop.hbase.executor.EventHandler;
028import org.apache.hadoop.hbase.executor.EventType;
029import org.apache.hadoop.hbase.regionserver.HRegion;
030import org.apache.hadoop.hbase.regionserver.HRegionServer;
031import org.apache.hadoop.hbase.regionserver.Region;
032import org.apache.hadoop.hbase.regionserver.RegionServerServices.PostOpenDeployContext;
033import org.apache.hadoop.hbase.regionserver.RegionServerServices.RegionStateTransitionContext;
034import org.apache.hadoop.hbase.util.RetryCounter;
035import org.apache.yetus.audience.InterfaceAudience;
036import org.slf4j.Logger;
037import org.slf4j.LoggerFactory;
038
039import org.apache.hadoop.hbase.shaded.protobuf.generated.RegionServerStatusProtos.RegionStateTransition.TransitionCode;
040
041/**
042 * Handles opening of a region on a region server.
043 * <p/>
044 * Just done the same thing with the old {@link OpenRegionHandler}, with some modifications on
045 * fencing and retrying. But we need to keep the {@link OpenRegionHandler} as is to keep compatible
046 * with the zk less assignment for 1.x, otherwise it is not possible to do rolling upgrade.
047 */
048@InterfaceAudience.Private
049public class AssignRegionHandler extends EventHandler {
050
051  private static final Logger LOG = LoggerFactory.getLogger(AssignRegionHandler.class);
052
053  private final RegionInfo regionInfo;
054
055  private final long openProcId;
056
057  private final TableDescriptor tableDesc;
058
059  private final long masterSystemTime;
060
061  private final RetryCounter retryCounter;
062
063  public AssignRegionHandler(HRegionServer server, RegionInfo regionInfo, long openProcId,
064    @Nullable TableDescriptor tableDesc, long masterSystemTime, EventType eventType) {
065    super(server, eventType);
066    this.regionInfo = regionInfo;
067    this.openProcId = openProcId;
068    this.tableDesc = tableDesc;
069    this.masterSystemTime = masterSystemTime;
070    this.retryCounter = HandlerUtil.getRetryCounter();
071  }
072
073  private HRegionServer getServer() {
074    return (HRegionServer) server;
075  }
076
077  private void cleanUpAndReportFailure(IOException error) throws IOException {
078    LOG.warn("Failed to open region {}, will report to master", regionInfo.getRegionNameAsString(),
079      error);
080    HRegionServer rs = getServer();
081    rs.getRegionsInTransitionInRS().remove(regionInfo.getEncodedNameAsBytes(), Boolean.TRUE);
082    if (
083      !rs.reportRegionStateTransition(new RegionStateTransitionContext(TransitionCode.FAILED_OPEN,
084        HConstants.NO_SEQNUM, openProcId, masterSystemTime, regionInfo))
085    ) {
086      throw new IOException(
087        "Failed to report failed open to master: " + regionInfo.getRegionNameAsString());
088    }
089  }
090
091  @Override
092  public void process() throws IOException {
093    HRegionServer rs = getServer();
094    String encodedName = regionInfo.getEncodedName();
095    byte[] encodedNameBytes = regionInfo.getEncodedNameAsBytes();
096    String regionName = regionInfo.getRegionNameAsString();
097    Region onlineRegion = rs.getRegion(encodedName);
098    if (onlineRegion != null) {
099      LOG.warn("Received OPEN for {} which is already online", regionName);
100      // Just follow the old behavior, do we need to call reportRegionStateTransition? Maybe not?
101      // For normal case, it could happen that the rpc call to schedule this handler is succeeded,
102      // but before returning to master the connection is broken. And when master tries again, we
103      // have already finished the opening. For this case we do not need to call
104      // reportRegionStateTransition any more.
105      return;
106    }
107    Boolean previous = rs.getRegionsInTransitionInRS().putIfAbsent(encodedNameBytes, Boolean.TRUE);
108    if (previous != null) {
109      if (previous) {
110        // The region is opening and this maybe a retry on the rpc call, it is safe to ignore it.
111        LOG.info("Receiving OPEN for {} which we are already trying to OPEN"
112          + " - ignoring this new request for this region.", regionName);
113      } else {
114        // The region is closing. This is possible as we will update the region state to CLOSED when
115        // calling reportRegionStateTransition, so the HMaster will think the region is offline,
116        // before we actually close the region, as reportRegionStateTransition is part of the
117        // closing process.
118        long backoff = retryCounter.getBackoffTimeAndIncrementAttempts();
119        LOG.info("Receiving OPEN for {} which we are trying to close, try again after {}ms",
120          regionName, backoff);
121        rs.getExecutorService().delayedSubmit(this, backoff, TimeUnit.MILLISECONDS);
122      }
123      return;
124    }
125    LOG.info("Open {}", regionName);
126    HRegion region;
127    try {
128      TableDescriptor htd =
129        tableDesc != null ? tableDesc : rs.getTableDescriptors().get(regionInfo.getTable());
130      if (htd == null) {
131        throw new IOException("Missing table descriptor for " + regionName);
132      }
133      // pass null for the last parameter, which used to be a CancelableProgressable, as now the
134      // opening can not be interrupted by a close request any more.
135      Configuration conf = rs.getConfiguration();
136      region = HRegion.openHRegion(regionInfo, htd, rs.getWAL(regionInfo), conf, rs, null);
137    } catch (IOException e) {
138      cleanUpAndReportFailure(e);
139      return;
140    }
141    // From here on out, this is PONR. We can not revert back. The only way to address an
142    // exception from here on out is to abort the region server.
143    rs.postOpenDeployTasks(new PostOpenDeployContext(region, openProcId, masterSystemTime));
144    rs.addRegion(region);
145    LOG.info("Opened {}", regionName);
146    // Cache the open region procedure id after report region transition succeed.
147    rs.finishRegionProcedure(openProcId);
148    Boolean current = rs.getRegionsInTransitionInRS().remove(regionInfo.getEncodedNameAsBytes());
149    if (current == null) {
150      // Should NEVER happen, but let's be paranoid.
151      LOG.error("Bad state: we've just opened {} which was NOT in transition", regionName);
152    } else if (!current) {
153      // Should NEVER happen, but let's be paranoid.
154      LOG.error("Bad state: we've just opened {} which was closing", regionName);
155    }
156  }
157
158  @Override
159  protected void handleException(Throwable t) {
160    LOG.warn("Fatal error occurred while opening region {}, aborting...",
161      regionInfo.getRegionNameAsString(), t);
162    // Clear any reference in getServer().getRegionsInTransitionInRS() otherwise can hold up
163    // regionserver abort on cluster shutdown. HBASE-23984.
164    getServer().getRegionsInTransitionInRS().remove(regionInfo.getEncodedNameAsBytes());
165    getServer().abort(
166      "Failed to open region " + regionInfo.getRegionNameAsString() + " and can not recover", t);
167  }
168
169  public static AssignRegionHandler create(HRegionServer server, RegionInfo regionInfo,
170    long openProcId, TableDescriptor tableDesc, long masterSystemTime) {
171    EventType eventType;
172    if (regionInfo.isMetaRegion()) {
173      eventType = EventType.M_RS_OPEN_META;
174    } else if (
175      regionInfo.getTable().isSystemTable()
176        || (tableDesc != null && tableDesc.getPriority() >= HConstants.ADMIN_QOS)
177    ) {
178      eventType = EventType.M_RS_OPEN_PRIORITY_REGION;
179    } else {
180      eventType = EventType.M_RS_OPEN_REGION;
181    }
182    return new AssignRegionHandler(server, regionInfo, openProcId, tableDesc, masterSystemTime,
183      eventType);
184  }
185}