2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.controller.cluster.raft.behaviors;
10 import akka.actor.ActorRef;
11 import com.google.common.annotations.VisibleForTesting;
12 import com.google.common.base.Preconditions;
13 import com.google.common.base.Stopwatch;
14 import java.util.concurrent.TimeUnit;
15 import org.opendaylight.controller.cluster.raft.RaftActorContext;
16 import org.opendaylight.controller.cluster.raft.base.messages.IsolatedLeaderCheck;
19 * The behavior of a RaftActor when it is in the Leader state
23 * <li> Upon election: send initial empty AppendEntries RPCs
24 * (heartbeat) to each server; repeat during idle periods to
25 * prevent election timeouts (§5.2)
26 * <li> If command received from client: append entry to local log,
27 * respond after entry applied to state machine (§5.3)
28 * <li> If last log index ≥ nextIndex for a follower: send
29 * AppendEntries RPC with log entries starting at nextIndex
31 * <li> If successful: update nextIndex and matchIndex for
33 * <li> If AppendEntries fails because of log inconsistency:
34 * decrement nextIndex and retry (§5.3)
36 * <li> If there exists an N such that N > commitIndex, a majority
37 * of matchIndex[i] ≥ N, and log[N].term == currentTerm:
38 * set commitIndex = N (§5.3, §5.4).
40 public class Leader extends AbstractLeader {
41 private static final IsolatedLeaderCheck ISOLATED_LEADER_CHECK = new IsolatedLeaderCheck();
42 private final Stopwatch isolatedLeaderCheck;
44 public Leader(RaftActorContext context) {
46 isolatedLeaderCheck = Stopwatch.createStarted();
49 @Override public RaftActorBehavior handleMessage(ActorRef sender, Object originalMessage) {
50 Preconditions.checkNotNull(sender, "sender should not be null");
52 if (originalMessage instanceof IsolatedLeaderCheck) {
53 if (isLeaderIsolated()) {
54 LOG.warn("{}: At least {} followers need to be active, Switching {} from Leader to IsolatedLeader",
55 context.getId(), minIsolatedLeaderPeerCount, leaderId);
57 return switchBehavior(new IsolatedLeader(context));
61 return super.handleMessage(sender, originalMessage);
65 protected void beforeSendHeartbeat(){
66 if(isolatedLeaderCheck.elapsed(TimeUnit.MILLISECONDS) > context.getConfigParams().getIsolatedCheckIntervalInMillis()){
67 context.getActor().tell(ISOLATED_LEADER_CHECK, context.getActor());
68 isolatedLeaderCheck.reset().start();
74 public void close() throws Exception {
79 void markFollowerActive(String followerId) {
80 getFollower(followerId).markFollowerActive();
84 void markFollowerInActive(String followerId) {
85 getFollower(followerId).markFollowerInActive();