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.Assert.assertEquals;
021import static org.junit.Assert.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.HBaseClassTestRule;
028import org.apache.hadoop.hbase.HBaseCommonTestingUtil;
029import org.apache.hadoop.hbase.procedure2.ProcedureTestingUtility.NoopProcedure;
030import org.apache.hadoop.hbase.procedure2.store.ProcedureStore;
031import org.apache.hadoop.hbase.testclassification.MasterTests;
032import org.apache.hadoop.hbase.testclassification.MediumTests;
033import org.junit.After;
034import org.junit.Before;
035import org.junit.ClassRule;
036import org.junit.Test;
037import org.junit.experimental.categories.Category;
038import org.slf4j.Logger;
039import org.slf4j.LoggerFactory;
040
041@Category({MasterTests.class, MediumTests.class})
042public class TestStateMachineProcedure {
043  @ClassRule
044  public static final HBaseClassTestRule CLASS_RULE =
045      HBaseClassTestRule.forClass(TestStateMachineProcedure.class);
046
047  private static final Logger LOG = LoggerFactory.getLogger(TestStateMachineProcedure.class);
048
049  private static final Exception TEST_FAILURE_EXCEPTION = new Exception("test failure") {
050
051    private static final long serialVersionUID = 2147942238987041310L;
052
053    @Override
054    public boolean equals(final Object other) {
055      if (this == other) {
056        return true;
057      }
058
059      if (!(other instanceof Exception)) {
060        return false;
061      }
062
063      // we are going to serialize the exception in the test,
064      // so the instance comparison will not match
065      return getMessage().equals(((Exception)other).getMessage());
066    }
067
068    @Override
069    public int hashCode() {
070      return getMessage().hashCode();
071    }
072  };
073
074  private static final int PROCEDURE_EXECUTOR_SLOTS = 1;
075
076  private ProcedureExecutor<TestProcEnv> procExecutor;
077  private ProcedureStore procStore;
078
079  private HBaseCommonTestingUtil htu;
080  private FileSystem fs;
081  private Path testDir;
082  private Path logDir;
083
084  @Before
085  public void setUp() throws IOException {
086    htu = new HBaseCommonTestingUtil();
087    testDir = htu.getDataTestDir();
088    fs = testDir.getFileSystem(htu.getConfiguration());
089
090    logDir = new Path(testDir, "proc-logs");
091    procStore = ProcedureTestingUtility.createWalStore(htu.getConfiguration(), logDir);
092    procExecutor = new ProcedureExecutor<>(htu.getConfiguration(), new TestProcEnv(), procStore);
093    procStore.start(PROCEDURE_EXECUTOR_SLOTS);
094    ProcedureTestingUtility.initAndStartWorkers(procExecutor, PROCEDURE_EXECUTOR_SLOTS, true);
095  }
096
097  @After
098  public void tearDown() throws IOException {
099    ProcedureTestingUtility.setKillAndToggleBeforeStoreUpdate(procExecutor, false);
100    assertTrue("expected executor to be running", procExecutor.isRunning());
101
102    procExecutor.stop();
103    procStore.stop(false);
104    fs.delete(logDir, true);
105  }
106
107  @Test
108  public void testAbortStuckProcedure() throws InterruptedException {
109    try {
110      procExecutor.getEnvironment().loop = true;
111      TestSMProcedure proc = new TestSMProcedure();
112      long procId = procExecutor.submitProcedure(proc);
113      Thread.sleep(1000 + (int) (Math.random() * 4001));
114      proc.abort(procExecutor.getEnvironment());
115      ProcedureTestingUtility.waitProcedure(procExecutor, procId);
116      assertEquals(true, proc.isFailed());
117    } finally {
118      procExecutor.getEnvironment().loop = false;
119    }
120  }
121
122  @Test
123  public void testChildOnLastStep() {
124    long procId = procExecutor.submitProcedure(new TestSMProcedure());
125    ProcedureTestingUtility.waitProcedure(procExecutor, procId);
126    assertEquals(3, procExecutor.getEnvironment().execCount.get());
127    assertEquals(0, procExecutor.getEnvironment().rollbackCount.get());
128    ProcedureTestingUtility.assertProcNotFailed(procExecutor, procId);
129  }
130
131  @Test
132  public void testChildOnLastStepDoubleExecution() throws Exception {
133    ProcedureTestingUtility.setKillAndToggleBeforeStoreUpdate(procExecutor, true);
134    long procId = procExecutor.submitProcedure(new TestSMProcedure());
135    ProcedureTestingUtility.testRecoveryAndDoubleExecution(procExecutor, procId);
136    assertEquals(6, procExecutor.getEnvironment().execCount.get());
137    assertEquals(0, procExecutor.getEnvironment().rollbackCount.get());
138    ProcedureTestingUtility.assertProcNotFailed(procExecutor, procId);
139  }
140
141  @Test
142  public void testChildOnLastStepWithRollback() {
143    procExecutor.getEnvironment().triggerChildRollback = true;
144    long procId = procExecutor.submitProcedure(new TestSMProcedure());
145    ProcedureTestingUtility.waitProcedure(procExecutor, procId);
146    assertEquals(3, procExecutor.getEnvironment().execCount.get());
147    assertEquals(3, procExecutor.getEnvironment().rollbackCount.get());
148    Throwable cause = ProcedureTestingUtility.assertProcFailed(procExecutor, procId);
149    assertEquals(TEST_FAILURE_EXCEPTION, cause);
150  }
151
152  @Test
153  public void testChildNormalRollbackStateCount() {
154    procExecutor.getEnvironment().triggerChildRollback = true;
155    TestSMProcedureBadRollback testNormalRollback = new TestSMProcedureBadRollback();
156    long procId = procExecutor.submitProcedure(testNormalRollback);
157    ProcedureTestingUtility.waitProcedure(procExecutor, procId);
158    assertEquals(0, testNormalRollback.stateCount);
159  }
160
161  @Test
162  public void testChildBadRollbackStateCount() {
163    procExecutor.getEnvironment().triggerChildRollback = true;
164    TestSMProcedureBadRollback testBadRollback = new TestSMProcedureBadRollback();
165    long procId = procExecutor.submitProcedure(testBadRollback);
166    ProcedureTestingUtility.waitProcedure(procExecutor, procId);
167    assertEquals(0, testBadRollback.stateCount);
168  }
169
170  @Test
171  public void testChildOnLastStepWithRollbackDoubleExecution() throws Exception {
172    procExecutor.getEnvironment().triggerChildRollback = true;
173    ProcedureTestingUtility.setKillAndToggleBeforeStoreUpdate(procExecutor, true);
174    long procId = procExecutor.submitProcedure(new TestSMProcedure());
175    ProcedureTestingUtility.testRecoveryAndDoubleExecution(procExecutor, procId, true);
176    assertEquals(6, procExecutor.getEnvironment().execCount.get());
177    assertEquals(6, procExecutor.getEnvironment().rollbackCount.get());
178    Throwable cause = ProcedureTestingUtility.assertProcFailed(procExecutor, procId);
179    assertEquals(TEST_FAILURE_EXCEPTION, cause);
180  }
181
182  public enum TestSMProcedureState { STEP_1, STEP_2 }
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    @Override
249    protected void rollbackState(TestProcEnv env, TestSMProcedureState state) {
250      LOG.info("ROLLBACK " + state + " " + this);
251      env.rollbackCount.incrementAndGet();
252    }
253
254    @Override
255    protected TestSMProcedureState getState(int stateId) {
256      return TestSMProcedureState.values()[stateId];
257    }
258
259    @Override
260    protected int getStateId(TestSMProcedureState state) {
261      return state.ordinal();
262    }
263
264    @Override
265    protected TestSMProcedureState getInitialState() {
266      return TestSMProcedureState.STEP_1;
267    }
268
269    @Override
270    protected void rollback(final TestProcEnv env)
271            throws IOException, InterruptedException {
272      if (isEofState()) {
273        stateCount--;
274      }
275      try {
276        updateTimestamp();
277        rollbackState(env, getCurrentState());
278        throw new IOException();
279      } catch(IOException e) {
280        //do nothing for now
281      } finally {
282        stateCount--;
283        updateTimestamp();
284      }
285    }
286  }
287
288  public static class SimpleChildProcedure extends NoopProcedure<TestProcEnv> {
289    @Override
290    protected Procedure<TestProcEnv>[] execute(TestProcEnv env) {
291      LOG.info("EXEC " + this);
292      env.execCount.incrementAndGet();
293      if (env.triggerChildRollback) {
294        setFailure("test-failure", TEST_FAILURE_EXCEPTION);
295      }
296      return null;
297    }
298
299    @Override
300    protected void rollback(TestProcEnv env) {
301      LOG.info("ROLLBACK " + this);
302      env.rollbackCount.incrementAndGet();
303    }
304  }
305
306  public static class TestProcEnv {
307    AtomicInteger execCount = new AtomicInteger(0);
308    AtomicInteger rollbackCount = new AtomicInteger(0);
309    boolean triggerChildRollback = false;
310    boolean loop = false;
311  }
312}