2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
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
9 package org.opendaylight.controller.cluster.raft.behaviors;
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.common.collect.ImmutableMap;
18 import com.google.common.collect.ImmutableMap.Builder;
19 import com.google.protobuf.ByteString;
20 import java.io.IOException;
21 import java.util.Collection;
22 import java.util.Collections;
23 import java.util.HashMap;
24 import java.util.Iterator;
25 import java.util.LinkedList;
26 import java.util.List;
28 import java.util.Map.Entry;
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.RaftActorContext;
35 import org.opendaylight.controller.cluster.raft.RaftState;
36 import org.opendaylight.controller.cluster.raft.ReplicatedLogEntry;
37 import org.opendaylight.controller.cluster.raft.Snapshot;
38 import org.opendaylight.controller.cluster.raft.base.messages.Replicate;
39 import org.opendaylight.controller.cluster.raft.base.messages.SendHeartBeat;
40 import org.opendaylight.controller.cluster.raft.base.messages.SendInstallSnapshot;
41 import org.opendaylight.controller.cluster.raft.messages.AppendEntries;
42 import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
43 import org.opendaylight.controller.cluster.raft.messages.InstallSnapshot;
44 import org.opendaylight.controller.cluster.raft.messages.InstallSnapshotReply;
45 import org.opendaylight.controller.cluster.raft.messages.RaftRPC;
46 import org.opendaylight.controller.cluster.raft.messages.RequestVoteReply;
47 import scala.concurrent.duration.FiniteDuration;
50 * The behavior of a RaftActor when it is in the Leader state
54 * <li> Upon election: send initial empty AppendEntries RPCs
55 * (heartbeat) to each server; repeat during idle periods to
56 * prevent election timeouts (§5.2)
57 * <li> If command received from client: append entry to local log,
58 * respond after entry applied to state machine (§5.3)
59 * <li> If last log index ≥ nextIndex for a follower: send
60 * AppendEntries RPC with log entries starting at nextIndex
62 * <li> If successful: update nextIndex and matchIndex for
64 * <li> If AppendEntries fails because of log inconsistency:
65 * decrement nextIndex and retry (§5.3)
67 * <li> If there exists an N such that N > commitIndex, a majority
68 * of matchIndex[i] ≥ N, and log[N].term == currentTerm:
69 * set commitIndex = N (§5.3, §5.4).
71 public abstract class AbstractLeader extends AbstractRaftActorBehavior {
73 // The index of the first chunk that is sent when installing a snapshot
74 public static final int FIRST_CHUNK_INDEX = 1;
76 // The index that the follower should respond with if it needs the install snapshot to be reset
77 public static final int INVALID_CHUNK_INDEX = -1;
79 // This would be passed as the hash code of the last chunk when sending the first chunk
80 public static final int INITIAL_LAST_CHUNK_HASH_CODE = -1;
82 private final Map<String, FollowerLogInformation> followerToLog;
83 private final Map<String, FollowerToSnapshot> mapFollowerToSnapshot = new HashMap<>();
85 private Cancellable heartbeatSchedule = null;
87 private final Collection<ClientRequestTracker> trackerList = new LinkedList<>();
89 protected final int minReplicationCount;
91 protected final int minIsolatedLeaderPeerCount;
93 private Optional<SnapshotHolder> snapshot;
95 public AbstractLeader(RaftActorContext context) {
96 super(context, RaftState.Leader);
98 setLeaderPayloadVersion(context.getPayloadVersion());
100 final Builder<String, FollowerLogInformation> ftlBuilder = ImmutableMap.builder();
101 for (String followerId : context.getPeerAddresses().keySet()) {
102 FollowerLogInformation followerLogInformation =
103 new FollowerLogInformationImpl(followerId, -1, context);
105 ftlBuilder.put(followerId, followerLogInformation);
107 followerToLog = ftlBuilder.build();
109 leaderId = context.getId();
111 LOG.debug("{}: Election: Leader has following peers: {}", logName(), getFollowerIds());
113 minReplicationCount = getMajorityVoteCount(getFollowerIds().size());
115 // the isolated Leader peer count will be 1 less than the majority vote count.
116 // this is because the vote count has the self vote counted in it
118 // 0 peers = 1 votesRequired , minIsolatedLeaderPeerCount = 0
119 // 2 peers = 2 votesRequired , minIsolatedLeaderPeerCount = 1
120 // 4 peers = 3 votesRequired, minIsolatedLeaderPeerCount = 2
121 minIsolatedLeaderPeerCount = minReplicationCount > 0 ? (minReplicationCount - 1) : 0;
123 snapshot = Optional.absent();
125 // Immediately schedule a heartbeat
126 // Upon election: send initial empty AppendEntries RPCs
127 // (heartbeat) to each server; repeat during idle periods to
128 // prevent election timeouts (§5.2)
129 sendAppendEntries(0, false);
131 // It is important to schedule this heartbeat here
132 scheduleHeartBeat(context.getConfigParams().getHeartBeatInterval());
136 * Return an immutable collection of follower identifiers.
138 * @return Collection of follower IDs
140 public final Collection<String> getFollowerIds() {
141 return followerToLog.keySet();
145 void setSnapshot(@Nullable Snapshot snapshot) {
146 if(snapshot != null) {
147 this.snapshot = Optional.of(new SnapshotHolder(snapshot));
149 this.snapshot = Optional.absent();
154 protected RaftActorBehavior handleAppendEntries(ActorRef sender,
155 AppendEntries appendEntries) {
157 LOG.debug("{}: handleAppendEntries: {}", logName(), appendEntries);
163 protected RaftActorBehavior handleAppendEntriesReply(ActorRef sender,
164 AppendEntriesReply appendEntriesReply) {
166 if(LOG.isTraceEnabled()) {
167 LOG.trace("{}: handleAppendEntriesReply: {}", logName(), appendEntriesReply);
170 // Update the FollowerLogInformation
171 String followerId = appendEntriesReply.getFollowerId();
172 FollowerLogInformation followerLogInformation =
173 followerToLog.get(followerId);
175 if(followerLogInformation == null){
176 LOG.error("{}: handleAppendEntriesReply - unknown follower {}", logName(), followerId);
180 if(followerLogInformation.timeSinceLastActivity() >
181 context.getConfigParams().getElectionTimeOutInterval().toMillis()) {
182 LOG.warn("{} : handleAppendEntriesReply delayed beyond election timeout, " +
183 "appendEntriesReply : {}, timeSinceLastActivity : {}, lastApplied : {}, commitIndex : {}",
184 logName(), appendEntriesReply, followerLogInformation.timeSinceLastActivity(),
185 context.getLastApplied(), context.getCommitIndex());
188 followerLogInformation.markFollowerActive();
189 followerLogInformation.setPayloadVersion(appendEntriesReply.getPayloadVersion());
191 boolean updated = false;
192 if (appendEntriesReply.isSuccess()) {
193 updated = updateFollowerLogInformation(followerLogInformation, appendEntriesReply);
195 LOG.debug("{}: handleAppendEntriesReply: received unsuccessful reply: {}", logName(), appendEntriesReply);
197 long followerLastLogIndex = appendEntriesReply.getLogLastIndex();
198 ReplicatedLogEntry followersLastLogEntry = context.getReplicatedLog().get(followerLastLogIndex);
199 if(followerLastLogIndex < 0 || (followersLastLogEntry != null &&
200 followersLastLogEntry.getTerm() == appendEntriesReply.getLogLastTerm())) {
201 // The follower's log is empty or the last entry is present in the leader's journal
202 // and the terms match so the follower is just behind the leader's journal from
203 // the last snapshot, if any. We'll catch up the follower quickly by starting at the
204 // follower's last log index.
206 updated = updateFollowerLogInformation(followerLogInformation, appendEntriesReply);
208 // TODO: When we find that the follower is out of sync with the
209 // Leader we simply decrement that followers next index by 1.
210 // Would it be possible to do better than this? The RAFT spec
211 // does not explicitly deal with it but may be something for us to
214 followerLogInformation.decrNextIndex();
218 // Now figure out if this reply warrants a change in the commitIndex
219 // If there exists an N such that N > commitIndex, a majority
220 // of matchIndex[i] ≥ N, and log[N].term == currentTerm:
221 // set commitIndex = N (§5.3, §5.4).
222 for (long N = context.getCommitIndex() + 1; ; N++) {
223 int replicatedCount = 1;
225 for (FollowerLogInformation info : followerToLog.values()) {
226 if (info.getMatchIndex() >= N) {
231 if (replicatedCount >= minReplicationCount) {
232 ReplicatedLogEntry replicatedLogEntry = context.getReplicatedLog().get(N);
233 if (replicatedLogEntry != null &&
234 replicatedLogEntry.getTerm() == currentTerm()) {
235 context.setCommitIndex(N);
242 // Apply the change to the state machine
243 if (context.getCommitIndex() > context.getLastApplied()) {
244 if(LOG.isDebugEnabled()) {
245 LOG.debug("{}: handleAppendEntriesReply from {}: applying to log - commitIndex: {}, lastAppliedIndex: {}",
246 logName(), followerId, context.getCommitIndex(), context.getLastApplied());
249 applyLogToStateMachine(context.getCommitIndex());
252 if (!context.getSnapshotManager().isCapturing()) {
256 //Send the next log entry immediately, if possible, no need to wait for heartbeat to trigger that event
257 sendUpdatesToFollower(followerId, followerLogInformation, false, !updated);
261 private boolean updateFollowerLogInformation(FollowerLogInformation followerLogInformation,
262 AppendEntriesReply appendEntriesReply) {
263 boolean updated = followerLogInformation.setMatchIndex(appendEntriesReply.getLogLastIndex());
264 updated = followerLogInformation.setNextIndex(appendEntriesReply.getLogLastIndex() + 1) || updated;
266 if(updated && LOG.isDebugEnabled()) {
267 LOG.debug("{}: handleAppendEntriesReply - FollowerLogInformation for {} updated: matchIndex: {}, nextIndex: {}",
268 logName(), followerLogInformation.getId(), followerLogInformation.getMatchIndex(),
269 followerLogInformation.getNextIndex());
274 private void purgeInMemoryLog() {
275 //find the lowest index across followers which has been replicated to all.
276 // lastApplied if there are no followers, so that we keep clearing the log for single-node
277 // we would delete the in-mem log from that index on, in-order to minimize mem usage
278 // we would also share this info thru AE with the followers so that they can delete their log entries as well.
279 long minReplicatedToAllIndex = followerToLog.isEmpty() ? context.getLastApplied() : Long.MAX_VALUE;
280 for (FollowerLogInformation info : followerToLog.values()) {
281 minReplicatedToAllIndex = Math.min(minReplicatedToAllIndex, info.getMatchIndex());
284 super.performSnapshotWithoutCapture(minReplicatedToAllIndex);
288 protected ClientRequestTracker removeClientRequestTracker(long logIndex) {
289 final Iterator<ClientRequestTracker> it = trackerList.iterator();
290 while (it.hasNext()) {
291 final ClientRequestTracker t = it.next();
292 if (t.getIndex() == logIndex) {
302 protected ClientRequestTracker findClientRequestTracker(long logIndex) {
303 for (ClientRequestTracker tracker : trackerList) {
304 if (tracker.getIndex() == logIndex) {
312 protected RaftActorBehavior handleRequestVoteReply(ActorRef sender,
313 RequestVoteReply requestVoteReply) {
317 protected void beforeSendHeartbeat(){}
320 public RaftActorBehavior handleMessage(ActorRef sender, Object originalMessage) {
321 Preconditions.checkNotNull(sender, "sender should not be null");
323 Object message = fromSerializableMessage(originalMessage);
325 if (message instanceof RaftRPC) {
326 RaftRPC rpc = (RaftRPC) message;
327 // If RPC request or response contains term T > currentTerm:
328 // set currentTerm = T, convert to follower (§5.1)
329 // This applies to all RPC messages and responses
330 if (rpc.getTerm() > context.getTermInformation().getCurrentTerm()) {
331 LOG.debug("{}: Term {} in \"{}\" message is greater than leader's term {} - switching to Follower",
332 logName(), rpc.getTerm(), rpc, context.getTermInformation().getCurrentTerm());
334 context.getTermInformation().updateAndPersist(rpc.getTerm(), null);
336 return switchBehavior(new Follower(context));
340 if (message instanceof SendHeartBeat) {
341 beforeSendHeartbeat();
343 scheduleHeartBeat(context.getConfigParams().getHeartBeatInterval());
346 } else if(message instanceof SendInstallSnapshot) {
347 // received from RaftActor
348 setSnapshot(((SendInstallSnapshot) message).getSnapshot());
349 sendInstallSnapshot();
351 } else if (message instanceof Replicate) {
352 replicate((Replicate) message);
354 } else if (message instanceof InstallSnapshotReply){
355 handleInstallSnapshotReply((InstallSnapshotReply) message);
360 return super.handleMessage(sender, message);
363 private void handleInstallSnapshotReply(InstallSnapshotReply reply) {
364 LOG.debug("{}: handleInstallSnapshotReply: {}", logName(), reply);
366 String followerId = reply.getFollowerId();
367 FollowerToSnapshot followerToSnapshot = mapFollowerToSnapshot.get(followerId);
369 if (followerToSnapshot == null) {
370 LOG.error("{}: FollowerId {} in InstallSnapshotReply not known to Leader",
371 logName(), followerId);
375 FollowerLogInformation followerLogInformation = followerToLog.get(followerId);
376 followerLogInformation.markFollowerActive();
378 if (followerToSnapshot.getChunkIndex() == reply.getChunkIndex()) {
379 boolean wasLastChunk = false;
380 if (reply.isSuccess()) {
381 if(followerToSnapshot.isLastChunk(reply.getChunkIndex())) {
382 //this was the last chunk reply
383 if(LOG.isDebugEnabled()) {
384 LOG.debug("{}: InstallSnapshotReply received, " +
385 "last chunk received, Chunk: {}. Follower: {} Setting nextIndex: {}",
386 logName(), reply.getChunkIndex(), followerId,
387 context.getReplicatedLog().getSnapshotIndex() + 1
391 long followerMatchIndex = snapshot.get().getLastIncludedIndex();
392 followerLogInformation.setMatchIndex(followerMatchIndex);
393 followerLogInformation.setNextIndex(followerMatchIndex + 1);
394 mapFollowerToSnapshot.remove(followerId);
396 LOG.debug("{}: follower: {}, matchIndex set to {}, nextIndex set to {}",
397 logName(), followerId, followerLogInformation.getMatchIndex(),
398 followerLogInformation.getNextIndex());
400 if (mapFollowerToSnapshot.isEmpty()) {
401 // once there are no pending followers receiving snapshots
402 // we can remove snapshot from the memory
408 followerToSnapshot.markSendStatus(true);
411 LOG.info("{}: InstallSnapshotReply received sending snapshot chunk failed, Will retry, Chunk: {}",
412 logName(), reply.getChunkIndex());
414 followerToSnapshot.markSendStatus(false);
417 if (wasLastChunk && !context.getSnapshotManager().isCapturing()) {
418 // Since the follower is now caught up try to purge the log.
420 } else if (!wasLastChunk && followerToSnapshot.canSendNextChunk()) {
421 ActorSelection followerActor = context.getPeerActorSelection(followerId);
422 if(followerActor != null) {
423 sendSnapshotChunk(followerActor, followerId);
428 LOG.error("{}: Chunk index {} in InstallSnapshotReply from follower {} does not match expected index {}",
429 logName(), reply.getChunkIndex(), followerId,
430 followerToSnapshot.getChunkIndex());
432 if(reply.getChunkIndex() == INVALID_CHUNK_INDEX){
433 // Since the Follower did not find this index to be valid we should reset the follower snapshot
434 // so that Installing the snapshot can resume from the beginning
435 followerToSnapshot.reset();
440 private void replicate(Replicate replicate) {
441 long logIndex = replicate.getReplicatedLogEntry().getIndex();
443 LOG.debug("{}: Replicate message: identifier: {}, logIndex: {}", logName(),
444 replicate.getIdentifier(), logIndex);
446 // Create a tracker entry we will use this later to notify the
449 new ClientRequestTrackerImpl(replicate.getClientActor(),
450 replicate.getIdentifier(),
454 boolean applyModificationToState = followerToLog.isEmpty()
455 || context.getRaftPolicy().applyModificationToStateBeforeConsensus();
457 if(applyModificationToState){
458 context.setCommitIndex(logIndex);
459 applyLogToStateMachine(logIndex);
462 if (!followerToLog.isEmpty()) {
463 sendAppendEntries(0, false);
467 private void sendAppendEntries(long timeSinceLastActivityInterval, boolean isHeartbeat) {
468 // Send an AppendEntries to all followers
469 for (Entry<String, FollowerLogInformation> e : followerToLog.entrySet()) {
470 final String followerId = e.getKey();
471 final FollowerLogInformation followerLogInformation = e.getValue();
472 // This checks helps not to send a repeat message to the follower
473 if(!followerLogInformation.isFollowerActive() ||
474 followerLogInformation.timeSinceLastActivity() >= timeSinceLastActivityInterval) {
475 sendUpdatesToFollower(followerId, followerLogInformation, true, isHeartbeat);
482 * This method checks if any update needs to be sent to the given follower. This includes append log entries,
483 * sending next snapshot chunk, and initiating a snapshot.
484 * @return true if any update is sent, false otherwise
487 private void sendUpdatesToFollower(String followerId, FollowerLogInformation followerLogInformation,
488 boolean sendHeartbeat, boolean isHeartbeat) {
490 ActorSelection followerActor = context.getPeerActorSelection(followerId);
491 if (followerActor != null) {
492 long followerNextIndex = followerLogInformation.getNextIndex();
493 boolean isFollowerActive = followerLogInformation.isFollowerActive();
494 boolean sendAppendEntries = false;
495 List<ReplicatedLogEntry> entries = Collections.emptyList();
497 if (mapFollowerToSnapshot.get(followerId) != null) {
498 // if install snapshot is in process , then sent next chunk if possible
499 if (isFollowerActive && mapFollowerToSnapshot.get(followerId).canSendNextChunk()) {
500 sendSnapshotChunk(followerActor, followerId);
501 } else if(sendHeartbeat) {
502 // we send a heartbeat even if we have not received a reply for the last chunk
503 sendAppendEntries = true;
506 long leaderLastIndex = context.getReplicatedLog().lastIndex();
507 long leaderSnapShotIndex = context.getReplicatedLog().getSnapshotIndex();
509 if((!isHeartbeat && LOG.isDebugEnabled()) || LOG.isTraceEnabled()) {
510 LOG.debug("{}: Checking sendAppendEntries for follower {}: active: {}, followerNextIndex: {}, leaderLastIndex: {}, leaderSnapShotIndex: {}",
511 logName(), followerId, isFollowerActive, followerNextIndex, leaderLastIndex, leaderSnapShotIndex);
514 if (isFollowerActive && context.getReplicatedLog().isPresent(followerNextIndex)) {
516 LOG.debug("{}: sendAppendEntries: {} is present for follower {}", logName(),
517 followerNextIndex, followerId);
519 if(followerLogInformation.okToReplicate()) {
520 // Try to send all the entries in the journal but not exceeding the max data size
521 // for a single AppendEntries message.
522 int maxEntries = (int) context.getReplicatedLog().size();
523 entries = context.getReplicatedLog().getFrom(followerNextIndex, maxEntries,
524 context.getConfigParams().getSnapshotChunkSize());
525 sendAppendEntries = true;
527 } else if (isFollowerActive && followerNextIndex >= 0 &&
528 leaderLastIndex > followerNextIndex && !context.getSnapshotManager().isCapturing()) {
529 // if the followers next index is not present in the leaders log, and
530 // if the follower is just not starting and if leader's index is more than followers index
531 // then snapshot should be sent
533 if (LOG.isDebugEnabled()) {
534 LOG.debug(String.format("%s: InitiateInstallSnapshot to follower: %s," +
535 "follower-nextIndex: %d, leader-snapshot-index: %d, " +
536 "leader-last-index: %d", logName(), followerId,
537 followerNextIndex, leaderSnapShotIndex, leaderLastIndex));
540 // Send heartbeat to follower whenever install snapshot is initiated.
541 sendAppendEntries = true;
542 initiateCaptureSnapshot(followerId, followerNextIndex);
544 } else if(sendHeartbeat) {
545 // we send an AppendEntries, even if the follower is inactive
546 // in-order to update the followers timestamp, in case it becomes active again
547 sendAppendEntries = true;
552 if(sendAppendEntries) {
553 sendAppendEntriesToFollower(followerActor, followerNextIndex,
554 entries, followerId);
559 private void sendAppendEntriesToFollower(ActorSelection followerActor, long followerNextIndex,
560 List<ReplicatedLogEntry> entries, String followerId) {
561 AppendEntries appendEntries = new AppendEntries(currentTerm(), context.getId(),
562 prevLogIndex(followerNextIndex),
563 prevLogTerm(followerNextIndex), entries,
564 context.getCommitIndex(), super.getReplicatedToAllIndex(), context.getPayloadVersion());
566 if(!entries.isEmpty() || LOG.isTraceEnabled()) {
567 LOG.debug("{}: Sending AppendEntries to follower {}: {}", logName(), followerId,
571 followerActor.tell(appendEntries.toSerializable(), actor());
575 * Install Snapshot works as follows
576 * 1. Leader initiates the capture snapshot by sending a CaptureSnapshot message to actor
577 * 2. RaftActor on receipt of the CaptureSnapshotReply (from Shard), stores the received snapshot in the replicated log
578 * and makes a call to Leader's handleMessage , with SendInstallSnapshot message.
579 * 3. Leader , picks the snapshot from im-mem ReplicatedLog and sends it in chunks to the Follower
580 * 4. On complete, Follower sends back a InstallSnapshotReply.
581 * 5. On receipt of the InstallSnapshotReply for the last chunk, Leader marks the install complete for that follower
582 * and replenishes the memory by deleting the snapshot in Replicated log.
583 * 6. If another follower requires a snapshot and a snapshot has been collected (via CaptureSnapshotReply)
584 * then send the existing snapshot in chunks to the follower.
586 * @param followerNextIndex
588 private void initiateCaptureSnapshot(String followerId, long followerNextIndex) {
589 if (!context.getReplicatedLog().isPresent(followerNextIndex) &&
590 context.getReplicatedLog().isInSnapshot(followerNextIndex)) {
592 if (snapshot.isPresent()) {
593 // if a snapshot is present in the memory, most likely another install is in progress
594 // no need to capture snapshot.
595 // This could happen if another follower needs an install when one is going on.
596 final ActorSelection followerActor = context.getPeerActorSelection(followerId);
597 sendSnapshotChunk(followerActor, followerId);
601 context.getSnapshotManager().captureToInstall(context.getReplicatedLog().last(),
602 this.getReplicatedToAllIndex(), followerId);
608 private void sendInstallSnapshot() {
609 LOG.debug("{}: sendInstallSnapshot", logName());
610 for (Entry<String, FollowerLogInformation> e : followerToLog.entrySet()) {
611 ActorSelection followerActor = context.getPeerActorSelection(e.getKey());
613 if (followerActor != null) {
614 long nextIndex = e.getValue().getNextIndex();
616 if (!context.getReplicatedLog().isPresent(nextIndex) &&
617 context.getReplicatedLog().isInSnapshot(nextIndex)) {
618 sendSnapshotChunk(followerActor, e.getKey());
625 * Sends a snapshot chunk to a given follower
626 * InstallSnapshot should qualify as a heartbeat too.
628 private void sendSnapshotChunk(ActorSelection followerActor, String followerId) {
630 if (snapshot.isPresent()) {
631 ByteString nextSnapshotChunk = getNextSnapshotChunk(followerId, snapshot.get().getSnapshotBytes());
633 // Note: the previous call to getNextSnapshotChunk has the side-effect of adding
634 // followerId to the followerToSnapshot map.
635 FollowerToSnapshot followerToSnapshot = mapFollowerToSnapshot.get(followerId);
638 new InstallSnapshot(currentTerm(), context.getId(),
639 snapshot.get().getLastIncludedIndex(),
640 snapshot.get().getLastIncludedTerm(),
642 followerToSnapshot.incrementChunkIndex(),
643 followerToSnapshot.getTotalChunks(),
644 Optional.of(followerToSnapshot.getLastChunkHashCode())
649 if(LOG.isDebugEnabled()) {
650 LOG.debug("{}: InstallSnapshot sent to follower {}, Chunk: {}/{}",
651 logName(), followerActor.path(), followerToSnapshot.getChunkIndex(),
652 followerToSnapshot.getTotalChunks());
655 } catch (IOException e) {
656 LOG.error("{}: InstallSnapshot failed for Leader.", logName(), e);
661 * Acccepts snaphot as ByteString, enters into map for future chunks
662 * creates and return a ByteString chunk
664 private ByteString getNextSnapshotChunk(String followerId, ByteString snapshotBytes) throws IOException {
665 FollowerToSnapshot followerToSnapshot = mapFollowerToSnapshot.get(followerId);
666 if (followerToSnapshot == null) {
667 followerToSnapshot = new FollowerToSnapshot(snapshotBytes);
668 mapFollowerToSnapshot.put(followerId, followerToSnapshot);
670 ByteString nextChunk = followerToSnapshot.getNextChunk();
672 LOG.debug("{}: next snapshot chunk size for follower {}: {}", logName(), followerId, nextChunk.size());
677 private void sendHeartBeat() {
678 if (!followerToLog.isEmpty()) {
679 LOG.trace("{}: Sending heartbeat", logName());
680 sendAppendEntries(context.getConfigParams().getHeartBeatInterval().toMillis(), true);
684 private void stopHeartBeat() {
685 if (heartbeatSchedule != null && !heartbeatSchedule.isCancelled()) {
686 heartbeatSchedule.cancel();
690 private void scheduleHeartBeat(FiniteDuration interval) {
691 if (followerToLog.isEmpty()) {
692 // Optimization - do not bother scheduling a heartbeat as there are
699 // Schedule a heartbeat. When the scheduler triggers a SendHeartbeat
700 // message is sent to itself.
701 // Scheduling the heartbeat only once here because heartbeats do not
702 // need to be sent if there are other messages being sent to the remote
704 heartbeatSchedule = context.getActorSystem().scheduler().scheduleOnce(
705 interval, context.getActor(), new SendHeartBeat(),
706 context.getActorSystem().dispatcher(), context.getActor());
710 public void close() throws Exception {
715 public String getLeaderId() {
716 return context.getId();
719 protected boolean isLeaderIsolated() {
720 int minPresent = minIsolatedLeaderPeerCount;
721 for (FollowerLogInformation followerLogInformation : followerToLog.values()) {
722 if (followerLogInformation.isFollowerActive()) {
724 if (minPresent == 0) {
729 return (minPresent != 0);
733 * Encapsulates the snapshot bytestring and handles the logic of sending
736 protected class FollowerToSnapshot {
737 private final ByteString snapshotBytes;
738 private int offset = 0;
739 // the next snapshot chunk is sent only if the replyReceivedForOffset matches offset
740 private int replyReceivedForOffset;
741 // if replyStatus is false, the previous chunk is attempted
742 private boolean replyStatus = false;
743 private int chunkIndex;
744 private final int totalChunks;
745 private int lastChunkHashCode = AbstractLeader.INITIAL_LAST_CHUNK_HASH_CODE;
746 private int nextChunkHashCode = AbstractLeader.INITIAL_LAST_CHUNK_HASH_CODE;
748 public FollowerToSnapshot(ByteString snapshotBytes) {
749 this.snapshotBytes = snapshotBytes;
750 int size = snapshotBytes.size();
751 totalChunks = ( size / context.getConfigParams().getSnapshotChunkSize()) +
752 ((size % context.getConfigParams().getSnapshotChunkSize()) > 0 ? 1 : 0);
753 if(LOG.isDebugEnabled()) {
754 LOG.debug("{}: Snapshot {} bytes, total chunks to send:{}",
755 logName(), size, totalChunks);
757 replyReceivedForOffset = -1;
758 chunkIndex = AbstractLeader.FIRST_CHUNK_INDEX;
761 public ByteString getSnapshotBytes() {
762 return snapshotBytes;
765 public int incrementOffset() {
767 // if prev chunk failed, we would want to sent the same chunk again
768 offset = offset + context.getConfigParams().getSnapshotChunkSize();
773 public int incrementChunkIndex() {
775 // if prev chunk failed, we would want to sent the same chunk again
776 chunkIndex = chunkIndex + 1;
781 public int getChunkIndex() {
785 public int getTotalChunks() {
789 public boolean canSendNextChunk() {
790 // we only send a false if a chunk is sent but we have not received a reply yet
791 return replyReceivedForOffset == offset;
794 public boolean isLastChunk(int chunkIndex) {
795 return totalChunks == chunkIndex;
798 public void markSendStatus(boolean success) {
800 // if the chunk sent was successful
801 replyReceivedForOffset = offset;
803 lastChunkHashCode = nextChunkHashCode;
805 // if the chunk sent was failure
806 replyReceivedForOffset = offset;
811 public ByteString getNextChunk() {
812 int snapshotLength = getSnapshotBytes().size();
813 int start = incrementOffset();
814 int size = context.getConfigParams().getSnapshotChunkSize();
815 if (context.getConfigParams().getSnapshotChunkSize() > snapshotLength) {
816 size = snapshotLength;
818 if ((start + context.getConfigParams().getSnapshotChunkSize()) > snapshotLength) {
819 size = snapshotLength - start;
824 LOG.debug("{}: Next chunk: length={}, offset={},size={}", logName(),
825 snapshotLength, start, size);
827 ByteString substring = getSnapshotBytes().substring(start, start + size);
828 nextChunkHashCode = substring.hashCode();
833 * reset should be called when the Follower needs to be sent the snapshot from the beginning
838 replyReceivedForOffset = offset;
839 chunkIndex = AbstractLeader.FIRST_CHUNK_INDEX;
840 lastChunkHashCode = AbstractLeader.INITIAL_LAST_CHUNK_HASH_CODE;
843 public int getLastChunkHashCode() {
844 return lastChunkHashCode;
848 // called from example-actor for printing the follower-states
849 public String printFollowerStates() {
850 final StringBuilder sb = new StringBuilder();
853 for (FollowerLogInformation followerLogInformation : followerToLog.values()) {
855 sb.append(followerLogInformation.getId());
856 sb.append(" state:");
857 sb.append(followerLogInformation.isFollowerActive());
862 return sb.toString();
866 public FollowerLogInformation getFollower(String followerId) {
867 return followerToLog.get(followerId);
871 protected void setFollowerSnapshot(String followerId, FollowerToSnapshot snapshot) {
872 mapFollowerToSnapshot.put(followerId, snapshot);
876 public int followerSnapshotSize() {
877 return mapFollowerToSnapshot.size();
881 public int followerLogSize() {
882 return followerToLog.size();
885 private static class SnapshotHolder {
886 private final long lastIncludedTerm;
887 private final long lastIncludedIndex;
888 private final ByteString snapshotBytes;
890 SnapshotHolder(Snapshot snapshot) {
891 this.lastIncludedTerm = snapshot.getLastAppliedTerm();
892 this.lastIncludedIndex = snapshot.getLastAppliedIndex();
893 this.snapshotBytes = ByteString.copyFrom(snapshot.getState());
896 long getLastIncludedTerm() {
897 return lastIncludedTerm;
900 long getLastIncludedIndex() {
901 return lastIncludedIndex;
904 ByteString getSnapshotBytes() {
905 return snapshotBytes;