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.SmallTests;
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, SmallTests.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 testChildOnLastStepWithRollbackDoubleExecution() throws Exception {
154    procExecutor.getEnvironment().triggerChildRollback = true;
155    ProcedureTestingUtility.setKillAndToggleBeforeStoreUpdate(procExecutor, true);
156    long procId = procExecutor.submitProcedure(new TestSMProcedure());
157    ProcedureTestingUtility.testRecoveryAndDoubleExecution(procExecutor, procId, true);
158    assertEquals(6, procExecutor.getEnvironment().execCount.get());
159    assertEquals(6, procExecutor.getEnvironment().rollbackCount.get());
160    Throwable cause = ProcedureTestingUtility.assertProcFailed(procExecutor, procId);
161    assertEquals(TEST_FAILURE_EXCEPTION, cause);
162  }
163
164  public enum TestSMProcedureState { STEP_1, STEP_2 };
165  public static class TestSMProcedure
166      extends StateMachineProcedure<TestProcEnv, TestSMProcedureState> {
167    @Override
168    protected Flow executeFromState(TestProcEnv env, TestSMProcedureState state) {
169      LOG.info("EXEC " + state + " " + this);
170      env.execCount.incrementAndGet();
171      switch (state) {
172        case STEP_1:
173          if (!env.loop) {
174            setNextState(TestSMProcedureState.STEP_2);
175          }
176          break;
177        case STEP_2:
178          addChildProcedure(new SimpleChildProcedure());
179          return Flow.NO_MORE_STATE;
180      }
181      return Flow.HAS_MORE_STATE;
182    }
183
184    @Override
185    protected boolean isRollbackSupported(TestSMProcedureState state) {
186      return true;
187    }
188
189    @Override
190    protected void rollbackState(TestProcEnv env, TestSMProcedureState state) {
191      LOG.info("ROLLBACK " + state + " " + this);
192      env.rollbackCount.incrementAndGet();
193    }
194
195    @Override
196    protected TestSMProcedureState getState(int stateId) {
197      return TestSMProcedureState.values()[stateId];
198    }
199
200    @Override
201    protected int getStateId(TestSMProcedureState state) {
202      return state.ordinal();
203    }
204
205    @Override
206    protected TestSMProcedureState getInitialState() {
207      return TestSMProcedureState.STEP_1;
208    }
209  }
210
211  public static class SimpleChildProcedure extends NoopProcedure<TestProcEnv> {
212    @Override
213    protected Procedure<TestProcEnv>[] execute(TestProcEnv env) {
214      LOG.info("EXEC " + this);
215      env.execCount.incrementAndGet();
216      if (env.triggerChildRollback) {
217        setFailure("test-failure", TEST_FAILURE_EXCEPTION);
218      }
219      return null;
220    }
221
222    @Override
223    protected void rollback(TestProcEnv env) {
224      LOG.info("ROLLBACK " + this);
225      env.rollbackCount.incrementAndGet();
226    }
227  }
228
229  public static class TestProcEnv {
230    AtomicInteger execCount = new AtomicInteger(0);
231    AtomicInteger rollbackCount = new AtomicInteger(0);
232    boolean triggerChildRollback = false;
233    boolean loop = false;
234  }
235}