Add distibuted action

- New module spring-statemachine-cluster which is
  based on spring-cloud-cluster to provide leader
  election.
- Ensemble now has a concept of a leader if implementation
  supports it.
- New DistributedLeaderAction can use leader info to execute
  action only on a leader.
- Tweak web sample with these new concepts.
- Fixes #176
This commit is contained in:
Janne Valkealahti
2016-03-28 10:44:48 +01:00
parent 89d183f91c
commit 6cce27e30b
23 changed files with 951 additions and 123 deletions

View File

@@ -0,0 +1,71 @@
/*
* Copyright 2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.statemachine.action;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.statemachine.StateContext;
import org.springframework.statemachine.StateMachine;
import org.springframework.statemachine.ensemble.StateMachineEnsemble;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
/**
* {@link Action} which is used to wrap execution of an {@link Action}
* so that only a {@link StateMachine} considered to be a leader in an
* {@link StateMachineEnsemble} will do the execution.
*
* Executing action via {@code DistributedLeaderAction} is bound to if
* current machine is a leader or not. Effectively this means that if
* leader doesn't exist, execution is discarded.
*
* @author Janne Valkealahti
*
* @param <S> the type of state
* @param <E> the type of event
*/
public class DistributedLeaderAction<S, E> implements Action<S, E> {
private final static Log log = LogFactory.getLog(DistributedLeaderAction.class);
private final Action<S, E> action;
private final StateMachineEnsemble<S, E> ensemble;
/**
* Instantiates a new distributed leader action.
*
* @param action the action
* @param ensemble the ensemble
*/
public DistributedLeaderAction(Action<S, E> action, StateMachineEnsemble<S, E> ensemble) {
Assert.notNull(action, "Action must be set");
Assert.notNull(ensemble, "Ensemble must be set");
this.action = action;
this.ensemble = ensemble;
}
@Override
public void execute(StateContext<S, E> context) {
StateMachine<S, E> left = context.getStateMachine();
StateMachine<S, E> right = ensemble.getLeader();
boolean leader = (left != null & right != null) && ObjectUtils.nullSafeEquals(left.getUuid(), right.getUuid());
if (log.isDebugEnabled()) {
log.debug("Distibuted action leader status is " + leader);
}
if (leader) {
action.execute(context);
}
}
}

View File

@@ -64,4 +64,19 @@ public class CompositeEnsembleListener<S, E> extends AbstractCompositeListener<E
}
}
@Override
public void ensembleLeaderGranted(StateMachine<S, E> stateMachine) {
for (Iterator<EnsembleListener<S, E>> iterator = getListeners().reverse(); iterator.hasNext();) {
EnsembleListener<S, E> listener = iterator.next();
listener.ensembleLeaderGranted(stateMachine);
}
}
@Override
public void ensembleLeaderRevoked(StateMachine<S, E> stateMachine) {
for (Iterator<EnsembleListener<S, E>> iterator = getListeners().reverse(); iterator.hasNext();) {
EnsembleListener<S, E> listener = iterator.next();
listener.ensembleLeaderRevoked(stateMachine);
}
}
}

View File

@@ -312,6 +312,13 @@ public class DistributedStateMachine<S, E> extends LifecycleObjectSupport implem
throw exception;
}
@Override
public void ensembleLeaderGranted(StateMachine<S, E> stateMachine) {
}
@Override
public void ensembleLeaderRevoked(StateMachine<S, E> stateMachine) {
}
}
}

View File

@@ -69,4 +69,19 @@ public interface EnsembleListener<S, E> {
*/
void ensembleError(StateMachineEnsembleException exception);
/**
* Called when a state machine is granted a leader role
* in an ensemble.
*
* @param stateMachine the state machine
*/
void ensembleLeaderGranted(StateMachine<S, E> stateMachine);
/**
* Called when a state machine is revoked from a leader role
* in an ensemble.
*
* @param stateMachine the state machine
*/
void ensembleLeaderRevoked(StateMachine<S, E> stateMachine);
}

View File

@@ -0,0 +1,55 @@
/*
* Copyright 2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.statemachine.ensemble;
import org.springframework.statemachine.StateMachine;
import org.springframework.statemachine.StateMachineContext;
/**
* Adapter implementation of {@link EnsembleListener} implementing all
* methods which extended implementation can override.
*
* @author Janne Valkealahti
*
* @param <S> the type of state
* @param <E> the type of event
*/
public class EnsembleListenerAdapter<S, E> implements EnsembleListener<S, E> {
@Override
public void stateMachineJoined(StateMachine<S, E> stateMachine, StateMachineContext<S, E> context) {
}
@Override
public void stateMachineLeft(StateMachine<S, E> stateMachine, StateMachineContext<S, E> context) {
}
@Override
public void stateChanged(StateMachineContext<S, E> context) {
}
@Override
public void ensembleError(StateMachineEnsembleException exception) {
}
@Override
public void ensembleLeaderGranted(StateMachine<S, E> stateMachine) {
}
@Override
public void ensembleLeaderRevoked(StateMachine<S, E> stateMachine) {
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2015 the original author or authors.
* Copyright 2015-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -80,4 +80,12 @@ public interface StateMachineEnsemble<S, E> {
*/
StateMachineContext<S, E> getState();
/**
* Gets the ensemble leader. If returned machine
* is {@code NULL} it indicates that this ensemble
* doesn't know any leader.
*
* @return the ensemble leader
*/
StateMachine<S, E> getLeader();
}

View File

@@ -63,11 +63,18 @@ public abstract class StateMachineEnsembleObjectSupport<S, E> extends LifecycleO
ensembleListener.ensembleError(exception);
}
protected void notifyGranted(StateMachine<S, E> stateMachine) {
ensembleListener.ensembleLeaderGranted(stateMachine);
}
protected void notifyRevoked(StateMachine<S, E> stateMachine) {
ensembleListener.ensembleLeaderRevoked(stateMachine);
}
protected void notifyStateChanged(StateMachineContext<S, E> context) {
if (log.isTraceEnabled()) {
log.trace("Notify notifyStateChanged " + context);
}
ensembleListener.stateChanged(context);
}
}

View File

@@ -0,0 +1,142 @@
/*
* Copyright 2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.statemachine.action;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.statemachine.AbstractStateMachineTests;
import org.springframework.statemachine.StateContext;
import org.springframework.statemachine.StateMachine;
import org.springframework.statemachine.config.EnableStateMachineFactory;
import org.springframework.statemachine.config.StateMachineConfigurerAdapter;
import org.springframework.statemachine.config.StateMachineFactory;
import org.springframework.statemachine.config.builders.StateMachineConfigurationConfigurer;
import org.springframework.statemachine.config.builders.StateMachineStateConfigurer;
import org.springframework.statemachine.config.builders.StateMachineTransitionConfigurer;
import org.springframework.statemachine.ensemble.InMemoryStateMachineEnsemble;
import org.springframework.statemachine.ensemble.StateMachineEnsemble;
public class DistributedLeaderActionTests extends AbstractStateMachineTests {
@Override
protected AnnotationConfigApplicationContext buildContext() {
return new AnnotationConfigApplicationContext();
}
@Test
public void testAction() throws Exception {
context.register(Config1.class);
context.refresh();
TestLeaderAction action = context.getBean("testLeaderAction", TestLeaderAction.class);
@SuppressWarnings("unchecked")
StateMachineFactory<String, String> factory = context.getBean(StateMachineFactory.class);
StateMachine<String, String> machine1 = factory.getStateMachine();
StateMachine<String, String> machine2 = factory.getStateMachine();
machine1.sendEvent("E1");
assertThat(action.latch.await(1, TimeUnit.SECONDS), is(false));
assertThat(action.count, is(1));
action.reset(2);
machine2.sendEvent("E2");
assertThat(action.latch.await(1, TimeUnit.SECONDS), is(false));
assertThat(action.count, is(1));
}
@Configuration
@EnableStateMachineFactory
static class Config1 extends StateMachineConfigurerAdapter<String, String> {
@Override
public void configure(StateMachineConfigurationConfigurer<String, String> config) throws Exception {
config
.withConfiguration()
.autoStartup(true)
.and()
.withDistributed()
.ensemble(ensemble());
}
@Override
public void configure(StateMachineStateConfigurer<String, String> states) throws Exception {
states
.withStates()
.initial("S1")
.state("S2", testDistributedLeaderAction(), null)
.state("S3", testDistributedLeaderAction(), null);
}
@Override
public void configure(StateMachineTransitionConfigurer<String, String> transitions) throws Exception {
transitions
.withExternal()
.source("S1").target("S2")
.event("E1")
.and()
.withExternal()
.source("S2").target("S3")
.event("E2")
.and()
.withExternal()
.source("S3").target("S1")
.event("E3");
}
@Bean
public StateMachineEnsemble<String, String> ensemble() {
return new InMemoryStateMachineEnsemble<String, String>();
}
@Bean
public Action<String, String> testLeaderAction() {
return new TestLeaderAction();
}
@Bean
public Action<String, String> testDistributedLeaderAction() {
return new DistributedLeaderAction<>(testLeaderAction(), ensemble());
}
}
static class TestLeaderAction implements Action<String, String> {
CountDownLatch latch = new CountDownLatch(2);
int count = 0;
@Override
public void execute(StateContext<String, String> context) {
count++;
latch.countDown();
}
public void reset(int a1) {
count = 0;
latch = new CountDownLatch(a1);
}
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2015 the original author or authors.
* Copyright 2015-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -24,13 +24,16 @@ import org.springframework.statemachine.StateMachineContext;
public class InMemoryStateMachineEnsemble<S, E> extends StateMachineEnsembleObjectSupport<S, E> {
private final Set<StateMachine<S, E>> joined = new HashSet<StateMachine<S,E>>();
private StateMachine<S, E> leader;
private StateMachineContext<S, E> current;
@Override
public void join(StateMachine<S, E> stateMachine) {
if (!joined.contains(stateMachine)) {
joined.add(stateMachine);
if (leader == null) {
leader = stateMachine;
}
notifyJoined(stateMachine, current);
}
}
@@ -38,6 +41,14 @@ public class InMemoryStateMachineEnsemble<S, E> extends StateMachineEnsembleObje
@Override
public void leave(StateMachine<S, E> stateMachine) {
if (joined.remove(stateMachine)) {
if (leader == stateMachine) {
StateMachine<S, E> newLeader = null;
try {
newLeader = joined.iterator().next();
} catch (Exception e) {
}
leader = newLeader;
}
notifyLeft(stateMachine, current);
}
}
@@ -53,4 +64,8 @@ public class InMemoryStateMachineEnsemble<S, E> extends StateMachineEnsembleObje
return current;
}
@Override
public StateMachine<S, E> getLeader() {
return leader;
}
}