Merge "Created Sample Feature Test Class for Base Feature Repository"
[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.SerializationUtils;
18 import org.opendaylight.controller.cluster.raft.base.messages.ApplyState;
19 import org.opendaylight.controller.cluster.raft.base.messages.ElectionTimeout;
20 import org.opendaylight.controller.cluster.raft.messages.AppendEntries;
21 import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
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      *
48      */
49     private Cancellable electionCancel = null;
50
51     /**
52      *
53      */
54     protected String leaderId = null;
55
56
57     protected AbstractRaftActorBehavior(RaftActorContext context) {
58         this.context = context;
59     }
60
61     /**
62      * Derived classes should not directly handle AppendEntries messages it
63      * should let the base class handle it first. Once the base class handles
64      * the AppendEntries message and does the common actions that are applicable
65      * in all RaftState's it will delegate the handling of the AppendEntries
66      * message to the derived class to do more state specific handling by calling
67      * this method
68      *
69      * @param sender         The actor that sent this message
70      * @param appendEntries  The AppendEntries message
71      * @return
72      */
73     protected abstract RaftState handleAppendEntries(ActorRef sender,
74         AppendEntries appendEntries);
75
76
77     /**
78      * appendEntries first processes the AppendEntries message and then
79      * delegates handling to a specific behavior
80      *
81      * @param sender
82      * @param appendEntries
83      * @return
84      */
85     protected RaftState appendEntries(ActorRef sender,
86         AppendEntries appendEntries) {
87
88         // 1. Reply false if term < currentTerm (§5.1)
89         if (appendEntries.getTerm() < currentTerm()) {
90             context.getLogger().debug(
91                 "Cannot append entries because sender term " + appendEntries
92                     .getTerm() + " is less than " + currentTerm());
93             sender.tell(
94                 new AppendEntriesReply(context.getId(), currentTerm(), false,
95                     lastIndex(), lastTerm()), actor()
96             );
97             return state();
98         }
99
100
101         return handleAppendEntries(sender, appendEntries);
102     }
103
104     /**
105      * Derived classes should not directly handle AppendEntriesReply messages it
106      * should let the base class handle it first. Once the base class handles
107      * the AppendEntriesReply message and does the common actions that are
108      * applicable in all RaftState's it will delegate the handling of the
109      * AppendEntriesReply message to the derived class to do more state specific
110      * handling by calling this method
111      *
112      * @param sender             The actor that sent this message
113      * @param appendEntriesReply The AppendEntriesReply message
114      * @return
115      */
116     protected abstract RaftState handleAppendEntriesReply(ActorRef sender,
117         AppendEntriesReply appendEntriesReply);
118
119     /**
120      * requestVote handles the RequestVote message. This logic is common
121      * for all behaviors
122      *
123      * @param sender
124      * @param requestVote
125      * @return
126      */
127     protected RaftState requestVote(ActorRef sender,
128         RequestVote requestVote) {
129
130         boolean grantVote = false;
131
132         //  Reply false if term < currentTerm (§5.1)
133         if (requestVote.getTerm() < currentTerm()) {
134             grantVote = false;
135
136             // If votedFor is null or candidateId, and candidate’s log is at
137             // least as up-to-date as receiver’s log, grant vote (§5.2, §5.4)
138         } else if (votedFor() == null || votedFor()
139             .equals(requestVote.getCandidateId())) {
140
141             boolean candidateLatest = false;
142
143             // From §5.4.1
144             // Raft determines which of two logs is more up-to-date
145             // by comparing the index and term of the last entries in the
146             // logs. If the logs have last entries with different terms, then
147             // the log with the later term is more up-to-date. If the logs
148             // end with the same term, then whichever log is longer is
149             // more up-to-date.
150             if (requestVote.getLastLogTerm() > lastTerm()) {
151                 candidateLatest = true;
152             } else if ((requestVote.getLastLogTerm() == lastTerm())
153                 && requestVote.getLastLogIndex() >= lastIndex()) {
154                 candidateLatest = true;
155             }
156
157             if (candidateLatest) {
158                 grantVote = true;
159                 context.getTermInformation().updateAndPersist(requestVote.getTerm(),
160                     requestVote.getCandidateId());
161             }
162         }
163
164         sender.tell(new RequestVoteReply(currentTerm(), grantVote), actor());
165
166         return state();
167     }
168
169     /**
170      * Derived classes should not directly handle RequestVoteReply messages it
171      * should let the base class handle it first. Once the base class handles
172      * the RequestVoteReply message and does the common actions that are
173      * applicable in all RaftState's it will delegate the handling of the
174      * RequestVoteReply message to the derived class to do more state specific
175      * handling by calling this method
176      *
177      * @param sender           The actor that sent this message
178      * @param requestVoteReply The RequestVoteReply message
179      * @return
180      */
181     protected abstract RaftState handleRequestVoteReply(ActorRef sender,
182         RequestVoteReply requestVoteReply);
183
184     /**
185      * Creates a random election duration
186      *
187      * @return
188      */
189     protected FiniteDuration electionDuration() {
190         long variance = new Random().nextInt(context.getConfigParams().getElectionTimeVariance());
191         return context.getConfigParams().getElectionTimeOutInterval().$plus(
192             new FiniteDuration(variance, TimeUnit.MILLISECONDS));
193     }
194
195     /**
196      * stop the scheduled election
197      */
198     protected void stopElection() {
199         if (electionCancel != null && !electionCancel.isCancelled()) {
200             electionCancel.cancel();
201         }
202     }
203
204     /**
205      * schedule a new election
206      *
207      * @param interval
208      */
209     protected void scheduleElection(FiniteDuration interval) {
210         stopElection();
211
212         // Schedule an election. When the scheduler triggers an ElectionTimeout
213         // message is sent to itself
214         electionCancel =
215             context.getActorSystem().scheduler().scheduleOnce(interval,
216                 context.getActor(), new ElectionTimeout(),
217                 context.getActorSystem().dispatcher(), context.getActor());
218     }
219
220     /**
221      * Get the current term
222      * @return
223      */
224     protected long currentTerm() {
225         return context.getTermInformation().getCurrentTerm();
226     }
227
228     /**
229      * Get the candidate for whom we voted in the current term
230      * @return
231      */
232     protected String votedFor() {
233         return context.getTermInformation().getVotedFor();
234     }
235
236     /**
237      * Get the actor associated with this behavior
238      * @return
239      */
240     protected ActorRef actor() {
241         return context.getActor();
242     }
243
244     /**
245      * Get the term from the last entry in the log
246      *
247      * @return
248      */
249     protected long lastTerm() {
250         return context.getReplicatedLog().lastTerm();
251     }
252
253     /**
254      * Get the index from the last entry in the log
255      *
256      * @return
257      */
258     protected long lastIndex() {
259         return context.getReplicatedLog().lastIndex();
260     }
261
262     /**
263      * Find the client request tracker for a specific logIndex
264      *
265      * @param logIndex
266      * @return
267      */
268     protected ClientRequestTracker findClientRequestTracker(long logIndex) {
269         return null;
270     }
271
272     /**
273      * Find the log index from the previous to last entry in the log
274      *
275      * @return
276      */
277     protected long prevLogIndex(long index){
278         ReplicatedLogEntry prevEntry =
279             context.getReplicatedLog().get(index - 1);
280         if (prevEntry != null) {
281             return prevEntry.getIndex();
282         }
283         return -1;
284     }
285
286     /**
287      * Find the log term from the previous to last entry in the log
288      * @return
289      */
290     protected long prevLogTerm(long index){
291         ReplicatedLogEntry prevEntry =
292             context.getReplicatedLog().get(index - 1);
293         if (prevEntry != null) {
294             return prevEntry.getTerm();
295         }
296         return -1;
297     }
298
299     /**
300      * Apply the provided index to the state machine
301      *
302      * @param index a log index that is known to be committed
303      */
304     protected void applyLogToStateMachine(long index) {
305         // Now maybe we apply to the state machine
306         for (long i = context.getLastApplied() + 1;
307              i < index + 1; i++) {
308             ActorRef clientActor = null;
309             String identifier = null;
310             ClientRequestTracker tracker = findClientRequestTracker(i);
311
312             if (tracker != null) {
313                 clientActor = tracker.getClientActor();
314                 identifier = tracker.getIdentifier();
315             }
316             ReplicatedLogEntry replicatedLogEntry =
317                 context.getReplicatedLog().get(i);
318
319             if (replicatedLogEntry != null) {
320                 actor().tell(new ApplyState(clientActor, identifier,
321                     replicatedLogEntry), actor());
322             } else {
323                 context.getLogger().error(
324                     "Missing index " + i + " from log. Cannot apply state.");
325             }
326         }
327         // Send a local message to the local RaftActor (it's derived class to be
328         // specific to apply the log to it's index)
329         context.setLastApplied(index);
330     }
331
332     protected Object fromSerializableMessage(Object serializable){
333         return SerializationUtils.fromSerializable(serializable);
334     }
335
336     @Override
337     public RaftState handleMessage(ActorRef sender, Object message) {
338         if (message instanceof AppendEntries) {
339             return appendEntries(sender, (AppendEntries) message);
340         } else if (message instanceof AppendEntriesReply) {
341             return handleAppendEntriesReply(sender, (AppendEntriesReply) message);
342         } else if (message instanceof RequestVote) {
343             return requestVote(sender, (RequestVote) message);
344         } else if (message instanceof RequestVoteReply) {
345             return handleRequestVoteReply(sender, (RequestVoteReply) message);
346         }
347         return state();
348     }
349
350     @Override public String getLeaderId() {
351         return leaderId;
352     }
353 }