Search in sources :

Example 1 with ElectionTimeout

use of org.opendaylight.controller.cluster.raft.base.messages.ElectionTimeout in project controller by opendaylight.

the class Candidate method handleMessage.

@Override
public RaftActorBehavior handleMessage(ActorRef sender, Object message) {
    if (message instanceof ElectionTimeout) {
        log.debug("{}: Received ElectionTimeout", logName());
        if (votesRequired == 0) {
            return internalSwitchBehavior(RaftState.Leader);
        }
        startNewTerm();
        scheduleElection(electionDuration());
        return this;
    }
    if (message instanceof RaftRPC) {
        RaftRPC rpc = (RaftRPC) message;
        log.debug("{}: RaftRPC message received {}, my term is {}", logName(), rpc, context.getTermInformation().getCurrentTerm());
        // This applies to all RPC messages and responses
        if (rpc.getTerm() > context.getTermInformation().getCurrentTerm()) {
            log.info("{}: Term {} in \"{}\" message is greater than Candidate's term {} - switching to Follower", logName(), rpc.getTerm(), rpc, context.getTermInformation().getCurrentTerm());
            context.getTermInformation().updateAndPersist(rpc.getTerm(), null);
            // this case but doing so gains quicker convergence when the sender's log is more up-to-date.
            if (message instanceof RequestVote) {
                super.handleMessage(sender, message);
            }
            return internalSwitchBehavior(RaftState.Follower);
        }
    }
    return super.handleMessage(sender, message);
}
Also used : RaftRPC(org.opendaylight.controller.cluster.raft.messages.RaftRPC) ElectionTimeout(org.opendaylight.controller.cluster.raft.base.messages.ElectionTimeout) RequestVote(org.opendaylight.controller.cluster.raft.messages.RequestVote)

Example 2 with ElectionTimeout

use of org.opendaylight.controller.cluster.raft.base.messages.ElectionTimeout in project controller by opendaylight.

the class Follower method handleMessage.

@Override
public RaftActorBehavior handleMessage(final ActorRef sender, final Object message) {
    if (message instanceof ElectionTimeout || message instanceof TimeoutNow) {
        return handleElectionTimeout(message);
    }
    if (appendEntriesMessageAssembler.handleMessage(message, actor())) {
        return this;
    }
    if (!(message instanceof RaftRPC)) {
        // The rest of the processing requires the message to be a RaftRPC
        return null;
    }
    final RaftRPC rpc = (RaftRPC) message;
    // This applies to all RPC messages and responses
    if (rpc.getTerm() > context.getTermInformation().getCurrentTerm()) {
        log.info("{}: Term {} in \"{}\" message is greater than follower's term {} - updating term", logName(), rpc.getTerm(), rpc, context.getTermInformation().getCurrentTerm());
        context.getTermInformation().updateAndPersist(rpc.getTerm(), null);
    }
    if (rpc instanceof InstallSnapshot) {
        handleInstallSnapshot(sender, (InstallSnapshot) rpc);
        restartLastLeaderMessageTimer();
        scheduleElection(electionDuration());
        return this;
    }
    if (!(rpc instanceof RequestVote) || canGrantVote((RequestVote) rpc)) {
        restartLastLeaderMessageTimer();
        scheduleElection(electionDuration());
    }
    return super.handleMessage(sender, rpc);
}
Also used : RaftRPC(org.opendaylight.controller.cluster.raft.messages.RaftRPC) TimeoutNow(org.opendaylight.controller.cluster.raft.base.messages.TimeoutNow) ElectionTimeout(org.opendaylight.controller.cluster.raft.base.messages.ElectionTimeout) RequestVote(org.opendaylight.controller.cluster.raft.messages.RequestVote) InstallSnapshot(org.opendaylight.controller.cluster.raft.messages.InstallSnapshot)

Example 3 with ElectionTimeout

use of org.opendaylight.controller.cluster.raft.base.messages.ElectionTimeout in project controller by opendaylight.

the class FollowerTest method testFollowerSchedulesElectionIfNonVoting.

@Test
public void testFollowerSchedulesElectionIfNonVoting() {
    MockRaftActorContext context = createActorContext();
    context.updatePeerIds(new ServerConfigurationPayload(Arrays.asList(new ServerInfo(context.getId(), false))));
    ((DefaultConfigParamsImpl) context.getConfigParams()).setHeartBeatInterval(FiniteDuration.apply(100, TimeUnit.MILLISECONDS));
    ((DefaultConfigParamsImpl) context.getConfigParams()).setElectionTimeoutFactor(1);
    follower = new Follower(context, "leader", (short) 1);
    ElectionTimeout electionTimeout = MessageCollectorActor.expectFirstMatching(followerActor, ElectionTimeout.class);
    RaftActorBehavior newBehavior = follower.handleMessage(ActorRef.noSender(), electionTimeout);
    assertSame("handleMessage result", follower, newBehavior);
    assertNull("Expected null leaderId", follower.getLeaderId());
}
Also used : ServerConfigurationPayload(org.opendaylight.controller.cluster.raft.persisted.ServerConfigurationPayload) ServerInfo(org.opendaylight.controller.cluster.raft.persisted.ServerInfo) ElectionTimeout(org.opendaylight.controller.cluster.raft.base.messages.ElectionTimeout) MockRaftActorContext(org.opendaylight.controller.cluster.raft.MockRaftActorContext) DefaultConfigParamsImpl(org.opendaylight.controller.cluster.raft.DefaultConfigParamsImpl) Test(org.junit.Test)

Example 4 with ElectionTimeout

use of org.opendaylight.controller.cluster.raft.base.messages.ElectionTimeout in project controller by opendaylight.

the class ShardTest method testChangeListenerNotifiedWhenNotTheLeaderOnRegistration.

@SuppressWarnings("serial")
@Test
public void testChangeListenerNotifiedWhenNotTheLeaderOnRegistration() throws Exception {
    // This test tests the timing window in which a change listener is registered before the
    // shard becomes the leader. We verify that the listener is registered and notified of the
    // existing data when the shard becomes the leader.
    // For this test, we want to send the RegisterChangeListener message after the shard
    // has recovered from persistence and before it becomes the leader. So we subclass
    // Shard to override onReceiveCommand and, when the first ElectionTimeout is received,
    // we know that the shard has been initialized to a follower and has started the
    // election process. The following 2 CountDownLatches are used to coordinate the
    // ElectionTimeout with the sending of the RegisterChangeListener message.
    final CountDownLatch onFirstElectionTimeout = new CountDownLatch(1);
    final CountDownLatch onChangeListenerRegistered = new CountDownLatch(1);
    final Creator<Shard> creator = new Creator<Shard>() {

        boolean firstElectionTimeout = true;

        @Override
        public Shard create() throws Exception {
            // it does do a persist)
            return new Shard(newShardBuilder()) {

                @Override
                public void handleCommand(final Object message) {
                    if (message instanceof ElectionTimeout && firstElectionTimeout) {
                        // Got the first ElectionTimeout. We don't forward it to the
                        // base Shard yet until we've sent the RegisterChangeListener
                        // message. So we signal the onFirstElectionTimeout latch to tell
                        // the main thread to send the RegisterChangeListener message and
                        // start a thread to wait on the onChangeListenerRegistered latch,
                        // which the main thread signals after it has sent the message.
                        // After the onChangeListenerRegistered is triggered, we send the
                        // original ElectionTimeout message to proceed with the election.
                        firstElectionTimeout = false;
                        final ActorRef self = getSelf();
                        new Thread(() -> {
                            Uninterruptibles.awaitUninterruptibly(onChangeListenerRegistered, 5, TimeUnit.SECONDS);
                            self.tell(message, self);
                        }).start();
                        onFirstElectionTimeout.countDown();
                    } else {
                        super.handleCommand(message);
                    }
                }
            };
        }
    };
    setupInMemorySnapshotStore();
    final YangInstanceIdentifier path = TestModel.TEST_PATH;
    final MockDataChangeListener listener = new MockDataChangeListener(1);
    final ActorRef dclActor = actorFactory.createActor(DataChangeListener.props(listener, path), "testRegisterChangeListenerWhenNotLeaderInitially-DataChangeListener");
    final TestActorRef<Shard> shard = actorFactory.createTestActor(Props.create(new DelegatingShardCreator(creator)).withDispatcher(Dispatchers.DefaultDispatcherId()), "testRegisterChangeListenerWhenNotLeaderInitially");
    new ShardTestKit(getSystem()) {

        {
            // Wait until the shard receives the first ElectionTimeout
            // message.
            assertEquals("Got first ElectionTimeout", true, onFirstElectionTimeout.await(5, TimeUnit.SECONDS));
            // Now send the RegisterChangeListener and wait for the reply.
            shard.tell(new RegisterChangeListener(path, dclActor, AsyncDataBroker.DataChangeScope.SUBTREE, false), getRef());
            final RegisterDataTreeNotificationListenerReply reply = expectMsgClass(duration("5 seconds"), RegisterDataTreeNotificationListenerReply.class);
            assertNotNull("getListenerRegistrationPath", reply.getListenerRegistrationPath());
            // Sanity check - verify the shard is not the leader yet.
            shard.tell(FindLeader.INSTANCE, getRef());
            final FindLeaderReply findLeadeReply = expectMsgClass(duration("5 seconds"), FindLeaderReply.class);
            assertFalse("Expected the shard not to be the leader", findLeadeReply.getLeaderActor().isPresent());
            // Signal the onChangeListenerRegistered latch to tell the
            // thread above to proceed
            // with the election process.
            onChangeListenerRegistered.countDown();
            // Wait for the shard to become the leader and notify our
            // listener with the existing
            // data in the store.
            listener.waitForChangeEvents(path);
        }
    };
}
Also used : RegisterDataTreeNotificationListenerReply(org.opendaylight.controller.cluster.datastore.messages.RegisterDataTreeNotificationListenerReply) ElectionTimeout(org.opendaylight.controller.cluster.raft.base.messages.ElectionTimeout) ActorRef(akka.actor.ActorRef) TestActorRef(akka.testkit.TestActorRef) RegisterChangeListener(org.opendaylight.controller.cluster.datastore.messages.RegisterChangeListener) Creator(akka.japi.Creator) CountDownLatch(java.util.concurrent.CountDownLatch) YangInstanceIdentifier(org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier) FindLeaderReply(org.opendaylight.controller.cluster.raft.client.messages.FindLeaderReply) MockDataChangeListener(org.opendaylight.controller.cluster.datastore.utils.MockDataChangeListener) Test(org.junit.Test)

Example 5 with ElectionTimeout

use of org.opendaylight.controller.cluster.raft.base.messages.ElectionTimeout in project controller by opendaylight.

the class ShardTest method testDataTreeChangeListenerNotifiedWhenNotTheLeaderOnRegistration.

@SuppressWarnings("serial")
@Test
public void testDataTreeChangeListenerNotifiedWhenNotTheLeaderOnRegistration() throws Exception {
    final CountDownLatch onFirstElectionTimeout = new CountDownLatch(1);
    final CountDownLatch onChangeListenerRegistered = new CountDownLatch(1);
    final Creator<Shard> creator = new Creator<Shard>() {

        boolean firstElectionTimeout = true;

        @Override
        public Shard create() throws Exception {
            return new Shard(newShardBuilder()) {

                @Override
                public void handleCommand(final Object message) {
                    if (message instanceof ElectionTimeout && firstElectionTimeout) {
                        firstElectionTimeout = false;
                        final ActorRef self = getSelf();
                        new Thread(() -> {
                            Uninterruptibles.awaitUninterruptibly(onChangeListenerRegistered, 5, TimeUnit.SECONDS);
                            self.tell(message, self);
                        }).start();
                        onFirstElectionTimeout.countDown();
                    } else {
                        super.handleCommand(message);
                    }
                }
            };
        }
    };
    setupInMemorySnapshotStore();
    final YangInstanceIdentifier path = TestModel.TEST_PATH;
    final MockDataTreeChangeListener listener = new MockDataTreeChangeListener(1);
    final ActorRef dclActor = actorFactory.createActor(DataTreeChangeListenerActor.props(listener, path), "testDataTreeChangeListenerNotifiedWhenNotTheLeaderOnRegistration-DataChangeListener");
    final TestActorRef<Shard> shard = actorFactory.createTestActor(Props.create(new DelegatingShardCreator(creator)).withDispatcher(Dispatchers.DefaultDispatcherId()), "testDataTreeChangeListenerNotifiedWhenNotTheLeaderOnRegistration");
    new ShardTestKit(getSystem()) {

        {
            assertEquals("Got first ElectionTimeout", true, onFirstElectionTimeout.await(5, TimeUnit.SECONDS));
            shard.tell(new RegisterDataTreeChangeListener(path, dclActor, false), getRef());
            final RegisterDataTreeNotificationListenerReply reply = expectMsgClass(duration("5 seconds"), RegisterDataTreeNotificationListenerReply.class);
            assertNotNull("getListenerRegistratioznPath", reply.getListenerRegistrationPath());
            shard.tell(FindLeader.INSTANCE, getRef());
            final FindLeaderReply findLeadeReply = expectMsgClass(duration("5 seconds"), FindLeaderReply.class);
            assertFalse("Expected the shard not to be the leader", findLeadeReply.getLeaderActor().isPresent());
            onChangeListenerRegistered.countDown();
            // TODO: investigate why we do not receive data chage events
            listener.waitForChangeEvents();
        }
    };
}
Also used : RegisterDataTreeNotificationListenerReply(org.opendaylight.controller.cluster.datastore.messages.RegisterDataTreeNotificationListenerReply) ElectionTimeout(org.opendaylight.controller.cluster.raft.base.messages.ElectionTimeout) ActorRef(akka.actor.ActorRef) TestActorRef(akka.testkit.TestActorRef) Creator(akka.japi.Creator) CountDownLatch(java.util.concurrent.CountDownLatch) YangInstanceIdentifier(org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier) RegisterDataTreeChangeListener(org.opendaylight.controller.cluster.datastore.messages.RegisterDataTreeChangeListener) FindLeaderReply(org.opendaylight.controller.cluster.raft.client.messages.FindLeaderReply) MockDataTreeChangeListener(org.opendaylight.controller.cluster.datastore.utils.MockDataTreeChangeListener) Test(org.junit.Test)

Aggregations

ElectionTimeout (org.opendaylight.controller.cluster.raft.base.messages.ElectionTimeout)5 Test (org.junit.Test)3 ActorRef (akka.actor.ActorRef)2 Creator (akka.japi.Creator)2 TestActorRef (akka.testkit.TestActorRef)2 CountDownLatch (java.util.concurrent.CountDownLatch)2 RegisterDataTreeNotificationListenerReply (org.opendaylight.controller.cluster.datastore.messages.RegisterDataTreeNotificationListenerReply)2 FindLeaderReply (org.opendaylight.controller.cluster.raft.client.messages.FindLeaderReply)2 RaftRPC (org.opendaylight.controller.cluster.raft.messages.RaftRPC)2 RequestVote (org.opendaylight.controller.cluster.raft.messages.RequestVote)2 YangInstanceIdentifier (org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier)2 RegisterChangeListener (org.opendaylight.controller.cluster.datastore.messages.RegisterChangeListener)1 RegisterDataTreeChangeListener (org.opendaylight.controller.cluster.datastore.messages.RegisterDataTreeChangeListener)1 MockDataChangeListener (org.opendaylight.controller.cluster.datastore.utils.MockDataChangeListener)1 MockDataTreeChangeListener (org.opendaylight.controller.cluster.datastore.utils.MockDataTreeChangeListener)1 DefaultConfigParamsImpl (org.opendaylight.controller.cluster.raft.DefaultConfigParamsImpl)1 MockRaftActorContext (org.opendaylight.controller.cluster.raft.MockRaftActorContext)1 TimeoutNow (org.opendaylight.controller.cluster.raft.base.messages.TimeoutNow)1 InstallSnapshot (org.opendaylight.controller.cluster.raft.messages.InstallSnapshot)1 ServerConfigurationPayload (org.opendaylight.controller.cluster.raft.persisted.ServerConfigurationPayload)1