Remove AbstractRaftActorBehavior#findClientRequestTracker()
[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 com.google.common.base.Preconditions;
14 import java.util.Random;
15 import java.util.concurrent.TimeUnit;
16 import org.opendaylight.controller.cluster.raft.ClientRequestTracker;
17 import org.opendaylight.controller.cluster.raft.RaftActorContext;
18 import org.opendaylight.controller.cluster.raft.RaftState;
19 import org.opendaylight.controller.cluster.raft.ReplicatedLogEntry;
20 import org.opendaylight.controller.cluster.raft.SerializationUtils;
21 import org.opendaylight.controller.cluster.raft.base.messages.ApplyJournalEntries;
22 import org.opendaylight.controller.cluster.raft.base.messages.ApplyState;
23 import org.opendaylight.controller.cluster.raft.base.messages.ElectionTimeout;
24 import org.opendaylight.controller.cluster.raft.messages.AppendEntries;
25 import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
26 import org.opendaylight.controller.cluster.raft.messages.RequestVote;
27 import org.opendaylight.controller.cluster.raft.messages.RequestVoteReply;
28 import org.slf4j.Logger;
29 import scala.concurrent.duration.FiniteDuration;
30
31 /**
32  * Abstract class that represents the behavior of a RaftActor
33  * <p/>
34  * All Servers:
35  * <ul>
36  * <li> If commitIndex > lastApplied: increment lastApplied, apply
37  * log[lastApplied] to state machine (§5.3)
38  * <li> If RPC request or response contains term T > currentTerm:
39  * set currentTerm = T, convert to follower (§5.1)
40  */
41 public abstract class AbstractRaftActorBehavior implements RaftActorBehavior {
42     /**
43      * Information about the RaftActor whose behavior this class represents
44      */
45     protected final RaftActorContext context;
46
47     /**
48      *
49      */
50     protected final Logger LOG;
51
52     /**
53      *
54      */
55     private Cancellable electionCancel = null;
56
57     private long replicatedToAllIndex = -1;
58
59     private final String logName;
60
61     private final RaftState state;
62
63     AbstractRaftActorBehavior(final RaftActorContext context, final RaftState state) {
64         this.context = Preconditions.checkNotNull(context);
65         this.state = Preconditions.checkNotNull(state);
66         this.LOG = context.getLogger();
67
68         logName = String.format("%s (%s)", context.getId(), state);
69     }
70
71     public static RaftActorBehavior createBehavior(final RaftActorContext context, final RaftState state) {
72         switch (state) {
73             case Candidate:
74                 return new Candidate(context);
75             case Follower:
76                 return new Follower(context);
77             case IsolatedLeader:
78                 return new IsolatedLeader(context);
79             case Leader:
80                 return new Leader(context);
81             default:
82                 throw new IllegalArgumentException("Unhandled state " + state);
83         }
84     }
85
86     @Override
87     public final RaftState state() {
88         return state;
89     }
90
91     protected final String logName() {
92         return logName;
93     }
94
95     @Override
96     public void setReplicatedToAllIndex(long replicatedToAllIndex) {
97         this.replicatedToAllIndex = replicatedToAllIndex;
98     }
99
100     @Override
101     public long getReplicatedToAllIndex() {
102         return replicatedToAllIndex;
103     }
104
105     /**
106      * Derived classes should not directly handle AppendEntries messages it
107      * should let the base class handle it first. Once the base class handles
108      * the AppendEntries message and does the common actions that are applicable
109      * in all RaftState's it will delegate the handling of the AppendEntries
110      * message to the derived class to do more state specific handling by calling
111      * this method
112      *
113      * @param sender         The actor that sent this message
114      * @param appendEntries  The AppendEntries message
115      * @return a new behavior if it was changed or the current behavior
116      */
117     protected abstract RaftActorBehavior handleAppendEntries(ActorRef sender,
118         AppendEntries appendEntries);
119
120
121     /**
122      * appendEntries first processes the AppendEntries message and then
123      * delegates handling to a specific behavior
124      *
125      * @param sender
126      * @param appendEntries
127      * @return a new behavior if it was changed or the current behavior
128      */
129     protected RaftActorBehavior appendEntries(ActorRef sender,
130         AppendEntries appendEntries) {
131
132         // 1. Reply false if term < currentTerm (§5.1)
133         if (appendEntries.getTerm() < currentTerm()) {
134             if(LOG.isDebugEnabled()) {
135                 LOG.debug("{}: Cannot append entries because sender term {} is less than {}",
136                         logName(), appendEntries.getTerm(), currentTerm());
137             }
138
139             sender.tell(
140                 new AppendEntriesReply(context.getId(), currentTerm(), false,
141                     lastIndex(), lastTerm(), context.getPayloadVersion()), actor()
142             );
143             return this;
144         }
145
146
147         return handleAppendEntries(sender, appendEntries);
148     }
149
150     /**
151      * Derived classes should not directly handle AppendEntriesReply messages it
152      * should let the base class handle it first. Once the base class handles
153      * the AppendEntriesReply message and does the common actions that are
154      * applicable in all RaftState's it will delegate the handling of the
155      * AppendEntriesReply message to the derived class to do more state specific
156      * handling by calling this method
157      *
158      * @param sender             The actor that sent this message
159      * @param appendEntriesReply The AppendEntriesReply message
160      * @return a new behavior if it was changed or the current behavior
161      */
162     protected abstract RaftActorBehavior handleAppendEntriesReply(ActorRef sender,
163         AppendEntriesReply appendEntriesReply);
164
165     /**
166      * requestVote handles the RequestVote message. This logic is common
167      * for all behaviors
168      *
169      * @param sender
170      * @param requestVote
171      * @return a new behavior if it was changed or the current behavior
172      */
173     protected RaftActorBehavior requestVote(ActorRef sender, RequestVote requestVote) {
174
175         LOG.debug("{}: In requestVote:  {}", logName(), requestVote);
176
177         boolean grantVote = canGrantVote(requestVote);
178
179         if(grantVote) {
180             context.getTermInformation().updateAndPersist(requestVote.getTerm(), requestVote.getCandidateId());
181         }
182
183         RequestVoteReply reply = new RequestVoteReply(currentTerm(), grantVote);
184
185         LOG.debug("{}: requestVote returning: {}", logName(), reply);
186
187         sender.tell(reply, actor());
188
189         return this;
190     }
191
192     protected boolean canGrantVote(RequestVote requestVote){
193         boolean grantVote = false;
194
195         //  Reply false if term < currentTerm (§5.1)
196         if (requestVote.getTerm() < currentTerm()) {
197             grantVote = false;
198
199             // If votedFor is null or candidateId, and candidate’s log is at
200             // least as up-to-date as receiver’s log, grant vote (§5.2, §5.4)
201         } else if (votedFor() == null || votedFor()
202                 .equals(requestVote.getCandidateId())) {
203
204             boolean candidateLatest = false;
205
206             // From §5.4.1
207             // Raft determines which of two logs is more up-to-date
208             // by comparing the index and term of the last entries in the
209             // logs. If the logs have last entries with different terms, then
210             // the log with the later term is more up-to-date. If the logs
211             // end with the same term, then whichever log is longer is
212             // more up-to-date.
213             if (requestVote.getLastLogTerm() > lastTerm()) {
214                 candidateLatest = true;
215             } else if ((requestVote.getLastLogTerm() == lastTerm())
216                     && requestVote.getLastLogIndex() >= lastIndex()) {
217                 candidateLatest = true;
218             }
219
220             if (candidateLatest) {
221                 grantVote = true;
222             }
223         }
224         return grantVote;
225     }
226
227     /**
228      * Derived classes should not directly handle RequestVoteReply messages it
229      * should let the base class handle it first. Once the base class handles
230      * the RequestVoteReply message and does the common actions that are
231      * applicable in all RaftState's it will delegate the handling of the
232      * RequestVoteReply message to the derived class to do more state specific
233      * handling by calling this method
234      *
235      * @param sender           The actor that sent this message
236      * @param requestVoteReply The RequestVoteReply message
237      * @return a new behavior if it was changed or the current behavior
238      */
239     protected abstract RaftActorBehavior handleRequestVoteReply(ActorRef sender,
240         RequestVoteReply requestVoteReply);
241
242     /**
243      *
244      * @return a random election duration
245      */
246     protected FiniteDuration electionDuration() {
247         long variance = new Random().nextInt(context.getConfigParams().getElectionTimeVariance());
248         return context.getConfigParams().getElectionTimeOutInterval().$plus(
249                 new FiniteDuration(variance, TimeUnit.MILLISECONDS));
250     }
251
252     /**
253      * stop the scheduled election
254      */
255     protected void stopElection() {
256         if (electionCancel != null && !electionCancel.isCancelled()) {
257             electionCancel.cancel();
258         }
259     }
260
261     protected boolean canStartElection() {
262         return context.getRaftPolicy().automaticElectionsEnabled() && context.isVotingMember();
263     }
264
265     /**
266      * schedule a new election
267      *
268      * @param interval the duration after which we should trigger a new election
269      */
270     protected void scheduleElection(FiniteDuration interval) {
271         stopElection();
272
273         if(canStartElection()) {
274             // Schedule an election. When the scheduler triggers an ElectionTimeout message is sent to itself
275             electionCancel = context.getActorSystem().scheduler().scheduleOnce(interval, context.getActor(),
276                     ElectionTimeout.INSTANCE, context.getActorSystem().dispatcher(), context.getActor());
277         }
278     }
279
280     /**
281      * @return the current term
282      */
283     protected long currentTerm() {
284         return context.getTermInformation().getCurrentTerm();
285     }
286
287     /**
288      * @return the candidate for whom we voted in the current term
289      */
290     protected String votedFor() {
291         return context.getTermInformation().getVotedFor();
292     }
293
294     /**
295      * @return the actor associated with this behavior
296      */
297     protected ActorRef actor() {
298         return context.getActor();
299     }
300
301     /**
302      *
303      * @return the term from the last entry in the log
304      */
305     protected long lastTerm() {
306         return context.getReplicatedLog().lastTerm();
307     }
308
309     /**
310      * @return the index from the last entry in the log
311      */
312     protected long lastIndex() {
313         return context.getReplicatedLog().lastIndex();
314     }
315
316     /**
317      * @param logIndex
318      * @return the client request tracker for the specified logIndex
319      */
320     protected ClientRequestTracker removeClientRequestTracker(long logIndex) {
321         return null;
322     }
323
324     /**
325      *
326      * @return log index from the previous to last entry in the log
327      */
328     protected long prevLogIndex(long index){
329         ReplicatedLogEntry prevEntry =
330             context.getReplicatedLog().get(index - 1);
331         if (prevEntry != null) {
332             return prevEntry.getIndex();
333         }
334         return -1;
335     }
336
337     /**
338      * @return log term from the previous to last entry in the log
339      */
340     protected long prevLogTerm(long index){
341         ReplicatedLogEntry prevEntry =
342             context.getReplicatedLog().get(index - 1);
343         if (prevEntry != null) {
344             return prevEntry.getTerm();
345         }
346         return -1;
347     }
348
349     /**
350      * Apply the provided index to the state machine
351      *
352      * @param index a log index that is known to be committed
353      */
354     protected void applyLogToStateMachine(final long index) {
355         long newLastApplied = context.getLastApplied();
356         // Now maybe we apply to the state machine
357         for (long i = context.getLastApplied() + 1; i < index + 1; i++) {
358
359             ReplicatedLogEntry replicatedLogEntry = context.getReplicatedLog().get(i);
360             if (replicatedLogEntry != null) {
361                 // Send a local message to the local RaftActor (it's derived class to be
362                 // specific to apply the log to it's index)
363
364                 final ApplyState msg;
365                 final ClientRequestTracker tracker = removeClientRequestTracker(i);
366                 if (tracker != null) {
367                     msg = new ApplyState(tracker.getClientActor(), tracker.getIdentifier(), replicatedLogEntry);
368                 } else {
369                     msg = new ApplyState(null, null, replicatedLogEntry);
370                 }
371
372                 actor().tell(msg, actor());
373                 newLastApplied = i;
374             } else {
375                 //if one index is not present in the log, no point in looping
376                 // around as the rest wont be present either
377                 LOG.warn("{}: Missing index {} from log. Cannot apply state. Ignoring {} to {}",
378                         logName(), i, i, index);
379                 break;
380             }
381         }
382         if(LOG.isDebugEnabled()) {
383             LOG.debug("{}: Setting last applied to {}", logName(), newLastApplied);
384         }
385         context.setLastApplied(newLastApplied);
386
387         // send a message to persist a ApplyLogEntries marker message into akka's persistent journal
388         // will be used during recovery
389         //in case if the above code throws an error and this message is not sent, it would be fine
390         // as the  append entries received later would initiate add this message to the journal
391         actor().tell(new ApplyJournalEntries(context.getLastApplied()), actor());
392     }
393
394     protected Object fromSerializableMessage(Object serializable){
395         return SerializationUtils.fromSerializable(serializable);
396     }
397
398     @Override
399     public RaftActorBehavior handleMessage(ActorRef sender, Object message) {
400         if (message instanceof AppendEntries) {
401             return appendEntries(sender, (AppendEntries) message);
402         } else if (message instanceof AppendEntriesReply) {
403             return handleAppendEntriesReply(sender, (AppendEntriesReply) message);
404         } else if (message instanceof RequestVote) {
405             return requestVote(sender, (RequestVote) message);
406         } else if (message instanceof RequestVoteReply) {
407             return handleRequestVoteReply(sender, (RequestVoteReply) message);
408         } else {
409             return null;
410         }
411     }
412
413     @Override
414     public RaftActorBehavior switchBehavior(RaftActorBehavior behavior) {
415         return internalSwitchBehavior(behavior);
416     }
417
418     protected RaftActorBehavior internalSwitchBehavior(RaftState newState) {
419         if(context.getRaftPolicy().automaticElectionsEnabled()){
420             return internalSwitchBehavior(createBehavior(context, newState));
421         }
422         return this;
423     }
424
425     private RaftActorBehavior internalSwitchBehavior(RaftActorBehavior newBehavior) {
426         LOG.info("{} :- Switching from behavior {} to {}", logName(), this.state(), newBehavior.state());
427         try {
428             close();
429         } catch (Exception e) {
430             LOG.error("{}: Failed to close behavior : {}", logName(), this.state(), e);
431         }
432         return newBehavior;
433     }
434
435
436     protected int getMajorityVoteCount(int numPeers) {
437         // Votes are required from a majority of the peers including self.
438         // The numMajority field therefore stores a calculated value
439         // of the number of votes required for this candidate to win an
440         // election based on it's known peers.
441         // If a peer was added during normal operation and raft replicas
442         // came to know about them then the new peer would also need to be
443         // taken into consideration when calculating this value.
444         // Here are some examples for what the numMajority would be for n
445         // peers
446         // 0 peers = 1 numMajority -: (0 + 1) / 2 + 1 = 1
447         // 2 peers = 2 numMajority -: (2 + 1) / 2 + 1 = 2
448         // 4 peers = 3 numMajority -: (4 + 1) / 2 + 1 = 3
449
450         int numMajority = 0;
451         if (numPeers > 0) {
452             int self = 1;
453             numMajority = (numPeers + self) / 2 + 1;
454         }
455         return numMajority;
456
457     }
458
459
460     /**
461      * Performs a snapshot with no capture on the replicated log.
462      * It clears the log from the supplied index or last-applied-1 which ever is minimum.
463      *
464      * @param snapshotCapturedIndex
465      */
466     protected void performSnapshotWithoutCapture(final long snapshotCapturedIndex) {
467         long actualIndex = context.getSnapshotManager().trimLog(snapshotCapturedIndex);
468
469         if(actualIndex != -1){
470             setReplicatedToAllIndex(actualIndex);
471         }
472     }
473
474     protected String getId(){
475         return context.getId();
476     }
477 }