Merge "Fix missing dependencies in opendaylight-startup archetype"
[controller.git] / opendaylight / md-sal / sal-akka-raft / src / main / java / org / opendaylight / controller / cluster / raft / behaviors / Leader.java
1 /*
2  * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.controller.cluster.raft.behaviors;
9
10 import akka.actor.ActorRef;
11 import akka.actor.Cancellable;
12 import com.google.common.annotations.VisibleForTesting;
13 import com.google.common.base.Preconditions;
14 import org.opendaylight.controller.cluster.raft.RaftActorContext;
15 import org.opendaylight.controller.cluster.raft.base.messages.InitiateInstallSnapshot;
16 import org.opendaylight.controller.cluster.raft.base.messages.IsolatedLeaderCheck;
17 import scala.concurrent.duration.FiniteDuration;
18
19 /**
20  * The behavior of a RaftActor when it is in the Leader state
21  * <p/>
22  * Leaders:
23  * <ul>
24  * <li> Upon election: send initial empty AppendEntries RPCs
25  * (heartbeat) to each server; repeat during idle periods to
26  * prevent election timeouts (§5.2)
27  * <li> If command received from client: append entry to local log,
28  * respond after entry applied to state machine (§5.3)
29  * <li> If last log index ≥ nextIndex for a follower: send
30  * AppendEntries RPC with log entries starting at nextIndex
31  * <ul>
32  * <li> If successful: update nextIndex and matchIndex for
33  * follower (§5.3)
34  * <li> If AppendEntries fails because of log inconsistency:
35  * decrement nextIndex and retry (§5.3)
36  * </ul>
37  * <li> If there exists an N such that N > commitIndex, a majority
38  * of matchIndex[i] ≥ N, and log[N].term == currentTerm:
39  * set commitIndex = N (§5.3, §5.4).
40  */
41 public class Leader extends AbstractLeader {
42     private Cancellable installSnapshotSchedule = null;
43     private Cancellable isolatedLeaderCheckSchedule = null;
44
45     public Leader(RaftActorContext context) {
46         super(context);
47
48         scheduleInstallSnapshotCheck(context.getConfigParams().getIsolatedCheckInterval());
49
50         scheduleIsolatedLeaderCheck(
51             new FiniteDuration(context.getConfigParams().getHeartBeatInterval().length() * 10,
52                 context.getConfigParams().getHeartBeatInterval().unit()));
53     }
54
55     @Override public RaftActorBehavior handleMessage(ActorRef sender, Object originalMessage) {
56         Preconditions.checkNotNull(sender, "sender should not be null");
57
58         if (originalMessage instanceof IsolatedLeaderCheck) {
59             if (isLeaderIsolated()) {
60                 LOG.info("At least {} followers need to be active, Switching {} from Leader to IsolatedLeader",
61                     minIsolatedLeaderPeerCount, leaderId);
62                 return switchBehavior(new IsolatedLeader(context));
63             }
64         }
65
66         return super.handleMessage(sender, originalMessage);
67     }
68
69     protected void stopInstallSnapshotSchedule() {
70         if (installSnapshotSchedule != null && !installSnapshotSchedule.isCancelled()) {
71             installSnapshotSchedule.cancel();
72         }
73     }
74
75     protected void scheduleInstallSnapshotCheck(FiniteDuration interval) {
76         if (getFollowerIds().isEmpty()) {
77             // Optimization - do not bother scheduling a heartbeat as there are
78             // no followers
79             return;
80         }
81
82         stopInstallSnapshotSchedule();
83
84         // Schedule a message to send append entries to followers that can
85         // accept an append entries with some data in it
86         installSnapshotSchedule =
87             context.getActorSystem().scheduler().scheduleOnce(
88                 interval,
89                 context.getActor(), new InitiateInstallSnapshot(),
90                 context.getActorSystem().dispatcher(), context.getActor());
91     }
92
93     protected void stopIsolatedLeaderCheckSchedule() {
94         if (isolatedLeaderCheckSchedule != null && !isolatedLeaderCheckSchedule.isCancelled()) {
95             isolatedLeaderCheckSchedule.cancel();
96         }
97     }
98
99     protected void scheduleIsolatedLeaderCheck(FiniteDuration isolatedCheckInterval) {
100         isolatedLeaderCheckSchedule = context.getActorSystem().scheduler().schedule(isolatedCheckInterval, isolatedCheckInterval,
101             context.getActor(), new IsolatedLeaderCheck(),
102             context.getActorSystem().dispatcher(), context.getActor());
103     }
104
105     @Override
106     public void close() throws Exception {
107         stopInstallSnapshotSchedule();
108         stopIsolatedLeaderCheckSchedule();
109         super.close();
110     }
111
112     @VisibleForTesting
113     void markFollowerActive(String followerId) {
114         getFollower(followerId).markFollowerActive();
115     }
116
117     @VisibleForTesting
118     void markFollowerInActive(String followerId) {
119         getFollower(followerId).markFollowerInActive();
120     }
121 }