State offline = State.from("OFFLINE");
State dropped = State.from("DROPPED");
StateModelDefId stateModelDefId = StateModelDefId.from("MasterSlave");
// create connection
HelixConnection connection = new ZkHelixConnection(_zkaddr);
connection.connect();
// setup cluster
ClusterAccessor clusterAccessor = connection.createClusterAccessor(clusterId);
clusterAccessor.dropCluster();
StateModelDefinition stateModelDef =
new StateModelDefinition.Builder(stateModelDefId).addState(master, 1).addState(slave, 2)
.addState(offline, 3).addState(dropped).addTransition(offline, slave, 3)
.addTransition(slave, offline, 4).addTransition(slave, master, 2)
.addTransition(master, slave, 1).addTransition(offline, dropped).initialState(offline)
.upperBound(master, 1).dynamicUpperBound(slave, "R").build();
PartitionId partition0 = PartitionId.from(resourceId, "0");
AutoModeISBuilder idealStateBuilder = new AutoModeISBuilder(resourceId).add(partition0);
idealStateBuilder.setNumReplica(1).setStateModelDefId(stateModelDefId);
idealStateBuilder.assignPreferenceList(partition0, participantId);
IdealState idealState = idealStateBuilder.build();
clusterAccessor.createCluster(new ClusterConfig.Builder(clusterId).addStateModelDefinition(
stateModelDef).build());
clusterAccessor.addResource(new ResourceConfig.Builder(resourceId).idealState(idealState)
.build());
clusterAccessor.addParticipant(new ParticipantConfig.Builder(participantId).build());
// start controller
HelixController controller = connection.createController(clusterId, controllerId);
controller.start();
// start participant
HelixParticipant participant = connection.createParticipant(clusterId, participantId);
participant.getStateMachineEngine().registerStateModelFactory(
StateModelDefId.from("MasterSlave"), new MockStateModelFactory());
participant.start();
Thread.sleep(1000);
// verify
final HelixDataAccessor accessor = connection.createDataAccessor(clusterId);
final PropertyKey.Builder keyBuilder = accessor.keyBuilder();
boolean success = TestHelper.verify(new TestHelper.Verifier() {
@Override
public boolean verify() throws Exception {
ExternalView externalView = accessor.getProperty(keyBuilder.externalView("testDB"));
Map<ParticipantId, State> stateMap = externalView.getStateMap(PartitionId.from("testDB_0"));
if (stateMap == null || !stateMap.containsKey(participantId)) {
return false;
}
return stateMap.get(participantId).equals(State.from("MASTER"));
}
}, 10 * 1000);
Assert.assertTrue(success);
// clean up
controller.stop();
participant.stop();
connection.disconnect();
System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis()));
}