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.master.assignment;
019
020import static org.junit.jupiter.api.Assertions.assertTrue;
021
022import java.io.IOException;
023import java.util.concurrent.CountDownLatch;
024import java.util.concurrent.atomic.AtomicInteger;
025import org.apache.hadoop.conf.Configuration;
026import org.apache.hadoop.hbase.HBaseTestingUtil;
027import org.apache.hadoop.hbase.HConstants;
028import org.apache.hadoop.hbase.PleaseHoldException;
029import org.apache.hadoop.hbase.StartTestingClusterOption;
030import org.apache.hadoop.hbase.TableName;
031import org.apache.hadoop.hbase.client.RegionInfo;
032import org.apache.hadoop.hbase.master.HMaster;
033import org.apache.hadoop.hbase.master.MasterServices;
034import org.apache.hadoop.hbase.master.RegionPlan;
035import org.apache.hadoop.hbase.master.RegionState;
036import org.apache.hadoop.hbase.master.ServerManager;
037import org.apache.hadoop.hbase.master.procedure.MasterProcedureEnv;
038import org.apache.hadoop.hbase.master.region.MasterRegion;
039import org.apache.hadoop.hbase.procedure2.ProcedureExecutor;
040import org.apache.hadoop.hbase.regionserver.HRegionServer;
041import org.apache.hadoop.hbase.testclassification.MasterTests;
042import org.apache.hadoop.hbase.testclassification.MediumTests;
043import org.apache.hadoop.hbase.util.Bytes;
044import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
045import org.apache.hadoop.hbase.util.JVMClusterUtil.MasterThread;
046import org.junit.jupiter.api.AfterAll;
047import org.junit.jupiter.api.BeforeAll;
048import org.junit.jupiter.api.Tag;
049import org.junit.jupiter.api.Test;
050
051import org.apache.hadoop.hbase.shaded.protobuf.ProtobufUtil;
052import org.apache.hadoop.hbase.shaded.protobuf.generated.RegionServerStatusProtos.RegionStateTransition;
053import org.apache.hadoop.hbase.shaded.protobuf.generated.RegionServerStatusProtos.RegionStateTransition.TransitionCode;
054import org.apache.hadoop.hbase.shaded.protobuf.generated.RegionServerStatusProtos.ReportRegionStateTransitionRequest;
055import org.apache.hadoop.hbase.shaded.protobuf.generated.RegionServerStatusProtos.ReportRegionStateTransitionResponse;
056
057/**
058 * A region open started by one active master must still complete after a failover to a master whose
059 * clock is behind, i.e. whose active time is lower than the active time sent with the open request.
060 */
061@Tag(MasterTests.TAG)
062@Tag(MediumTests.TAG)
063public class TestOpenRegionReportAfterFailoverToMasterWithClockBehind {
064
065  private static final HBaseTestingUtil UTIL = new HBaseTestingUtil();
066
067  private static final TableName NAME = TableName.valueOf("ClockBehind");
068
069  private static final byte[] CF = Bytes.toBytes("cf");
070
071  private static volatile CountDownLatch ARRIVE;
072
073  /** The master that holds OPENED reports for the table until RESUME. */
074  private static volatile MasterServices HOLDING_MASTER;
075
076  private static volatile CountDownLatch RESUME;
077
078  /** How far behind the clock of the next active master is, 0 for no skew. */
079  private static volatile long SKEW_MS;
080
081  private static final AtomicInteger SKEWED_CALLS = new AtomicInteger();
082
083  private static final class AssignmentManagerForTest extends AssignmentManager {
084
085    public AssignmentManagerForTest(MasterServices master, MasterRegion masterRegion) {
086      super(master, masterRegion);
087    }
088
089    @Override
090    public ReportRegionStateTransitionResponse reportRegionStateTransition(
091      ReportRegionStateTransitionRequest req) throws PleaseHoldException {
092      RegionStateTransition transition = req.getTransition(0);
093      if (
094        getMaster() == HOLDING_MASTER && transition.getTransitionCode() == TransitionCode.OPENED
095          && ProtobufUtil.toTableName(transition.getRegionInfo(0).getTableName()).equals(NAME)
096      ) {
097        // hold every OPENED report on the old active master until the next active master is up,
098        // then fail it with PleaseHoldException, so the region server sends it again to the
099        // active master
100        ARRIVE.countDown();
101        try {
102          RESUME.await();
103        } catch (InterruptedException e) {
104          Thread.currentThread().interrupt();
105        }
106        throw new PleaseHoldException("master is gone");
107      }
108      return super.reportRegionStateTransition(req);
109    }
110  }
111
112  public static final class HMasterForTest extends HMaster {
113
114    public HMasterForTest(Configuration conf) throws IOException {
115      super(conf);
116    }
117
118    @Override
119    protected long getCurrentTimeForActiveTime() {
120      long skew = SKEW_MS;
121      if (skew > 0) {
122        SKEWED_CALLS.incrementAndGet();
123      }
124      return super.getCurrentTimeForActiveTime() - skew;
125    }
126
127    @Override
128    protected AssignmentManager createAssignmentManager(MasterServices master,
129      MasterRegion masterRegion) {
130      return new AssignmentManagerForTest(master, masterRegion);
131    }
132  }
133
134  @BeforeAll
135  public static void setUp() throws Exception {
136    Configuration conf = UTIL.getConfiguration();
137    conf.setClass(HConstants.MASTER_IMPL, HMasterForTest.class, HMaster.class);
138    // the skew below is more than the time between the two masters becoming active, which is
139    // longer than the default max clock skew on a slow test machine
140    conf.setLong(ServerManager.MAX_CLOCK_SKEW_MS, 10 * 60 * 1000);
141    UTIL.startMiniCluster(
142      StartTestingClusterOption.builder().numMasters(2).numRegionServers(2).build());
143    UTIL.createTable(NAME, CF);
144    UTIL.waitTableAvailable(NAME);
145    UTIL.getAdmin().balancerSwitch(false, true);
146  }
147
148  @AfterAll
149  public static void tearDown() throws Exception {
150    SKEW_MS = 0;
151    if (RESUME != null) {
152      RESUME.countDown();
153    }
154    // The old active master still sees itself as active until it aborts, which can be after the
155    // test. Stop it, or the mini cluster may send the cluster shutdown to it instead of the new
156    // active master, and wait for the new active master forever.
157    if (HOLDING_MASTER != null) {
158      HOLDING_MASTER.stop("Stopping the old active master");
159    }
160    UTIL.shutdownMiniCluster();
161  }
162
163  @Test
164  public void testOpenCompletesAfterFailoverToMasterWithClockBehind() throws Exception {
165    HMaster oldMaster = UTIL.getMiniHBaseCluster().getMaster();
166    long oldActiveTime = oldMaster.getMasterActiveTime();
167    RegionInfo region = UTIL.getMiniHBaseCluster().getRegions(NAME).get(0).getRegionInfo();
168    HRegionServer rs1 = UTIL.getRSForFirstRegionInTable(NAME);
169    HRegionServer rs2 = UTIL.getOtherRegionServer(rs1);
170
171    ARRIVE = new CountDownLatch(1);
172    RESUME = new CountDownLatch(1);
173    HOLDING_MASTER = oldMaster;
174    oldMaster.getAssignmentManager()
175      .moveAsync(new RegionPlan(region, rs1.getServerName(), rs2.getServerName()));
176    // rs2 has opened the region and is reporting OPENED, with the old master's active time
177    ARRIVE.await();
178
179    // the next active master's clock is behind by more than the time since the old master became
180    // active, so its active time will be lower than the one rs2 is reporting with
181    SKEW_MS = EnvironmentEdgeManager.currentTime() - oldActiveTime + 60_000;
182    oldMaster.getZooKeeper().close();
183    UTIL.waitFor(120_000,
184      () -> getNewActiveMaster(oldMaster) != null && getNewActiveMaster(oldMaster).isInitialized());
185    SKEW_MS = 0;
186    assertTrue(SKEWED_CALLS.get() > 0, "The new active master did not read the skewed clock");
187    RESUME.countDown();
188
189    HMaster newMaster = getNewActiveMaster(oldMaster);
190    ProcedureExecutor<MasterProcedureEnv> procExec = newMaster.getMasterProcedureExecutor();
191    UTIL.waitFor(60_000,
192      () -> procExec.getProcedures().stream().anyMatch(p -> p instanceof OpenRegionProcedure
193        && ((OpenRegionProcedure) p).region.getTable().equals(NAME)));
194    long procId =
195      procExec.getProcedures().stream()
196        .filter(p -> p instanceof OpenRegionProcedure
197          && ((OpenRegionProcedure) p).region.getTable().equals(NAME))
198        .findFirst().get().getProcId();
199    // rs2 keeps reporting OPENED with the old master's active time; the new master must accept it
200    UTIL.waitFor(60_000, () -> procExec.isFinished(procId));
201    UTIL.waitFor(60_000, () -> {
202      RegionState state = newMaster.getAssignmentManager().getRegionStates().getRegionState(region);
203      return state != null && state.isOpened() && rs2.getServerName().equals(state.getServerName());
204    });
205    assertTrue(newMaster.getMasterActiveTime() > oldActiveTime,
206      "Active time went backwards: " + newMaster.getMasterActiveTime() + " <= " + oldActiveTime);
207  }
208
209  private static HMaster getNewActiveMaster(HMaster oldMaster) {
210    for (MasterThread mt : UTIL.getMiniHBaseCluster().getMasterThreads()) {
211      if (mt.getMaster() != oldMaster && mt.getMaster().isActiveMaster()) {
212        return mt.getMaster();
213      }
214    }
215    return null;
216  }
217}