befc6d412962a7395608c4ee1981b02014f5986d
[controller.git] / opendaylight / md-sal / sal-akka-raft / src / main / java / org / opendaylight / controller / cluster / raft / behaviors / AbstractLeader.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.ActorSelection;
13 import akka.actor.Cancellable;
14 import com.google.common.annotations.VisibleForTesting;
15 import com.google.common.base.Optional;
16 import com.google.common.base.Preconditions;
17 import com.google.protobuf.ByteString;
18 import java.io.IOException;
19 import java.util.Arrays;
20 import java.util.Collection;
21 import java.util.Collections;
22 import java.util.HashMap;
23 import java.util.Iterator;
24 import java.util.LinkedList;
25 import java.util.List;
26 import java.util.Map;
27 import java.util.Map.Entry;
28 import java.util.Queue;
29 import javax.annotation.Nullable;
30 import org.opendaylight.controller.cluster.raft.ClientRequestTracker;
31 import org.opendaylight.controller.cluster.raft.ClientRequestTrackerImpl;
32 import org.opendaylight.controller.cluster.raft.FollowerLogInformation;
33 import org.opendaylight.controller.cluster.raft.FollowerLogInformationImpl;
34 import org.opendaylight.controller.cluster.raft.PeerInfo;
35 import org.opendaylight.controller.cluster.raft.RaftActorContext;
36 import org.opendaylight.controller.cluster.raft.RaftState;
37 import org.opendaylight.controller.cluster.raft.ReplicatedLogEntry;
38 import org.opendaylight.controller.cluster.raft.Snapshot;
39 import org.opendaylight.controller.cluster.raft.VotingState;
40 import org.opendaylight.controller.cluster.raft.base.messages.Replicate;
41 import org.opendaylight.controller.cluster.raft.base.messages.SendHeartBeat;
42 import org.opendaylight.controller.cluster.raft.base.messages.SendInstallSnapshot;
43 import org.opendaylight.controller.cluster.raft.messages.AppendEntries;
44 import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
45 import org.opendaylight.controller.cluster.raft.messages.InstallSnapshot;
46 import org.opendaylight.controller.cluster.raft.messages.InstallSnapshotReply;
47 import org.opendaylight.controller.cluster.raft.messages.RaftRPC;
48 import org.opendaylight.controller.cluster.raft.messages.RequestVoteReply;
49 import org.opendaylight.controller.cluster.raft.messages.UnInitializedFollowerSnapshotReply;
50 import org.opendaylight.controller.cluster.raft.persisted.ServerConfigurationPayload;
51 import scala.concurrent.duration.FiniteDuration;
52
53 /**
54  * The behavior of a RaftActor when it is in the Leader state
55  * <p/>
56  * Leaders:
57  * <ul>
58  * <li> Upon election: send initial empty AppendEntries RPCs
59  * (heartbeat) to each server; repeat during idle periods to
60  * prevent election timeouts (§5.2)
61  * <li> If command received from client: append entry to local log,
62  * respond after entry applied to state machine (§5.3)
63  * <li> If last log index ≥ nextIndex for a follower: send
64  * AppendEntries RPC with log entries starting at nextIndex
65  * <ul>
66  * <li> If successful: update nextIndex and matchIndex for
67  * follower (§5.3)
68  * <li> If AppendEntries fails because of log inconsistency:
69  * decrement nextIndex and retry (§5.3)
70  * </ul>
71  * <li> If there exists an N such that N > commitIndex, a majority
72  * of matchIndex[i] ≥ N, and log[N].term == currentTerm:
73  * set commitIndex = N (§5.3, §5.4).
74  */
75 public abstract class AbstractLeader extends AbstractRaftActorBehavior {
76
77     // The index of the first chunk that is sent when installing a snapshot
78     public static final int FIRST_CHUNK_INDEX = 1;
79
80     // The index that the follower should respond with if it needs the install snapshot to be reset
81     public static final int INVALID_CHUNK_INDEX = -1;
82
83     // This would be passed as the hash code of the last chunk when sending the first chunk
84     public static final int INITIAL_LAST_CHUNK_HASH_CODE = -1;
85
86     private final Map<String, FollowerLogInformation> followerToLog = new HashMap<>();
87     private final Map<String, FollowerToSnapshot> mapFollowerToSnapshot = new HashMap<>();
88
89     /**
90      * Lookup table for request contexts based on journal index. We could use a {@link Map} here, but we really
91      * expect the entries to be modified in sequence, hence we open-code the lookup.
92      *
93      * TODO: Evaluate the use of ArrayDeque(), as that has lower memory overhead. Non-head removals are more costly,
94      *       but we already expect those to be far from frequent.
95      */
96     private final Queue<ClientRequestTracker> trackers = new LinkedList<>();
97
98     private Cancellable heartbeatSchedule = null;
99     private Optional<SnapshotHolder> snapshot;
100     private int minReplicationCount;
101
102     protected AbstractLeader(RaftActorContext context, RaftState state,
103             @Nullable AbstractLeader initializeFromLeader) {
104         super(context, state);
105
106         if(initializeFromLeader != null) {
107             followerToLog.putAll(initializeFromLeader.followerToLog);
108         } else {
109             for(PeerInfo peerInfo: context.getPeers()) {
110                 FollowerLogInformation followerLogInformation = new FollowerLogInformationImpl(peerInfo, -1, context);
111                 followerToLog.put(peerInfo.getId(), followerLogInformation);
112             }
113         }
114
115         LOG.debug("{}: Election: Leader has following peers: {}", logName(), getFollowerIds());
116
117         updateMinReplicaCount();
118
119         snapshot = Optional.absent();
120
121         // Immediately schedule a heartbeat
122         // Upon election: send initial empty AppendEntries RPCs
123         // (heartbeat) to each server; repeat during idle periods to
124         // prevent election timeouts (§5.2)
125         sendAppendEntries(0, false);
126
127         // It is important to schedule this heartbeat here
128         scheduleHeartBeat(context.getConfigParams().getHeartBeatInterval());
129     }
130
131     protected AbstractLeader(RaftActorContext context, RaftState state) {
132         this(context, state, null);
133     }
134
135     /**
136      * Return an immutable collection of follower identifiers.
137      *
138      * @return Collection of follower IDs
139      */
140     public final Collection<String> getFollowerIds() {
141         return followerToLog.keySet();
142     }
143
144     public void addFollower(String followerId) {
145         FollowerLogInformation followerLogInformation = new FollowerLogInformationImpl(
146                 context.getPeerInfo(followerId), -1, context);
147         followerToLog.put(followerId, followerLogInformation);
148
149         if(heartbeatSchedule == null) {
150             scheduleHeartBeat(context.getConfigParams().getHeartBeatInterval());
151         }
152     }
153
154     public void removeFollower(String followerId) {
155         followerToLog.remove(followerId);
156         mapFollowerToSnapshot.remove(followerId);
157     }
158
159     public void updateMinReplicaCount() {
160         int numVoting = 0;
161         for(PeerInfo peer: context.getPeers()) {
162             if(peer.isVoting()) {
163                 numVoting++;
164             }
165         }
166
167         minReplicationCount = getMajorityVoteCount(numVoting);
168     }
169
170     protected int getMinIsolatedLeaderPeerCount(){
171       //the isolated Leader peer count will be 1 less than the majority vote count.
172         //this is because the vote count has the self vote counted in it
173         //for e.g
174         //0 peers = 1 votesRequired , minIsolatedLeaderPeerCount = 0
175         //2 peers = 2 votesRequired , minIsolatedLeaderPeerCount = 1
176         //4 peers = 3 votesRequired, minIsolatedLeaderPeerCount = 2
177
178         return minReplicationCount > 0 ? (minReplicationCount - 1) : 0;
179     }
180
181     @VisibleForTesting
182     void setSnapshot(@Nullable Snapshot snapshot) {
183         if(snapshot != null) {
184             this.snapshot = Optional.of(new SnapshotHolder(snapshot));
185         } else {
186             this.snapshot = Optional.absent();
187         }
188     }
189
190     @Override
191     protected RaftActorBehavior handleAppendEntries(ActorRef sender,
192         AppendEntries appendEntries) {
193
194         LOG.debug("{}: handleAppendEntries: {}", logName(), appendEntries);
195
196         return this;
197     }
198
199     @Override
200     protected RaftActorBehavior handleAppendEntriesReply(ActorRef sender,
201         AppendEntriesReply appendEntriesReply) {
202
203         if(LOG.isTraceEnabled()) {
204             LOG.trace("{}: handleAppendEntriesReply: {}", logName(), appendEntriesReply);
205         }
206
207         // Update the FollowerLogInformation
208         String followerId = appendEntriesReply.getFollowerId();
209         FollowerLogInformation followerLogInformation =
210             followerToLog.get(followerId);
211
212         if(followerLogInformation == null){
213             LOG.error("{}: handleAppendEntriesReply - unknown follower {}", logName(), followerId);
214             return this;
215         }
216
217         if(followerLogInformation.timeSinceLastActivity() >
218                 context.getConfigParams().getElectionTimeOutInterval().toMillis()) {
219             LOG.warn("{} : handleAppendEntriesReply delayed beyond election timeout, " +
220                             "appendEntriesReply : {}, timeSinceLastActivity : {}, lastApplied : {}, commitIndex : {}",
221                     logName(), appendEntriesReply, followerLogInformation.timeSinceLastActivity(),
222                     context.getLastApplied(), context.getCommitIndex());
223         }
224
225         followerLogInformation.markFollowerActive();
226         followerLogInformation.setPayloadVersion(appendEntriesReply.getPayloadVersion());
227         followerLogInformation.setRaftVersion(appendEntriesReply.getRaftVersion());
228
229         boolean updated = false;
230         if(appendEntriesReply.getLogLastIndex() > context.getReplicatedLog().lastIndex()) {
231             // The follower's log is actually ahead of the leader's log. Normally this doesn't happen
232             // in raft as a node cannot become leader if it's log is behind another's. However, the
233             // non-voting semantics deviate a bit from raft. Only voting members participate in
234             // elections and can become leader so it's possible for a non-voting follower to be ahead
235             // of the leader. This can happen if persistence is disabled and all voting members are
236             // restarted. In this case, the voting leader will start out with an empty log however
237             // the non-voting followers still retain the previous data in memory. On the first
238             // AppendEntries, the non-voting follower returns a successful reply b/c the prevLogIndex
239             // sent by the leader is -1 and thus the integrity checks pass. However the follower's returned
240             // lastLogIndex may be higher in which case we want to reset the follower by installing a
241             // snapshot. It's also possible that the follower's last log index is behind the leader's.
242             // However in this case the log terms won't match and the logs will conflict - this is handled
243             // elsewhere.
244             LOG.debug("{}: handleAppendEntriesReply: follower {} lastIndex {} is ahead of our lastIndex {} - forcing install snaphot",
245                     logName(), followerLogInformation.getId(), appendEntriesReply.getLogLastIndex(),
246                     context.getReplicatedLog().lastIndex());
247
248             followerLogInformation.setMatchIndex(-1);
249             followerLogInformation.setNextIndex(-1);
250
251             initiateCaptureSnapshot(followerId);
252             updated = true;
253         } else if (appendEntriesReply.isSuccess()) {
254             updated = updateFollowerLogInformation(followerLogInformation, appendEntriesReply);
255         } else {
256             LOG.debug("{}: handleAppendEntriesReply: received unsuccessful reply: {}", logName(), appendEntriesReply);
257
258             long followerLastLogIndex = appendEntriesReply.getLogLastIndex();
259             long followersLastLogTerm = getLogEntryTerm(followerLastLogIndex);
260             if(appendEntriesReply.isForceInstallSnapshot()) {
261                 // Reset the followers match and next index. This is to signal that this follower has nothing
262                 // in common with this Leader and so would require a snapshot to be installed
263                 followerLogInformation.setMatchIndex(-1);
264                 followerLogInformation.setNextIndex(-1);
265
266                 // Force initiate a snapshot capture
267                 initiateCaptureSnapshot(followerId);
268             } else if(followerLastLogIndex < 0 || (followersLastLogTerm >= 0 &&
269                     followersLastLogTerm == appendEntriesReply.getLogLastTerm())) {
270                 // The follower's log is empty or the last entry is present in the leader's journal
271                 // and the terms match so the follower is just behind the leader's journal from
272                 // the last snapshot, if any. We'll catch up the follower quickly by starting at the
273                 // follower's last log index.
274
275                 updated = updateFollowerLogInformation(followerLogInformation, appendEntriesReply);
276             } else {
277                 // The follower's log conflicts with leader's log so decrement follower's next index by 1
278                 // in an attempt to find where the logs match.
279
280                 LOG.debug("{}: follower's last log term {} conflicts with the leader's {} - dec next index",
281                         logName(), appendEntriesReply.getLogLastTerm(), followersLastLogTerm);
282
283                 followerLogInformation.decrNextIndex();
284             }
285         }
286
287         // Now figure out if this reply warrants a change in the commitIndex
288         // If there exists an N such that N > commitIndex, a majority
289         // of matchIndex[i] ≥ N, and log[N].term == currentTerm:
290         // set commitIndex = N (§5.3, §5.4).
291         if(LOG.isTraceEnabled()) {
292             LOG.trace("{}: handleAppendEntriesReply from {}: commitIndex: {}, lastAppliedIndex: {}, currentTerm: {}",
293                     logName(), followerId, context.getCommitIndex(), context.getLastApplied(), currentTerm());
294         }
295
296         for (long N = context.getCommitIndex() + 1; ; N++) {
297             int replicatedCount = 1;
298
299             LOG.trace("{}: checking Nth index {}", logName(), N);
300             for (FollowerLogInformation info : followerToLog.values()) {
301                 final PeerInfo peerInfo = context.getPeerInfo(info.getId());
302                 if(info.getMatchIndex() >= N && (peerInfo != null && peerInfo.isVoting())) {
303                     replicatedCount++;
304                 } else if(LOG.isTraceEnabled()) {
305                     LOG.trace("{}: Not counting follower {} - matchIndex: {}, {}", logName(), info.getId(),
306                             info.getMatchIndex(), peerInfo);
307                 }
308             }
309
310             if(LOG.isTraceEnabled()) {
311                 LOG.trace("{}: replicatedCount {}, minReplicationCount: {}", logName(), replicatedCount, minReplicationCount);
312             }
313
314             if (replicatedCount >= minReplicationCount) {
315                 ReplicatedLogEntry replicatedLogEntry = context.getReplicatedLog().get(N);
316                 if (replicatedLogEntry == null) {
317                     LOG.debug("{}: ReplicatedLogEntry not found for index {} - snapshotIndex: {}, journal size: {}",
318                             logName(), N, context.getReplicatedLog().getSnapshotIndex(), context.getReplicatedLog().size());
319                     break;
320                 }
321
322                 // Don't update the commit index if the log entry is from a previous term, as per §5.4.1:
323                 // "Raft never commits log entries from previous terms by counting replicas".
324                 // However we keep looping so we can make progress when new entries in the current term
325                 // reach consensus, as per §5.4.1: "once an entry from the current term is committed by
326                 // counting replicas, then all prior entries are committed indirectly".
327                 if (replicatedLogEntry.getTerm() == currentTerm()) {
328                     LOG.trace("{}: Setting commit index to {}", logName(), N);
329                     context.setCommitIndex(N);
330                 } else {
331                     LOG.debug("{}: Not updating commit index to {} - retrieved log entry with index {}, term {} does not match the current term {}",
332                             logName(), N, replicatedLogEntry.getIndex(), replicatedLogEntry.getTerm(), currentTerm());
333                 }
334             } else {
335                 LOG.trace("{}: minReplicationCount not reached, actual {} - breaking", logName(), replicatedCount);
336                 break;
337             }
338         }
339
340         // Apply the change to the state machine
341         if (context.getCommitIndex() > context.getLastApplied()) {
342             if(LOG.isDebugEnabled()) {
343                 LOG.debug("{}: handleAppendEntriesReply from {}: applying to log - commitIndex: {}, lastAppliedIndex: {}",
344                         logName(), followerId, context.getCommitIndex(), context.getLastApplied());
345             }
346
347             applyLogToStateMachine(context.getCommitIndex());
348         }
349
350         if (!context.getSnapshotManager().isCapturing()) {
351             purgeInMemoryLog();
352         }
353
354         //Send the next log entry immediately, if possible, no need to wait for heartbeat to trigger that event
355         sendUpdatesToFollower(followerId, followerLogInformation, false, !updated);
356
357         return this;
358     }
359
360     private boolean updateFollowerLogInformation(FollowerLogInformation followerLogInformation,
361             AppendEntriesReply appendEntriesReply) {
362         boolean updated = followerLogInformation.setMatchIndex(appendEntriesReply.getLogLastIndex());
363         updated = followerLogInformation.setNextIndex(appendEntriesReply.getLogLastIndex() + 1) || updated;
364
365         if(updated && LOG.isDebugEnabled()) {
366             LOG.debug("{}: handleAppendEntriesReply - FollowerLogInformation for {} updated: matchIndex: {}, nextIndex: {}",
367                     logName(), followerLogInformation.getId(), followerLogInformation.getMatchIndex(),
368                     followerLogInformation.getNextIndex());
369         }
370         return updated;
371     }
372
373     private void purgeInMemoryLog() {
374         //find the lowest index across followers which has been replicated to all.
375         // lastApplied if there are no followers, so that we keep clearing the log for single-node
376         // we would delete the in-mem log from that index on, in-order to minimize mem usage
377         // we would also share this info thru AE with the followers so that they can delete their log entries as well.
378         long minReplicatedToAllIndex = followerToLog.isEmpty() ? context.getLastApplied() : Long.MAX_VALUE;
379         for (FollowerLogInformation info : followerToLog.values()) {
380             minReplicatedToAllIndex = Math.min(minReplicatedToAllIndex, info.getMatchIndex());
381         }
382
383         super.performSnapshotWithoutCapture(minReplicatedToAllIndex);
384     }
385
386     @Override
387     protected ClientRequestTracker removeClientRequestTracker(long logIndex) {
388         final Iterator<ClientRequestTracker> it = trackers.iterator();
389         while (it.hasNext()) {
390             final ClientRequestTracker t = it.next();
391             if (t.getIndex() == logIndex) {
392                 it.remove();
393                 return t;
394             }
395         }
396
397         return null;
398     }
399
400     @Override
401     protected RaftActorBehavior handleRequestVoteReply(ActorRef sender,
402         RequestVoteReply requestVoteReply) {
403         return this;
404     }
405
406     protected void beforeSendHeartbeat(){}
407
408     @Override
409     public RaftActorBehavior handleMessage(ActorRef sender, Object message) {
410         Preconditions.checkNotNull(sender, "sender should not be null");
411
412         if (message instanceof RaftRPC) {
413             RaftRPC rpc = (RaftRPC) message;
414             // If RPC request or response contains term T > currentTerm:
415             // set currentTerm = T, convert to follower (§5.1)
416             // This applies to all RPC messages and responses
417             if (rpc.getTerm() > context.getTermInformation().getCurrentTerm()) {
418                 LOG.debug("{}: Term {} in \"{}\" message is greater than leader's term {} - switching to Follower",
419                         logName(), rpc.getTerm(), rpc, context.getTermInformation().getCurrentTerm());
420
421                 context.getTermInformation().updateAndPersist(rpc.getTerm(), null);
422
423                 return internalSwitchBehavior(RaftState.Follower);
424             }
425         }
426
427         if (message instanceof SendHeartBeat) {
428             beforeSendHeartbeat();
429             sendHeartBeat();
430             scheduleHeartBeat(context.getConfigParams().getHeartBeatInterval());
431         } else if(message instanceof SendInstallSnapshot) {
432             // received from RaftActor
433             setSnapshot(((SendInstallSnapshot) message).getSnapshot());
434             sendInstallSnapshot();
435         } else if (message instanceof Replicate) {
436             replicate((Replicate) message);
437         } else if (message instanceof InstallSnapshotReply) {
438             handleInstallSnapshotReply((InstallSnapshotReply) message);
439         } else {
440             return super.handleMessage(sender, message);
441         }
442
443         return this;
444     }
445
446     private void handleInstallSnapshotReply(InstallSnapshotReply reply) {
447         LOG.debug("{}: handleInstallSnapshotReply: {}", logName(), reply);
448
449         String followerId = reply.getFollowerId();
450         FollowerToSnapshot followerToSnapshot = mapFollowerToSnapshot.get(followerId);
451
452         if (followerToSnapshot == null) {
453             LOG.error("{}: FollowerToSnapshot not found for follower {} in InstallSnapshotReply",
454                     logName(), followerId);
455             return;
456         }
457
458         FollowerLogInformation followerLogInformation = followerToLog.get(followerId);
459         if(followerLogInformation == null) {
460             // This can happen during AddServer if it times out.
461             LOG.error("{}: FollowerLogInformation not found for follower {} in InstallSnapshotReply",
462                     logName(), followerId);
463             mapFollowerToSnapshot.remove(followerId);
464             return;
465         }
466
467         followerLogInformation.markFollowerActive();
468
469         if (followerToSnapshot.getChunkIndex() == reply.getChunkIndex()) {
470             boolean wasLastChunk = false;
471             if (reply.isSuccess()) {
472                 if(followerToSnapshot.isLastChunk(reply.getChunkIndex())) {
473                     //this was the last chunk reply
474                     if(LOG.isDebugEnabled()) {
475                         LOG.debug("{}: InstallSnapshotReply received, " +
476                                 "last chunk received, Chunk: {}. Follower: {} Setting nextIndex: {}",
477                                 logName(), reply.getChunkIndex(), followerId,
478                             context.getReplicatedLog().getSnapshotIndex() + 1
479                         );
480                     }
481
482                     long followerMatchIndex = snapshot.get().getLastIncludedIndex();
483                     followerLogInformation.setMatchIndex(followerMatchIndex);
484                     followerLogInformation.setNextIndex(followerMatchIndex + 1);
485                     mapFollowerToSnapshot.remove(followerId);
486
487                     LOG.debug("{}: follower: {}, matchIndex set to {}, nextIndex set to {}",
488                         logName(), followerId, followerLogInformation.getMatchIndex(),
489                         followerLogInformation.getNextIndex());
490
491                     if (mapFollowerToSnapshot.isEmpty()) {
492                         // once there are no pending followers receiving snapshots
493                         // we can remove snapshot from the memory
494                         setSnapshot(null);
495                     }
496                     wasLastChunk = true;
497                     if(context.getPeerInfo(followerId).getVotingState() == VotingState.VOTING_NOT_INITIALIZED){
498                         UnInitializedFollowerSnapshotReply unInitFollowerSnapshotSuccess =
499                                              new UnInitializedFollowerSnapshotReply(followerId);
500                         context.getActor().tell(unInitFollowerSnapshotSuccess, context.getActor());
501                         LOG.debug("Sent message UnInitializedFollowerSnapshotReply to self");
502                     }
503                 } else {
504                     followerToSnapshot.markSendStatus(true);
505                 }
506             } else {
507                 LOG.info("{}: InstallSnapshotReply received sending snapshot chunk failed, Will retry, Chunk: {}",
508                         logName(), reply.getChunkIndex());
509
510                 followerToSnapshot.markSendStatus(false);
511             }
512
513             if (wasLastChunk && !context.getSnapshotManager().isCapturing()) {
514                 // Since the follower is now caught up try to purge the log.
515                 purgeInMemoryLog();
516             } else if (!wasLastChunk && followerToSnapshot.canSendNextChunk()) {
517                 ActorSelection followerActor = context.getPeerActorSelection(followerId);
518                 if(followerActor != null) {
519                     sendSnapshotChunk(followerActor, followerId);
520                 }
521             }
522
523         } else {
524             LOG.error("{}: Chunk index {} in InstallSnapshotReply from follower {} does not match expected index {}",
525                     logName(), reply.getChunkIndex(), followerId,
526                     followerToSnapshot.getChunkIndex());
527
528             if(reply.getChunkIndex() == INVALID_CHUNK_INDEX){
529                 // Since the Follower did not find this index to be valid we should reset the follower snapshot
530                 // so that Installing the snapshot can resume from the beginning
531                 followerToSnapshot.reset();
532             }
533         }
534     }
535
536     private void replicate(Replicate replicate) {
537         long logIndex = replicate.getReplicatedLogEntry().getIndex();
538
539         LOG.debug("{}: Replicate message: identifier: {}, logIndex: {}, payload: {}", logName(),
540                 replicate.getIdentifier(), logIndex, replicate.getReplicatedLogEntry().getData().getClass());
541
542         // Create a tracker entry we will use this later to notify the
543         // client actor
544         if(replicate.getClientActor() != null) {
545             trackers.add(new ClientRequestTrackerImpl(replicate.getClientActor(), replicate.getIdentifier(),
546                     logIndex));
547         }
548
549         boolean applyModificationToState = !context.anyVotingPeers()
550                 || context.getRaftPolicy().applyModificationToStateBeforeConsensus();
551
552         if(applyModificationToState){
553             context.setCommitIndex(logIndex);
554             applyLogToStateMachine(logIndex);
555         }
556
557         if (!followerToLog.isEmpty()) {
558             sendAppendEntries(0, false);
559         }
560     }
561
562     protected void sendAppendEntries(long timeSinceLastActivityInterval, boolean isHeartbeat) {
563         // Send an AppendEntries to all followers
564         for (Entry<String, FollowerLogInformation> e : followerToLog.entrySet()) {
565             final String followerId = e.getKey();
566             final FollowerLogInformation followerLogInformation = e.getValue();
567             // This checks helps not to send a repeat message to the follower
568             if(!followerLogInformation.isFollowerActive() ||
569                     followerLogInformation.timeSinceLastActivity() >= timeSinceLastActivityInterval) {
570                 sendUpdatesToFollower(followerId, followerLogInformation, true, isHeartbeat);
571             }
572         }
573     }
574
575     /**
576      *
577      * This method checks if any update needs to be sent to the given follower. This includes append log entries,
578      * sending next snapshot chunk, and initiating a snapshot.
579      * @return true if any update is sent, false otherwise
580      */
581
582     private void sendUpdatesToFollower(String followerId, FollowerLogInformation followerLogInformation,
583                                        boolean sendHeartbeat, boolean isHeartbeat) {
584
585         ActorSelection followerActor = context.getPeerActorSelection(followerId);
586         if (followerActor != null) {
587             long followerNextIndex = followerLogInformation.getNextIndex();
588             boolean isFollowerActive = followerLogInformation.isFollowerActive();
589             boolean sendAppendEntries = false;
590             List<ReplicatedLogEntry> entries = Collections.emptyList();
591
592             if (mapFollowerToSnapshot.get(followerId) != null) {
593                 // if install snapshot is in process , then sent next chunk if possible
594                 if (isFollowerActive && mapFollowerToSnapshot.get(followerId).canSendNextChunk()) {
595                     sendSnapshotChunk(followerActor, followerId);
596                 } else if(sendHeartbeat) {
597                     // we send a heartbeat even if we have not received a reply for the last chunk
598                     sendAppendEntries = true;
599                 }
600             } else {
601                 long leaderLastIndex = context.getReplicatedLog().lastIndex();
602                 long leaderSnapShotIndex = context.getReplicatedLog().getSnapshotIndex();
603
604                 if((!isHeartbeat && LOG.isDebugEnabled()) || LOG.isTraceEnabled()) {
605                     LOG.debug("{}: Checking sendAppendEntries for follower {}: active: {}, followerNextIndex: {}, leaderLastIndex: {}, leaderSnapShotIndex: {}",
606                             logName(), followerId, isFollowerActive, followerNextIndex, leaderLastIndex, leaderSnapShotIndex);
607                 }
608
609                 if (isFollowerActive && context.getReplicatedLog().isPresent(followerNextIndex)) {
610
611                     LOG.debug("{}: sendAppendEntries: {} is present for follower {}", logName(),
612                             followerNextIndex, followerId);
613
614                     if(followerLogInformation.okToReplicate()) {
615                         // Try to send all the entries in the journal but not exceeding the max data size
616                         // for a single AppendEntries message.
617                         int maxEntries = (int) context.getReplicatedLog().size();
618                         entries = context.getReplicatedLog().getFrom(followerNextIndex, maxEntries,
619                                 context.getConfigParams().getSnapshotChunkSize());
620                         sendAppendEntries = true;
621                     }
622                 } else if (isFollowerActive && followerNextIndex >= 0 &&
623                     leaderLastIndex > followerNextIndex && !context.getSnapshotManager().isCapturing()) {
624                     // if the followers next index is not present in the leaders log, and
625                     // if the follower is just not starting and if leader's index is more than followers index
626                     // then snapshot should be sent
627
628                     if (LOG.isDebugEnabled()) {
629                         LOG.debug(String.format("%s: InitiateInstallSnapshot to follower: %s, " +
630                                     "follower-nextIndex: %d, leader-snapshot-index: %d,  " +
631                                     "leader-last-index: %d", logName(), followerId,
632                                     followerNextIndex, leaderSnapShotIndex, leaderLastIndex));
633                     }
634
635                     // Send heartbeat to follower whenever install snapshot is initiated.
636                     sendAppendEntries = true;
637                     if (canInstallSnapshot(followerNextIndex)) {
638                         initiateCaptureSnapshot(followerId);
639                     }
640
641                 } else if(sendHeartbeat) {
642                     // we send an AppendEntries, even if the follower is inactive
643                     // in-order to update the followers timestamp, in case it becomes active again
644                     sendAppendEntries = true;
645                 }
646
647             }
648
649             if(sendAppendEntries) {
650                 sendAppendEntriesToFollower(followerActor, followerNextIndex,
651                         entries, followerId);
652             }
653         }
654     }
655
656     private void sendAppendEntriesToFollower(ActorSelection followerActor, long followerNextIndex,
657         List<ReplicatedLogEntry> entries, String followerId) {
658         AppendEntries appendEntries = new AppendEntries(currentTerm(), context.getId(),
659             getLogEntryIndex(followerNextIndex - 1),
660             getLogEntryTerm(followerNextIndex - 1), entries,
661             context.getCommitIndex(), super.getReplicatedToAllIndex(), context.getPayloadVersion());
662
663         if(!entries.isEmpty() || LOG.isTraceEnabled()) {
664             LOG.debug("{}: Sending AppendEntries to follower {}: {}", logName(), followerId,
665                     appendEntries);
666         }
667
668         followerActor.tell(appendEntries, actor());
669     }
670
671     /**
672      * Install Snapshot works as follows
673      * 1. Leader initiates the capture snapshot by sending a CaptureSnapshot message to actor
674      * 2. RaftActor on receipt of the CaptureSnapshotReply (from Shard), stores the received snapshot in the replicated log
675      * and makes a call to Leader's handleMessage , with SendInstallSnapshot message.
676      * 3. Leader , picks the snapshot from im-mem ReplicatedLog and sends it in chunks to the Follower
677      * 4. On complete, Follower sends back a InstallSnapshotReply.
678      * 5. On receipt of the InstallSnapshotReply for the last chunk, Leader marks the install complete for that follower
679      * and replenishes the memory by deleting the snapshot in Replicated log.
680      * 6. If another follower requires a snapshot and a snapshot has been collected (via CaptureSnapshotReply)
681      * then send the existing snapshot in chunks to the follower.
682      * @param followerId
683      */
684     public boolean initiateCaptureSnapshot(String followerId) {
685         if (snapshot.isPresent()) {
686             // if a snapshot is present in the memory, most likely another install is in progress
687             // no need to capture snapshot.
688             // This could happen if another follower needs an install when one is going on.
689             final ActorSelection followerActor = context.getPeerActorSelection(followerId);
690             sendSnapshotChunk(followerActor, followerId);
691             return true;
692         } else {
693             return context.getSnapshotManager().captureToInstall(context.getReplicatedLog().last(),
694                     this.getReplicatedToAllIndex(), followerId);
695         }
696     }
697
698     private boolean canInstallSnapshot(long nextIndex){
699         // If the follower's nextIndex is -1 then we might as well send it a snapshot
700         // Otherwise send it a snapshot only if the nextIndex is not present in the log but is present
701         // in the snapshot
702         return (nextIndex == -1 ||
703                 (!context.getReplicatedLog().isPresent(nextIndex)
704                         && context.getReplicatedLog().isInSnapshot(nextIndex)));
705
706     }
707
708
709     private void sendInstallSnapshot() {
710         LOG.debug("{}: sendInstallSnapshot", logName());
711         for (Entry<String, FollowerLogInformation> e : followerToLog.entrySet()) {
712             String followerId = e.getKey();
713             ActorSelection followerActor = context.getPeerActorSelection(followerId);
714             FollowerLogInformation followerLogInfo = e.getValue();
715
716             if (followerActor != null) {
717                 long nextIndex = followerLogInfo.getNextIndex();
718                 if (context.getPeerInfo(followerId).getVotingState() == VotingState.VOTING_NOT_INITIALIZED ||
719                         canInstallSnapshot(nextIndex)) {
720                     sendSnapshotChunk(followerActor, followerId);
721                 }
722             }
723         }
724     }
725
726     /**
727      *  Sends a snapshot chunk to a given follower
728      *  InstallSnapshot should qualify as a heartbeat too.
729      */
730     private void sendSnapshotChunk(ActorSelection followerActor, String followerId) {
731         try {
732             if (snapshot.isPresent()) {
733                 byte[] nextSnapshotChunk = getNextSnapshotChunk(followerId, snapshot.get().getSnapshotBytes());
734
735                 // Note: the previous call to getNextSnapshotChunk has the side-effect of adding
736                 // followerId to the followerToSnapshot map.
737                 FollowerToSnapshot followerToSnapshot = mapFollowerToSnapshot.get(followerId);
738
739                 int nextChunkIndex = followerToSnapshot.incrementChunkIndex();
740                 Optional<ServerConfigurationPayload> serverConfig = Optional.absent();
741                 if(followerToSnapshot.isLastChunk(nextChunkIndex)) {
742                     serverConfig = Optional.fromNullable(context.getPeerServerInfo(true));
743                 }
744
745                 followerActor.tell(
746                     new InstallSnapshot(currentTerm(), context.getId(),
747                         snapshot.get().getLastIncludedIndex(),
748                         snapshot.get().getLastIncludedTerm(),
749                         nextSnapshotChunk,
750                         nextChunkIndex,
751                         followerToSnapshot.getTotalChunks(),
752                         Optional.of(followerToSnapshot.getLastChunkHashCode()),
753                         serverConfig
754                     ).toSerializable(followerToLog.get(followerId).getRaftVersion()),
755                     actor()
756                 );
757
758                 if(LOG.isDebugEnabled()) {
759                     LOG.debug("{}: InstallSnapshot sent to follower {}, Chunk: {}/{}",
760                             logName(), followerActor.path(), followerToSnapshot.getChunkIndex(),
761                             followerToSnapshot.getTotalChunks());
762                 }
763             }
764         } catch (IOException e) {
765             LOG.error("{}: InstallSnapshot failed for Leader.", logName(), e);
766         }
767     }
768
769     /**
770      * Acccepts snaphot as ByteString, enters into map for future chunks
771      * creates and return a ByteString chunk
772      */
773     private byte[] getNextSnapshotChunk(String followerId, ByteString snapshotBytes) throws IOException {
774         FollowerToSnapshot followerToSnapshot = mapFollowerToSnapshot.get(followerId);
775         if (followerToSnapshot == null) {
776             followerToSnapshot = new FollowerToSnapshot(snapshotBytes);
777             mapFollowerToSnapshot.put(followerId, followerToSnapshot);
778         }
779         byte[] nextChunk = followerToSnapshot.getNextChunk();
780
781         LOG.debug("{}: next snapshot chunk size for follower {}: {}", logName(), followerId, nextChunk.length);
782
783         return nextChunk;
784     }
785
786     private void sendHeartBeat() {
787         if (!followerToLog.isEmpty()) {
788             LOG.trace("{}: Sending heartbeat", logName());
789             sendAppendEntries(context.getConfigParams().getHeartBeatInterval().toMillis(), true);
790         }
791     }
792
793     private void stopHeartBeat() {
794         if (heartbeatSchedule != null && !heartbeatSchedule.isCancelled()) {
795             heartbeatSchedule.cancel();
796         }
797     }
798
799     private void scheduleHeartBeat(FiniteDuration interval) {
800         if (followerToLog.isEmpty()) {
801             // Optimization - do not bother scheduling a heartbeat as there are
802             // no followers
803             return;
804         }
805
806         stopHeartBeat();
807
808         // Schedule a heartbeat. When the scheduler triggers a SendHeartbeat
809         // message is sent to itself.
810         // Scheduling the heartbeat only once here because heartbeats do not
811         // need to be sent if there are other messages being sent to the remote
812         // actor.
813         heartbeatSchedule = context.getActorSystem().scheduler().scheduleOnce(
814             interval, context.getActor(), SendHeartBeat.INSTANCE,
815             context.getActorSystem().dispatcher(), context.getActor());
816     }
817
818     @Override
819     public void close() {
820         stopHeartBeat();
821     }
822
823     @Override
824     public final String getLeaderId() {
825         return context.getId();
826     }
827
828     @Override
829     public final short getLeaderPayloadVersion() {
830         return context.getPayloadVersion();
831     }
832
833     protected boolean isLeaderIsolated() {
834         int minPresent = getMinIsolatedLeaderPeerCount();
835         for (FollowerLogInformation followerLogInformation : followerToLog.values()) {
836             final PeerInfo peerInfo = context.getPeerInfo(followerLogInformation.getId());
837             if(peerInfo != null && peerInfo.isVoting() && followerLogInformation.isFollowerActive()) {
838                 --minPresent;
839                 if (minPresent == 0) {
840                     return false;
841                 }
842             }
843         }
844         return (minPresent != 0);
845     }
846
847     /**
848      * Encapsulates the snapshot bytestring and handles the logic of sending
849      * snapshot chunks
850      */
851     protected class FollowerToSnapshot {
852         private final ByteString snapshotBytes;
853         private int offset = 0;
854         // the next snapshot chunk is sent only if the replyReceivedForOffset matches offset
855         private int replyReceivedForOffset;
856         // if replyStatus is false, the previous chunk is attempted
857         private boolean replyStatus = false;
858         private int chunkIndex;
859         private final int totalChunks;
860         private int lastChunkHashCode = AbstractLeader.INITIAL_LAST_CHUNK_HASH_CODE;
861         private int nextChunkHashCode = AbstractLeader.INITIAL_LAST_CHUNK_HASH_CODE;
862
863         public FollowerToSnapshot(ByteString snapshotBytes) {
864             this.snapshotBytes = snapshotBytes;
865             int size = snapshotBytes.size();
866             totalChunks = ( size / context.getConfigParams().getSnapshotChunkSize()) +
867                 ((size % context.getConfigParams().getSnapshotChunkSize()) > 0 ? 1 : 0);
868             if(LOG.isDebugEnabled()) {
869                 LOG.debug("{}: Snapshot {} bytes, total chunks to send:{}",
870                         logName(), size, totalChunks);
871             }
872             replyReceivedForOffset = -1;
873             chunkIndex = AbstractLeader.FIRST_CHUNK_INDEX;
874         }
875
876         public ByteString getSnapshotBytes() {
877             return snapshotBytes;
878         }
879
880         public int incrementOffset() {
881             if(replyStatus) {
882                 // if prev chunk failed, we would want to sent the same chunk again
883                 offset = offset + context.getConfigParams().getSnapshotChunkSize();
884             }
885             return offset;
886         }
887
888         public int incrementChunkIndex() {
889             if (replyStatus) {
890                 // if prev chunk failed, we would want to sent the same chunk again
891                 chunkIndex =  chunkIndex + 1;
892             }
893             return chunkIndex;
894         }
895
896         public int getChunkIndex() {
897             return chunkIndex;
898         }
899
900         public int getTotalChunks() {
901             return totalChunks;
902         }
903
904         public boolean canSendNextChunk() {
905             // we only send a false if a chunk is sent but we have not received a reply yet
906             return replyReceivedForOffset == offset;
907         }
908
909         public boolean isLastChunk(int chunkIndex) {
910             return totalChunks == chunkIndex;
911         }
912
913         public void markSendStatus(boolean success) {
914             if (success) {
915                 // if the chunk sent was successful
916                 replyReceivedForOffset = offset;
917                 replyStatus = true;
918                 lastChunkHashCode = nextChunkHashCode;
919             } else {
920                 // if the chunk sent was failure
921                 replyReceivedForOffset = offset;
922                 replyStatus = false;
923             }
924         }
925
926         public byte[] getNextChunk() {
927             int snapshotLength = getSnapshotBytes().size();
928             int start = incrementOffset();
929             int size = context.getConfigParams().getSnapshotChunkSize();
930             if (context.getConfigParams().getSnapshotChunkSize() > snapshotLength) {
931                 size = snapshotLength;
932             } else if ((start + context.getConfigParams().getSnapshotChunkSize()) > snapshotLength) {
933                 size = snapshotLength - start;
934             }
935
936             byte[] nextChunk = new byte[size];
937             getSnapshotBytes().copyTo(nextChunk, start, 0, size);
938             nextChunkHashCode = Arrays.hashCode(nextChunk);
939
940             LOG.debug("{}: Next chunk: total length={}, offset={}, size={}, hashCode={}", logName(),
941                     snapshotLength, start, size, nextChunkHashCode);
942             return nextChunk;
943         }
944
945         /**
946          * reset should be called when the Follower needs to be sent the snapshot from the beginning
947          */
948         public void reset(){
949             offset = 0;
950             replyStatus = false;
951             replyReceivedForOffset = offset;
952             chunkIndex = AbstractLeader.FIRST_CHUNK_INDEX;
953             lastChunkHashCode = AbstractLeader.INITIAL_LAST_CHUNK_HASH_CODE;
954         }
955
956         public int getLastChunkHashCode() {
957             return lastChunkHashCode;
958         }
959     }
960
961     // called from example-actor for printing the follower-states
962     public String printFollowerStates() {
963         final StringBuilder sb = new StringBuilder();
964
965         sb.append('[');
966         for (FollowerLogInformation followerLogInformation : followerToLog.values()) {
967             sb.append('{');
968             sb.append(followerLogInformation.getId());
969             sb.append(" state:");
970             sb.append(followerLogInformation.isFollowerActive());
971             sb.append("},");
972         }
973         sb.append(']');
974
975         return sb.toString();
976     }
977
978     @VisibleForTesting
979     public FollowerLogInformation getFollower(String followerId) {
980         return followerToLog.get(followerId);
981     }
982
983     @VisibleForTesting
984     protected void setFollowerSnapshot(String followerId, FollowerToSnapshot snapshot) {
985         mapFollowerToSnapshot.put(followerId, snapshot);
986     }
987
988     @VisibleForTesting
989     public int followerSnapshotSize() {
990         return mapFollowerToSnapshot.size();
991     }
992
993     @VisibleForTesting
994     public int followerLogSize() {
995         return followerToLog.size();
996     }
997
998     private static class SnapshotHolder {
999         private final long lastIncludedTerm;
1000         private final long lastIncludedIndex;
1001         private final ByteString snapshotBytes;
1002
1003         SnapshotHolder(Snapshot snapshot) {
1004             this.lastIncludedTerm = snapshot.getLastAppliedTerm();
1005             this.lastIncludedIndex = snapshot.getLastAppliedIndex();
1006             this.snapshotBytes = ByteString.copyFrom(snapshot.getState());
1007         }
1008
1009         long getLastIncludedTerm() {
1010             return lastIncludedTerm;
1011         }
1012
1013         long getLastIncludedIndex() {
1014             return lastIncludedIndex;
1015         }
1016
1017         ByteString getSnapshotBytes() {
1018             return snapshotBytes;
1019         }
1020     }
1021 }

©2013 OpenDaylight, A Linux Foundation Collaborative Project. All Rights Reserved.
OpenDaylight is a registered trademark of The OpenDaylight Project, Inc.
Linux Foundation and OpenDaylight are registered trademarks of the Linux Foundation.
Linux is a registered trademark of Linus Torvalds.