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.procedure2;
019
020import static org.junit.jupiter.api.Assertions.assertEquals;
021import static org.junit.jupiter.api.Assertions.assertTrue;
022
023import java.io.IOException;
024import java.util.concurrent.atomic.AtomicInteger;
025import org.apache.hadoop.fs.FileSystem;
026import org.apache.hadoop.fs.Path;
027import org.apache.hadoop.hbase.HBaseCommonTestingUtil;
028import org.apache.hadoop.hbase.procedure2.ProcedureTestingUtility.NoopProcedure;
029import org.apache.hadoop.hbase.procedure2.store.ProcedureStore;
030import org.apache.hadoop.hbase.testclassification.MasterTests;
031import org.apache.hadoop.hbase.testclassification.MediumTests;
032import org.junit.jupiter.api.AfterEach;
033import org.junit.jupiter.api.BeforeEach;
034import org.junit.jupiter.api.Tag;
035import org.junit.jupiter.api.Test;
036import org.slf4j.Logger;
037import org.slf4j.LoggerFactory;
038
039@Tag(MasterTests.TAG)
040@Tag(MediumTests.TAG)
041public class TestStateMachineProcedure {
042
043  private static final Logger LOG = LoggerFactory.getLogger(TestStateMachineProcedure.class);
044
045  private static final Exception TEST_FAILURE_EXCEPTION = new Exception("test failure") {
046
047    private static final long serialVersionUID = 2147942238987041310L;
048
049    @Override
050    public boolean equals(final Object other) {
051      if (this == other) {
052        return true;
053      }
054
055      if (!(other instanceof Exception)) {
056        return false;
057      }
058
059      // we are going to serialize the exception in the test,
060      // so the instance comparison will not match
061      return getMessage().equals(((Exception) other).getMessage());
062    }
063
064    @Override
065    public int hashCode() {
066      return getMessage().hashCode();
067    }
068  };
069
070  private static final int PROCEDURE_EXECUTOR_SLOTS = 1;
071
072  private ProcedureExecutor<TestProcEnv> procExecutor;
073  private ProcedureStore procStore;
074
075  private HBaseCommonTestingUtil htu;
076  private FileSystem fs;
077  private Path testDir;
078  private Path logDir;
079
080  @BeforeEach
081  public void setUp() throws IOException {
082    htu = new HBaseCommonTestingUtil();
083    testDir = htu.getDataTestDir();
084    fs = testDir.getFileSystem(htu.getConfiguration());
085
086    logDir = new Path(testDir, "proc-logs");
087    procStore = ProcedureTestingUtility.createWalStore(htu.getConfiguration(), logDir);
088    procExecutor = new ProcedureExecutor<>(htu.getConfiguration(), new TestProcEnv(), procStore);
089    procStore.start(PROCEDURE_EXECUTOR_SLOTS);
090    ProcedureTestingUtility.initAndStartWorkers(procExecutor, PROCEDURE_EXECUTOR_SLOTS, true);
091  }
092
093  @AfterEach
094  public void tearDown() throws IOException {
095    ProcedureTestingUtility.setKillAndToggleBeforeStoreUpdate(procExecutor, false);
096    assertTrue(procExecutor.isRunning(), "expected executor to be running");
097
098    procExecutor.stop();
099    procStore.stop(false);
100    fs.delete(logDir, true);
101  }
102
103  @Test
104  public void testAbortStuckProcedure() throws InterruptedException {
105    try {
106      procExecutor.getEnvironment().loop = true;
107      TestSMProcedure proc = new TestSMProcedure();
108      long procId = procExecutor.submitProcedure(proc);
109      Thread.sleep(1000 + (int) (Math.random() * 4001));
110      proc.abort(procExecutor.getEnvironment());
111      ProcedureTestingUtility.waitProcedure(procExecutor, procId);
112      assertTrue(proc.isFailed());
113    } finally {
114      procExecutor.getEnvironment().loop = false;
115    }
116  }
117
118  @Test
119  public void testChildOnLastStep() {
120    long procId = procExecutor.submitProcedure(new TestSMProcedure());
121    ProcedureTestingUtility.waitProcedure(procExecutor, procId);
122    assertEquals(3, procExecutor.getEnvironment().execCount.get());
123    assertEquals(0, procExecutor.getEnvironment().rollbackCount.get());
124    ProcedureTestingUtility.assertProcNotFailed(procExecutor, procId);
125  }
126
127  @Test
128  public void testChildOnLastStepDoubleExecution() throws Exception {
129    ProcedureTestingUtility.setKillAndToggleBeforeStoreUpdate(procExecutor, true);
130    long procId = procExecutor.submitProcedure(new TestSMProcedure());
131    ProcedureTestingUtility.testRecoveryAndDoubleExecution(procExecutor, procId);
132    assertEquals(6, procExecutor.getEnvironment().execCount.get());
133    assertEquals(0, procExecutor.getEnvironment().rollbackCount.get());
134    ProcedureTestingUtility.assertProcNotFailed(procExecutor, procId);
135  }
136
137  @Test
138  public void testChildOnLastStepWithRollback() {
139    procExecutor.getEnvironment().triggerChildRollback = true;
140    long procId = procExecutor.submitProcedure(new TestSMProcedure());
141    ProcedureTestingUtility.waitProcedure(procExecutor, procId);
142    assertEquals(3, procExecutor.getEnvironment().execCount.get());
143    assertEquals(3, procExecutor.getEnvironment().rollbackCount.get());
144    Throwable cause = ProcedureTestingUtility.assertProcFailed(procExecutor, procId);
145    assertEquals(TEST_FAILURE_EXCEPTION, cause);
146  }
147
148  @Test
149  public void testChildNormalRollbackStateCount() {
150    procExecutor.getEnvironment().triggerChildRollback = true;
151    TestSMProcedureBadRollback testNormalRollback = new TestSMProcedureBadRollback();
152    long procId = procExecutor.submitProcedure(testNormalRollback);
153    ProcedureTestingUtility.waitProcedure(procExecutor, procId);
154    assertEquals(0, testNormalRollback.stateCount);
155  }
156
157  @Test
158  public void testChildBadRollbackStateCount() {
159    procExecutor.getEnvironment().triggerChildRollback = true;
160    TestSMProcedureBadRollback testBadRollback = new TestSMProcedureBadRollback();
161    long procId = procExecutor.submitProcedure(testBadRollback);
162    ProcedureTestingUtility.waitProcedure(procExecutor, procId);
163    assertEquals(0, testBadRollback.stateCount);
164  }
165
166  @Test
167  public void testChildOnLastStepWithRollbackDoubleExecution() throws Exception {
168    procExecutor.getEnvironment().triggerChildRollback = true;
169    ProcedureTestingUtility.setKillAndToggleBeforeStoreUpdate(procExecutor, true);
170    ProcedureTestingUtility.setKillAndToggleBeforeStoreUpdateInRollback(procExecutor, true);
171    long procId = procExecutor.submitProcedure(new TestSMProcedure());
172    ProcedureTestingUtility.testRecoveryAndDoubleExecution(procExecutor, procId, true);
173    assertEquals(6, procExecutor.getEnvironment().execCount.get());
174    assertEquals(6, procExecutor.getEnvironment().rollbackCount.get());
175    Throwable cause = ProcedureTestingUtility.assertProcFailed(procExecutor, procId);
176    assertEquals(TEST_FAILURE_EXCEPTION, cause);
177  }
178
179  public enum TestSMProcedureState {
180    STEP_1,
181    STEP_2
182  }
183
184  public static class TestSMProcedure
185    extends StateMachineProcedure<TestProcEnv, TestSMProcedureState> {
186    @Override
187    protected Flow executeFromState(TestProcEnv env, TestSMProcedureState state) {
188      LOG.info("EXEC " + state + " " + this);
189      env.execCount.incrementAndGet();
190      switch (state) {
191        case STEP_1:
192          if (!env.loop) {
193            setNextState(TestSMProcedureState.STEP_2);
194          }
195          break;
196        case STEP_2:
197          addChildProcedure(new SimpleChildProcedure());
198          return Flow.NO_MORE_STATE;
199      }
200      return Flow.HAS_MORE_STATE;
201    }
202
203    @Override
204    protected boolean isRollbackSupported(TestSMProcedureState state) {
205      return true;
206    }
207
208    @Override
209    protected void rollbackState(TestProcEnv env, TestSMProcedureState state) {
210      LOG.info("ROLLBACK " + state + " " + this);
211      env.rollbackCount.incrementAndGet();
212    }
213
214    @Override
215    protected TestSMProcedureState getState(int stateId) {
216      return TestSMProcedureState.values()[stateId];
217    }
218
219    @Override
220    protected int getStateId(TestSMProcedureState state) {
221      return state.ordinal();
222    }
223
224    @Override
225    protected TestSMProcedureState getInitialState() {
226      return TestSMProcedureState.STEP_1;
227    }
228  }
229
230  public static class TestSMProcedureBadRollback
231    extends StateMachineProcedure<TestProcEnv, TestSMProcedureState> {
232    @Override
233    protected Flow executeFromState(TestProcEnv env, TestSMProcedureState state) {
234      LOG.info("EXEC " + state + " " + this);
235      env.execCount.incrementAndGet();
236      switch (state) {
237        case STEP_1:
238          if (!env.loop) {
239            setNextState(TestSMProcedureState.STEP_2);
240          }
241          break;
242        case STEP_2:
243          addChildProcedure(new SimpleChildProcedure());
244          return Flow.NO_MORE_STATE;
245      }
246      return Flow.HAS_MORE_STATE;
247    }
248
249    @Override
250    protected boolean isRollbackSupported(TestSMProcedureState state) {
251      return true;
252    }
253
254    @Override
255    protected void rollbackState(TestProcEnv env, TestSMProcedureState state) {
256      LOG.info("ROLLBACK " + state + " " + this);
257      env.rollbackCount.incrementAndGet();
258    }
259
260    @Override
261    protected TestSMProcedureState getState(int stateId) {
262      return TestSMProcedureState.values()[stateId];
263    }
264
265    @Override
266    protected int getStateId(TestSMProcedureState state) {
267      return state.ordinal();
268    }
269
270    @Override
271    protected TestSMProcedureState getInitialState() {
272      return TestSMProcedureState.STEP_1;
273    }
274
275    @Override
276    protected void rollback(final TestProcEnv env) throws IOException, InterruptedException {
277      if (isEofState()) {
278        stateCount--;
279      }
280      try {
281        updateTimestamp();
282        rollbackState(env, getCurrentState());
283        throw new IOException();
284      } catch (IOException e) {
285        // do nothing for now
286      } finally {
287        stateCount--;
288        updateTimestamp();
289      }
290    }
291  }
292
293  public static class SimpleChildProcedure extends NoopProcedure<TestProcEnv> {
294    @Override
295    protected Procedure<TestProcEnv>[] execute(TestProcEnv env) {
296      LOG.info("EXEC " + this);
297      env.execCount.incrementAndGet();
298      if (env.triggerChildRollback) {
299        setFailure("test-failure", TEST_FAILURE_EXCEPTION);
300      }
301      return null;
302    }
303
304    @Override
305    protected void rollback(TestProcEnv env) {
306      LOG.info("ROLLBACK " + this);
307      env.rollbackCount.incrementAndGet();
308    }
309  }
310
311  public static class TestProcEnv {
312    AtomicInteger execCount = new AtomicInteger(0);
313    AtomicInteger rollbackCount = new AtomicInteger(0);
314    boolean triggerChildRollback = false;
315    boolean loop = false;
316  }
317}