304b2fdbab0b8c242ae01e4768547cd8d5861a46
[controller.git] / opendaylight / md-sal / sal-akka-raft / src / main / java / org / opendaylight / controller / cluster / raft / behaviors / AbstractRaftActorBehavior.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
9 package org.opendaylight.controller.cluster.raft.behaviors;
10
11 import akka.actor.ActorRef;
12 import akka.actor.Cancellable;
13 import org.opendaylight.controller.cluster.raft.ClientRequestTracker;
14 import org.opendaylight.controller.cluster.raft.RaftActorContext;
15 import org.opendaylight.controller.cluster.raft.RaftState;
16 import org.opendaylight.controller.cluster.raft.ReplicatedLogEntry;
17 import org.opendaylight.controller.cluster.raft.internal.messages.ApplyState;
18 import org.opendaylight.controller.cluster.raft.internal.messages.ElectionTimeout;
19 import org.opendaylight.controller.cluster.raft.messages.AppendEntries;
20 import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
21 import org.opendaylight.controller.cluster.raft.messages.RaftRPC;
22 import org.opendaylight.controller.cluster.raft.messages.RequestVote;
23 import org.opendaylight.controller.cluster.raft.messages.RequestVoteReply;
24 import scala.concurrent.duration.FiniteDuration;
25
26 import java.util.Random;
27 import java.util.concurrent.TimeUnit;
28
29 /**
30  * Abstract class that represents the behavior of a RaftActor
31  * <p/>
32  * All Servers:
33  * <ul>
34  * <li> If commitIndex > lastApplied: increment lastApplied, apply
35  * log[lastApplied] to state machine (§5.3)
36  * <li> If RPC request or response contains term T > currentTerm:
37  * set currentTerm = T, convert to follower (§5.1)
38  */
39 public abstract class AbstractRaftActorBehavior implements RaftActorBehavior {
40
41     /**
42      * Information about the RaftActor whose behavior this class represents
43      */
44     protected final RaftActorContext context;
45
46     /**
47      * The maximum election time variance
48      */
49     private static final int ELECTION_TIME_MAX_VARIANCE = 100;
50
51     /**
52      * The interval at which a heart beat message will be sent to the remote
53      * RaftActor
54      * <p/>
55      * Since this is set to 100 milliseconds the Election timeout should be
56      * at least 200 milliseconds
57      */
58     protected static final FiniteDuration HEART_BEAT_INTERVAL =
59         new FiniteDuration(100, TimeUnit.MILLISECONDS);
60
61     /**
62      * The interval in which a new election would get triggered if no leader is found
63      */
64     private static final long ELECTION_TIME_INTERVAL =
65         HEART_BEAT_INTERVAL.toMillis() * 2;
66
67     /**
68      *
69      */
70     private Cancellable electionCancel = null;
71
72     /**
73      *
74      */
75     protected String leaderId = null;
76
77
78     protected AbstractRaftActorBehavior(RaftActorContext context) {
79         this.context = context;
80     }
81
82     /**
83      * Derived classes should not directly handle AppendEntries messages it
84      * should let the base class handle it first. Once the base class handles
85      * the AppendEntries message and does the common actions that are applicable
86      * in all RaftState's it will delegate the handling of the AppendEntries
87      * message to the derived class to do more state specific handling by calling
88      * this method
89      *
90      * @param sender         The actor that sent this message
91      * @param appendEntries  The AppendEntries message
92      * @param suggestedState The state that the RaftActor should be in based
93      *                       on the base class's processing of the AppendEntries
94      *                       message
95      * @return
96      */
97     protected abstract RaftState handleAppendEntries(ActorRef sender,
98         AppendEntries appendEntries, RaftState suggestedState);
99
100
101     protected RaftState appendEntries(ActorRef sender,
102         AppendEntries appendEntries, RaftState raftState) {
103
104         if (raftState != state()) {
105             context.getLogger().debug("Suggested state is " + raftState
106                 + " current behavior state is " + state());
107         }
108
109         // 1. Reply false if term < currentTerm (§5.1)
110         if (appendEntries.getTerm() < currentTerm()) {
111             context.getLogger().debug(
112                 "Cannot append entries because sender term " + appendEntries
113                     .getTerm() + " is less than " + currentTerm());
114             sender.tell(
115                 new AppendEntriesReply(context.getId(), currentTerm(), false,
116                     lastIndex(), lastTerm()), actor()
117             );
118             return state();
119         }
120
121
122         return handleAppendEntries(sender, appendEntries, raftState);
123     }
124
125     /**
126      * Derived classes should not directly handle AppendEntriesReply messages it
127      * should let the base class handle it first. Once the base class handles
128      * the AppendEntriesReply message and does the common actions that are
129      * applicable in all RaftState's it will delegate the handling of the
130      * AppendEntriesReply message to the derived class to do more state specific
131      * handling by calling this method
132      *
133      * @param sender             The actor that sent this message
134      * @param appendEntriesReply The AppendEntriesReply message
135      * @param suggestedState     The state that the RaftActor should be in based
136      *                           on the base class's processing of the
137      *                           AppendEntriesReply message
138      * @return
139      */
140
141     protected abstract RaftState handleAppendEntriesReply(ActorRef sender,
142         AppendEntriesReply appendEntriesReply, RaftState suggestedState);
143
144     protected RaftState requestVote(ActorRef sender,
145         RequestVote requestVote, RaftState suggestedState) {
146
147         boolean grantVote = false;
148
149         //  Reply false if term < currentTerm (§5.1)
150         if (requestVote.getTerm() < currentTerm()) {
151             grantVote = false;
152
153             // If votedFor is null or candidateId, and candidate’s log is at
154             // least as up-to-date as receiver’s log, grant vote (§5.2, §5.4)
155         } else if (votedFor() == null || votedFor()
156             .equals(requestVote.getCandidateId())) {
157
158             boolean candidateLatest = false;
159
160             // From §5.4.1
161             // Raft determines which of two logs is more up-to-date
162             // by comparing the index and term of the last entries in the
163             // logs. If the logs have last entries with different terms, then
164             // the log with the later term is more up-to-date. If the logs
165             // end with the same term, then whichever log is longer is
166             // more up-to-date.
167             if (requestVote.getLastLogTerm() > lastTerm()) {
168                 candidateLatest = true;
169             } else if ((requestVote.getLastLogTerm() == lastTerm())
170                 && requestVote.getLastLogIndex() >= lastIndex()) {
171                 candidateLatest = true;
172             }
173
174             if (candidateLatest) {
175                 grantVote = true;
176                 context.getTermInformation().update(requestVote.getTerm(),
177                     requestVote.getCandidateId());
178             }
179         }
180
181         sender.tell(new RequestVoteReply(currentTerm(), grantVote), actor());
182
183         return suggestedState;
184     }
185
186     /**
187      * Derived classes should not directly handle RequestVoteReply messages it
188      * should let the base class handle it first. Once the base class handles
189      * the RequestVoteReply message and does the common actions that are
190      * applicable in all RaftState's it will delegate the handling of the
191      * RequestVoteReply message to the derived class to do more state specific
192      * handling by calling this method
193      *
194      * @param sender           The actor that sent this message
195      * @param requestVoteReply The RequestVoteReply message
196      * @param suggestedState   The state that the RaftActor should be in based
197      *                         on the base class's processing of the RequestVote
198      *                         message
199      * @return
200      */
201
202     protected abstract RaftState handleRequestVoteReply(ActorRef sender,
203         RequestVoteReply requestVoteReply, RaftState suggestedState);
204
205     protected FiniteDuration electionDuration() {
206         long variance = new Random().nextInt(ELECTION_TIME_MAX_VARIANCE);
207         return new FiniteDuration(ELECTION_TIME_INTERVAL + variance,
208             TimeUnit.MILLISECONDS);
209     }
210
211     protected void stopElection() {
212         if (electionCancel != null && !electionCancel.isCancelled()) {
213             electionCancel.cancel();
214         }
215     }
216
217     protected void scheduleElection(FiniteDuration interval) {
218
219         stopElection();
220
221         // Schedule an election. When the scheduler triggers an ElectionTimeout
222         // message is sent to itself
223         electionCancel =
224             context.getActorSystem().scheduler().scheduleOnce(interval,
225                 context.getActor(), new ElectionTimeout(),
226                 context.getActorSystem().dispatcher(), context.getActor());
227     }
228
229     protected long currentTerm() {
230         return context.getTermInformation().getCurrentTerm();
231     }
232
233     protected String votedFor() {
234         return context.getTermInformation().getVotedFor();
235     }
236
237     protected ActorRef actor() {
238         return context.getActor();
239     }
240
241     protected long lastTerm() {
242         return context.getReplicatedLog().lastTerm();
243     }
244
245     protected long lastIndex() {
246         return context.getReplicatedLog().lastIndex();
247     }
248
249     protected ClientRequestTracker findClientRequestTracker(long logIndex) {
250         return null;
251     }
252
253     protected void applyLogToStateMachine(long index) {
254         // Now maybe we apply to the state machine
255         for (long i = context.getLastApplied() + 1;
256              i < index + 1; i++) {
257             ActorRef clientActor = null;
258             String identifier = null;
259             ClientRequestTracker tracker = findClientRequestTracker(i);
260
261             if (tracker != null) {
262                 clientActor = tracker.getClientActor();
263                 identifier = tracker.getIdentifier();
264             }
265             ReplicatedLogEntry replicatedLogEntry =
266                 context.getReplicatedLog().get(i);
267
268             if (replicatedLogEntry != null) {
269                 actor().tell(new ApplyState(clientActor, identifier,
270                     replicatedLogEntry), actor());
271             } else {
272                 context.getLogger().error(
273                     "Missing index " + i + " from log. Cannot apply state.");
274             }
275         }
276         // Send a local message to the local RaftActor (it's derived class to be
277         // specific to apply the log to it's index)
278         context.setLastApplied(index);
279     }
280
281     @Override
282     public RaftState handleMessage(ActorRef sender, Object message) {
283         RaftState raftState = state();
284         if (message instanceof RaftRPC) {
285             raftState = applyTerm((RaftRPC) message);
286         }
287         if (message instanceof AppendEntries) {
288             raftState = appendEntries(sender, (AppendEntries) message,
289                 raftState);
290         } else if (message instanceof AppendEntriesReply) {
291             raftState =
292                 handleAppendEntriesReply(sender, (AppendEntriesReply) message,
293                     raftState);
294         } else if (message instanceof RequestVote) {
295             raftState =
296                 requestVote(sender, (RequestVote) message, raftState);
297         } else if (message instanceof RequestVoteReply) {
298             raftState =
299                 handleRequestVoteReply(sender, (RequestVoteReply) message,
300                     raftState);
301         }
302         return raftState;
303     }
304
305     @Override public String getLeaderId() {
306         return leaderId;
307     }
308
309     private RaftState applyTerm(RaftRPC rpc) {
310         // If RPC request or response contains term T > currentTerm:
311         // set currentTerm = T, convert to follower (§5.1)
312         // This applies to all RPC messages and responses
313         if (rpc.getTerm() > context.getTermInformation().getCurrentTerm()) {
314             context.getTermInformation().update(rpc.getTerm(), null);
315             return RaftState.Follower;
316         }
317         return state();
318     }
319
320 }