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.HBaseCommonTestingUtility;
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 HBaseCommonTestingUtility 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 HBaseCommonTestingUtility();
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  public static class TestSMProcedure
184      extends StateMachineProcedure<TestProcEnv, TestSMProcedureState> {
185    @Override
186    protected Flow executeFromState(TestProcEnv env, TestSMProcedureState state) {
187      LOG.info("EXEC " + state + " " + this);
188      env.execCount.incrementAndGet();
189      switch (state) {
190        case STEP_1:
191          if (!env.loop) {
192            setNextState(TestSMProcedureState.STEP_2);
193          }
194          break;
195        case STEP_2:
196          addChildProcedure(new SimpleChildProcedure());
197          return Flow.NO_MORE_STATE;
198      }
199      return Flow.HAS_MORE_STATE;
200    }
201
202    @Override
203    protected boolean isRollbackSupported(TestSMProcedureState state) {
204      return true;
205    }
206
207    @Override
208    protected void rollbackState(TestProcEnv env, TestSMProcedureState state) {
209      LOG.info("ROLLBACK " + state + " " + this);
210      env.rollbackCount.incrementAndGet();
211    }
212
213    @Override
214    protected TestSMProcedureState getState(int stateId) {
215      return TestSMProcedureState.values()[stateId];
216    }
217
218    @Override
219    protected int getStateId(TestSMProcedureState state) {
220      return state.ordinal();
221    }
222
223    @Override
224    protected TestSMProcedureState getInitialState() {
225      return TestSMProcedureState.STEP_1;
226    }
227  }
228
229  public static class TestSMProcedureBadRollback
230          extends StateMachineProcedure<TestProcEnv, TestSMProcedureState> {
231    @Override
232    protected Flow executeFromState(TestProcEnv env, TestSMProcedureState state) {
233      LOG.info("EXEC " + state + " " + this);
234      env.execCount.incrementAndGet();
235      switch (state) {
236        case STEP_1:
237          if (!env.loop) {
238            setNextState(TestSMProcedureState.STEP_2);
239          }
240          break;
241        case STEP_2:
242          addChildProcedure(new SimpleChildProcedure());
243          return Flow.NO_MORE_STATE;
244      }
245      return Flow.HAS_MORE_STATE;
246    }
247    @Override
248    protected void rollbackState(TestProcEnv env, TestSMProcedureState state) {
249      LOG.info("ROLLBACK " + state + " " + this);
250      env.rollbackCount.incrementAndGet();
251    }
252
253    @Override
254    protected TestSMProcedureState getState(int stateId) {
255      return TestSMProcedureState.values()[stateId];
256    }
257
258    @Override
259    protected int getStateId(TestSMProcedureState state) {
260      return state.ordinal();
261    }
262
263    @Override
264    protected TestSMProcedureState getInitialState() {
265      return TestSMProcedureState.STEP_1;
266    }
267
268    @Override
269    protected void rollback(final TestProcEnv env)
270            throws IOException, InterruptedException {
271      if (isEofState()) {
272        stateCount--;
273      }
274      try {
275        updateTimestamp();
276        rollbackState(env, getCurrentState());
277        throw new IOException();
278      } catch(IOException e) {
279        //do nothing for now
280      } finally {
281        stateCount--;
282        updateTimestamp();
283      }
284    }
285  }
286
287  public static class SimpleChildProcedure extends NoopProcedure<TestProcEnv> {
288    @Override
289    protected Procedure<TestProcEnv>[] execute(TestProcEnv env) {
290      LOG.info("EXEC " + this);
291      env.execCount.incrementAndGet();
292      if (env.triggerChildRollback) {
293        setFailure("test-failure", TEST_FAILURE_EXCEPTION);
294      }
295      return null;
296    }
297
298    @Override
299    protected void rollback(TestProcEnv env) {
300      LOG.info("ROLLBACK " + this);
301      env.rollbackCount.incrementAndGet();
302    }
303  }
304
305  public static class TestProcEnv {
306    AtomicInteger execCount = new AtomicInteger(0);
307    AtomicInteger rollbackCount = new AtomicInteger(0);
308    boolean triggerChildRollback = false;
309    boolean loop = false;
310  }
311}