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 org.opendaylight.controller.cluster.raft.ClientRequestTracker;
30 import org.opendaylight.controller.cluster.raft.ClientRequestTrackerImpl;
31 import org.opendaylight.controller.cluster.raft.FollowerLogInformation;
32 import org.opendaylight.controller.cluster.raft.FollowerLogInformationImpl;
33 import org.opendaylight.controller.cluster.raft.RaftActorContext;
34 import org.opendaylight.controller.cluster.raft.RaftState;
35 import org.opendaylight.controller.cluster.raft.ReplicatedLogEntry;
36 import org.opendaylight.controller.cluster.raft.base.messages.CaptureSnapshot;
37 import org.opendaylight.controller.cluster.raft.base.messages.Replicate;
38 import org.opendaylight.controller.cluster.raft.base.messages.SendHeartBeat;
39 import org.opendaylight.controller.cluster.raft.base.messages.SendInstallSnapshot;
40 import org.opendaylight.controller.cluster.raft.messages.AppendEntries;
41 import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
42 import org.opendaylight.controller.cluster.raft.messages.InstallSnapshot;
43 import org.opendaylight.controller.cluster.raft.messages.InstallSnapshotReply;
44 import org.opendaylight.controller.cluster.raft.messages.RaftRPC;
45 import org.opendaylight.controller.cluster.raft.messages.RequestVoteReply;
46 import scala.concurrent.duration.FiniteDuration;
49 * The behavior of a RaftActor when it is in the Leader state
53 * <li> Upon election: send initial empty AppendEntries RPCs
54 * (heartbeat) to each server; repeat during idle periods to
55 * prevent election timeouts (§5.2)
56 * <li> If command received from client: append entry to local log,
57 * respond after entry applied to state machine (§5.3)
58 * <li> If last log index ≥ nextIndex for a follower: send
59 * AppendEntries RPC with log entries starting at nextIndex
61 * <li> If successful: update nextIndex and matchIndex for
63 * <li> If AppendEntries fails because of log inconsistency:
64 * decrement nextIndex and retry (§5.3)
66 * <li> If there exists an N such that N > commitIndex, a majority
67 * of matchIndex[i] ≥ N, and log[N].term == currentTerm:
68 * set commitIndex = N (§5.3, §5.4).
70 public abstract class AbstractLeader extends AbstractRaftActorBehavior {
72 // The index of the first chunk that is sent when installing a snapshot
73 public static final int FIRST_CHUNK_INDEX = 1;
75 // The index that the follower should respond with if it needs the install snapshot to be reset
76 public static final int INVALID_CHUNK_INDEX = -1;
78 // This would be passed as the hash code of the last chunk when sending the first chunk
79 public static final int INITIAL_LAST_CHUNK_HASH_CODE = -1;
81 private final Map<String, FollowerLogInformation> followerToLog;
82 private final Map<String, FollowerToSnapshot> mapFollowerToSnapshot = new HashMap<>();
84 private Cancellable heartbeatSchedule = null;
86 private final Collection<ClientRequestTracker> trackerList = new LinkedList<>();
88 protected final int minReplicationCount;
90 protected final int minIsolatedLeaderPeerCount;
92 private Optional<ByteString> snapshot;
94 public AbstractLeader(RaftActorContext context) {
95 super(context, RaftState.Leader);
97 final Builder<String, FollowerLogInformation> ftlBuilder = ImmutableMap.builder();
98 for (String followerId : context.getPeerAddresses().keySet()) {
99 FollowerLogInformation followerLogInformation =
100 new FollowerLogInformationImpl(followerId,
101 context.getCommitIndex(), -1,
102 context.getConfigParams().getElectionTimeOutInterval());
104 ftlBuilder.put(followerId, followerLogInformation);
106 followerToLog = ftlBuilder.build();
108 leaderId = context.getId();
110 LOG.debug("{}: Election: Leader has following peers: {}", logName(), getFollowerIds());
112 minReplicationCount = getMajorityVoteCount(getFollowerIds().size());
114 // the isolated Leader peer count will be 1 less than the majority vote count.
115 // this is because the vote count has the self vote counted in it
117 // 0 peers = 1 votesRequired , minIsolatedLeaderPeerCount = 0
118 // 2 peers = 2 votesRequired , minIsolatedLeaderPeerCount = 1
119 // 4 peers = 3 votesRequired, minIsolatedLeaderPeerCount = 2
120 minIsolatedLeaderPeerCount = minReplicationCount > 0 ? (minReplicationCount - 1) : 0;
122 snapshot = Optional.absent();
124 // Immediately schedule a heartbeat
125 // Upon election: send initial empty AppendEntries RPCs
126 // (heartbeat) to each server; repeat during idle periods to
127 // prevent election timeouts (§5.2)
128 sendAppendEntries(0, false);
132 * Return an immutable collection of follower identifiers.
134 * @return Collection of follower IDs
136 protected final Collection<String> getFollowerIds() {
137 return followerToLog.keySet();
141 void setSnapshot(Optional<ByteString> snapshot) {
142 this.snapshot = snapshot;
146 protected RaftActorBehavior handleAppendEntries(ActorRef sender,
147 AppendEntries appendEntries) {
149 LOG.debug("{}: handleAppendEntries: {}", logName(), appendEntries);
155 protected RaftActorBehavior handleAppendEntriesReply(ActorRef sender,
156 AppendEntriesReply appendEntriesReply) {
158 if(LOG.isTraceEnabled()) {
159 LOG.trace("{}: handleAppendEntriesReply: {}", logName(), appendEntriesReply);
160 } else if(LOG.isDebugEnabled() && !appendEntriesReply.isSuccess()) {
161 LOG.debug("{}: handleAppendEntriesReply: {}", logName(), appendEntriesReply);
164 // Update the FollowerLogInformation
165 String followerId = appendEntriesReply.getFollowerId();
166 FollowerLogInformation followerLogInformation =
167 followerToLog.get(followerId);
169 if(followerLogInformation == null){
170 LOG.error("{}: handleAppendEntriesReply - unknown follower {}", logName(), followerId);
174 if(followerLogInformation.timeSinceLastActivity() >
175 context.getConfigParams().getElectionTimeOutInterval().toMillis()) {
176 LOG.error("{} : handleAppendEntriesReply delayed beyond election timeout, " +
177 "appendEntriesReply : {}, timeSinceLastActivity : {}, lastApplied : {}, commitIndex : {}",
178 logName(), appendEntriesReply, followerLogInformation.timeSinceLastActivity(),
179 context.getLastApplied(), context.getCommitIndex());
182 followerLogInformation.markFollowerActive();
184 if (appendEntriesReply.isSuccess()) {
185 followerLogInformation
186 .setMatchIndex(appendEntriesReply.getLogLastIndex());
187 followerLogInformation
188 .setNextIndex(appendEntriesReply.getLogLastIndex() + 1);
191 // TODO: When we find that the follower is out of sync with the
192 // Leader we simply decrement that followers next index by 1.
193 // Would it be possible to do better than this? The RAFT spec
194 // does not explicitly deal with it but may be something for us to
197 followerLogInformation.decrNextIndex();
200 // Now figure out if this reply warrants a change in the commitIndex
201 // If there exists an N such that N > commitIndex, a majority
202 // of matchIndex[i] ≥ N, and log[N].term == currentTerm:
203 // set commitIndex = N (§5.3, §5.4).
204 for (long N = context.getCommitIndex() + 1; ; N++) {
205 int replicatedCount = 1;
207 for (FollowerLogInformation info : followerToLog.values()) {
208 if (info.getMatchIndex() >= N) {
213 if (replicatedCount >= minReplicationCount) {
214 ReplicatedLogEntry replicatedLogEntry = context.getReplicatedLog().get(N);
215 if (replicatedLogEntry != null &&
216 replicatedLogEntry.getTerm() == currentTerm()) {
217 context.setCommitIndex(N);
224 // Apply the change to the state machine
225 if (context.getCommitIndex() > context.getLastApplied()) {
226 LOG.debug("{}: handleAppendEntriesReply: applying to log - commitIndex: {}, lastAppliedIndex: {}",
227 logName(), context.getCommitIndex(), context.getLastApplied());
229 applyLogToStateMachine(context.getCommitIndex());
232 if (!context.isSnapshotCaptureInitiated()) {
236 //Send the next log entry immediately, if possible, no need to wait for heartbeat to trigger that event
237 sendUpdatesToFollower(followerId, followerLogInformation, false, false);
241 private void purgeInMemoryLog() {
242 //find the lowest index across followers which has been replicated to all.
243 // lastApplied if there are no followers, so that we keep clearing the log for single-node
244 // we would delete the in-mem log from that index on, in-order to minimize mem usage
245 // we would also share this info thru AE with the followers so that they can delete their log entries as well.
246 long minReplicatedToAllIndex = followerToLog.isEmpty() ? context.getLastApplied() : Long.MAX_VALUE;
247 for (FollowerLogInformation info : followerToLog.values()) {
248 minReplicatedToAllIndex = Math.min(minReplicatedToAllIndex, info.getMatchIndex());
251 super.performSnapshotWithoutCapture(minReplicatedToAllIndex);
255 protected ClientRequestTracker removeClientRequestTracker(long logIndex) {
256 final Iterator<ClientRequestTracker> it = trackerList.iterator();
257 while (it.hasNext()) {
258 final ClientRequestTracker t = it.next();
259 if (t.getIndex() == logIndex) {
269 protected ClientRequestTracker findClientRequestTracker(long logIndex) {
270 for (ClientRequestTracker tracker : trackerList) {
271 if (tracker.getIndex() == logIndex) {
279 protected RaftActorBehavior handleRequestVoteReply(ActorRef sender,
280 RequestVoteReply requestVoteReply) {
285 public RaftActorBehavior handleMessage(ActorRef sender, Object originalMessage) {
286 Preconditions.checkNotNull(sender, "sender should not be null");
288 Object message = fromSerializableMessage(originalMessage);
290 if (message instanceof RaftRPC) {
291 RaftRPC rpc = (RaftRPC) message;
292 // If RPC request or response contains term T > currentTerm:
293 // set currentTerm = T, convert to follower (§5.1)
294 // This applies to all RPC messages and responses
295 if (rpc.getTerm() > context.getTermInformation().getCurrentTerm()) {
296 LOG.debug("{}: Term {} in \"{}\" message is greater than leader's term {} - switching to Follower",
297 logName(), rpc.getTerm(), rpc, context.getTermInformation().getCurrentTerm());
299 context.getTermInformation().updateAndPersist(rpc.getTerm(), null);
301 return switchBehavior(new Follower(context));
306 if (message instanceof SendHeartBeat) {
310 } else if(message instanceof SendInstallSnapshot) {
311 // received from RaftActor
312 setSnapshot(Optional.of(((SendInstallSnapshot) message).getSnapshot()));
313 sendInstallSnapshot();
315 } else if (message instanceof Replicate) {
316 replicate((Replicate) message);
318 } else if (message instanceof InstallSnapshotReply){
319 handleInstallSnapshotReply((InstallSnapshotReply) message);
323 scheduleHeartBeat(context.getConfigParams().getHeartBeatInterval());
326 return super.handleMessage(sender, message);
329 private void handleInstallSnapshotReply(InstallSnapshotReply reply) {
330 LOG.debug("{}: handleInstallSnapshotReply: {}", logName(), reply);
332 String followerId = reply.getFollowerId();
333 FollowerToSnapshot followerToSnapshot = mapFollowerToSnapshot.get(followerId);
335 if (followerToSnapshot == null) {
336 LOG.error("{}: FollowerId {} in InstallSnapshotReply not known to Leader",
337 logName(), followerId);
341 FollowerLogInformation followerLogInformation = followerToLog.get(followerId);
342 followerLogInformation.markFollowerActive();
344 if (followerToSnapshot.getChunkIndex() == reply.getChunkIndex()) {
345 boolean wasLastChunk = false;
346 if (reply.isSuccess()) {
347 if(followerToSnapshot.isLastChunk(reply.getChunkIndex())) {
348 //this was the last chunk reply
349 if(LOG.isDebugEnabled()) {
350 LOG.debug("{}: InstallSnapshotReply received, " +
351 "last chunk received, Chunk: {}. Follower: {} Setting nextIndex: {}",
352 logName(), reply.getChunkIndex(), followerId,
353 context.getReplicatedLog().getSnapshotIndex() + 1
357 followerLogInformation.setMatchIndex(
358 context.getReplicatedLog().getSnapshotIndex());
359 followerLogInformation.setNextIndex(
360 context.getReplicatedLog().getSnapshotIndex() + 1);
361 mapFollowerToSnapshot.remove(followerId);
363 LOG.debug("{}: follower: {}, matchIndex set to {}, nextIndex set to {}",
364 logName(), followerId, followerLogInformation.getMatchIndex(),
365 followerLogInformation.getNextIndex());
367 if (mapFollowerToSnapshot.isEmpty()) {
368 // once there are no pending followers receiving snapshots
369 // we can remove snapshot from the memory
370 setSnapshot(Optional.<ByteString>absent());
375 followerToSnapshot.markSendStatus(true);
378 LOG.info("{}: InstallSnapshotReply received sending snapshot chunk failed, Will retry, Chunk: {}",
379 logName(), reply.getChunkIndex());
381 followerToSnapshot.markSendStatus(false);
384 if (!wasLastChunk && followerToSnapshot.canSendNextChunk()) {
385 ActorSelection followerActor = context.getPeerActorSelection(followerId);
386 if(followerActor != null) {
387 sendSnapshotChunk(followerActor, followerId);
392 LOG.error("{}: Chunk index {} in InstallSnapshotReply from follower {} does not match expected index {}",
393 logName(), reply.getChunkIndex(), followerId,
394 followerToSnapshot.getChunkIndex());
396 if(reply.getChunkIndex() == INVALID_CHUNK_INDEX){
397 // Since the Follower did not find this index to be valid we should reset the follower snapshot
398 // so that Installing the snapshot can resume from the beginning
399 followerToSnapshot.reset();
404 private void replicate(Replicate replicate) {
405 long logIndex = replicate.getReplicatedLogEntry().getIndex();
407 LOG.debug("{}: Replicate message: identifier: {}, logIndex: {}", logName(),
408 replicate.getIdentifier(), logIndex);
410 // Create a tracker entry we will use this later to notify the
413 new ClientRequestTrackerImpl(replicate.getClientActor(),
414 replicate.getIdentifier(),
418 if (followerToLog.isEmpty()) {
419 context.setCommitIndex(logIndex);
420 applyLogToStateMachine(logIndex);
422 sendAppendEntries(0, false);
426 private void sendAppendEntries(long timeSinceLastActivityInterval, boolean isHeartbeat) {
427 // Send an AppendEntries to all followers
428 for (Entry<String, FollowerLogInformation> e : followerToLog.entrySet()) {
429 final String followerId = e.getKey();
430 final FollowerLogInformation followerLogInformation = e.getValue();
431 // This checks helps not to send a repeat message to the follower
432 if(!followerLogInformation.isFollowerActive() ||
433 followerLogInformation.timeSinceLastActivity() >= timeSinceLastActivityInterval) {
434 sendUpdatesToFollower(followerId, followerLogInformation, true, isHeartbeat);
441 * This method checks if any update needs to be sent to the given follower. This includes append log entries,
442 * sending next snapshot chunk, and initiating a snapshot.
443 * @return true if any update is sent, false otherwise
446 private void sendUpdatesToFollower(String followerId, FollowerLogInformation followerLogInformation,
447 boolean sendHeartbeat, boolean isHeartbeat) {
449 ActorSelection followerActor = context.getPeerActorSelection(followerId);
450 if (followerActor != null) {
451 long followerNextIndex = followerLogInformation.getNextIndex();
452 boolean isFollowerActive = followerLogInformation.isFollowerActive();
454 if (mapFollowerToSnapshot.get(followerId) != null) {
455 // if install snapshot is in process , then sent next chunk if possible
456 if (isFollowerActive && mapFollowerToSnapshot.get(followerId).canSendNextChunk()) {
457 sendSnapshotChunk(followerActor, followerId);
458 } else if(sendHeartbeat) {
459 // we send a heartbeat even if we have not received a reply for the last chunk
460 sendAppendEntriesToFollower(followerActor, followerLogInformation.getNextIndex(),
461 Collections.<ReplicatedLogEntry>emptyList(), followerId);
464 long leaderLastIndex = context.getReplicatedLog().lastIndex();
465 long leaderSnapShotIndex = context.getReplicatedLog().getSnapshotIndex();
467 if(!isHeartbeat || LOG.isTraceEnabled()) {
468 LOG.debug("{}: Checking sendAppendEntries for follower {}, leaderLastIndex: {}, leaderSnapShotIndex: {}",
469 logName(), followerId, leaderLastIndex, leaderSnapShotIndex);
472 if (isFollowerActive && context.getReplicatedLog().isPresent(followerNextIndex)) {
474 LOG.debug("{}: sendAppendEntries: {} is present for follower {}", logName(),
475 followerNextIndex, followerId);
477 // FIXME : Sending one entry at a time
478 final List<ReplicatedLogEntry> entries = context.getReplicatedLog().getFrom(followerNextIndex, 1);
480 sendAppendEntriesToFollower(followerActor, followerNextIndex, entries, followerId);
482 } else if (isFollowerActive && followerNextIndex >= 0 &&
483 leaderLastIndex > followerNextIndex && !context.isSnapshotCaptureInitiated()) {
484 // if the followers next index is not present in the leaders log, and
485 // if the follower is just not starting and if leader's index is more than followers index
486 // then snapshot should be sent
488 if (LOG.isDebugEnabled()) {
489 LOG.debug(String.format("%s: InitiateInstallSnapshot to follower: %s," +
490 "follower-nextIndex: %d, leader-snapshot-index: %d, " +
491 "leader-last-index: %d", logName(), followerId,
492 followerNextIndex, leaderSnapShotIndex, leaderLastIndex));
495 // Send heartbeat to follower whenever install snapshot is initiated.
496 sendAppendEntriesToFollower(followerActor, followerLogInformation.getNextIndex(),
497 Collections.<ReplicatedLogEntry>emptyList(), followerId);
499 initiateCaptureSnapshot(followerId, followerNextIndex);
501 } else if(sendHeartbeat) {
502 //we send an AppendEntries, even if the follower is inactive
503 // in-order to update the followers timestamp, in case it becomes active again
504 sendAppendEntriesToFollower(followerActor, followerLogInformation.getNextIndex(),
505 Collections.<ReplicatedLogEntry>emptyList(), followerId);
512 private void sendAppendEntriesToFollower(ActorSelection followerActor, long followerNextIndex,
513 List<ReplicatedLogEntry> entries, String followerId) {
514 AppendEntries appendEntries = new AppendEntries(currentTerm(), context.getId(),
515 prevLogIndex(followerNextIndex),
516 prevLogTerm(followerNextIndex), entries,
517 context.getCommitIndex(), super.getReplicatedToAllIndex());
519 if(!entries.isEmpty() || LOG.isTraceEnabled()) {
520 LOG.debug("{}: Sending AppendEntries to follower {}: {}", logName(), followerId,
524 followerActor.tell(appendEntries.toSerializable(), actor());
528 * Install Snapshot works as follows
529 * 1. Leader initiates the capture snapshot by sending a CaptureSnapshot message to actor
530 * 2. RaftActor on receipt of the CaptureSnapshotReply (from Shard), stores the received snapshot in the replicated log
531 * and makes a call to Leader's handleMessage , with SendInstallSnapshot message.
532 * 3. Leader , picks the snapshot from im-mem ReplicatedLog and sends it in chunks to the Follower
533 * 4. On complete, Follower sends back a InstallSnapshotReply.
534 * 5. On receipt of the InstallSnapshotReply for the last chunk, Leader marks the install complete for that follower
535 * and replenishes the memory by deleting the snapshot in Replicated log.
536 * 6. If another follower requires a snapshot and a snapshot has been collected (via CaptureSnapshotReply)
537 * then send the existing snapshot in chunks to the follower.
539 * @param followerNextIndex
541 private void initiateCaptureSnapshot(String followerId, long followerNextIndex) {
542 if (!context.getReplicatedLog().isPresent(followerNextIndex) &&
543 context.getReplicatedLog().isInSnapshot(followerNextIndex)) {
545 if (snapshot.isPresent()) {
546 // if a snapshot is present in the memory, most likely another install is in progress
547 // no need to capture snapshot.
548 // This could happen if another follower needs an install when one is going on.
549 final ActorSelection followerActor = context.getPeerActorSelection(followerId);
550 sendSnapshotChunk(followerActor, followerId);
552 } else if (!context.isSnapshotCaptureInitiated()) {
554 LOG.info("{}: Initiating Snapshot Capture to Install Snapshot, Leader:{}", logName(), getLeaderId());
555 ReplicatedLogEntry lastAppliedEntry = context.getReplicatedLog().get(context.getLastApplied());
556 long lastAppliedIndex = -1;
557 long lastAppliedTerm = -1;
559 if (lastAppliedEntry != null) {
560 lastAppliedIndex = lastAppliedEntry.getIndex();
561 lastAppliedTerm = lastAppliedEntry.getTerm();
562 } else if (context.getReplicatedLog().getSnapshotIndex() > -1) {
563 lastAppliedIndex = context.getReplicatedLog().getSnapshotIndex();
564 lastAppliedTerm = context.getReplicatedLog().getSnapshotTerm();
567 boolean isInstallSnapshotInitiated = true;
568 long replicatedToAllIndex = super.getReplicatedToAllIndex();
569 ReplicatedLogEntry replicatedToAllEntry = context.getReplicatedLog().get(replicatedToAllIndex);
570 actor().tell(new CaptureSnapshot(lastIndex(), lastTerm(), lastAppliedIndex, lastAppliedTerm,
571 (replicatedToAllEntry != null ? replicatedToAllEntry.getIndex() : -1),
572 (replicatedToAllEntry != null ? replicatedToAllEntry.getTerm() : -1),
573 isInstallSnapshotInitiated), actor());
574 context.setSnapshotCaptureInitiated(true);
580 private void sendInstallSnapshot() {
581 LOG.debug("{}: sendInstallSnapshot", logName());
582 for (Entry<String, FollowerLogInformation> e : followerToLog.entrySet()) {
583 ActorSelection followerActor = context.getPeerActorSelection(e.getKey());
585 if (followerActor != null) {
586 long nextIndex = e.getValue().getNextIndex();
588 if (!context.getReplicatedLog().isPresent(nextIndex) &&
589 context.getReplicatedLog().isInSnapshot(nextIndex)) {
590 sendSnapshotChunk(followerActor, e.getKey());
597 * Sends a snapshot chunk to a given follower
598 * InstallSnapshot should qualify as a heartbeat too.
600 private void sendSnapshotChunk(ActorSelection followerActor, String followerId) {
602 if (snapshot.isPresent()) {
603 ByteString nextSnapshotChunk = getNextSnapshotChunk(followerId,snapshot.get());
605 // Note: the previous call to getNextSnapshotChunk has the side-effect of adding
606 // followerId to the followerToSnapshot map.
607 FollowerToSnapshot followerToSnapshot = mapFollowerToSnapshot.get(followerId);
610 new InstallSnapshot(currentTerm(), context.getId(),
611 context.getReplicatedLog().getSnapshotIndex(),
612 context.getReplicatedLog().getSnapshotTerm(),
614 followerToSnapshot.incrementChunkIndex(),
615 followerToSnapshot.getTotalChunks(),
616 Optional.of(followerToSnapshot.getLastChunkHashCode())
620 LOG.info("{}: InstallSnapshot sent to follower {}, Chunk: {}/{}",
621 logName(), followerActor.path(),
622 followerToSnapshot.getChunkIndex(),
623 followerToSnapshot.getTotalChunks());
625 } catch (IOException e) {
626 LOG.error("{}: InstallSnapshot failed for Leader.", logName(), e);
631 * Acccepts snaphot as ByteString, enters into map for future chunks
632 * creates and return a ByteString chunk
634 private ByteString getNextSnapshotChunk(String followerId, ByteString snapshotBytes) throws IOException {
635 FollowerToSnapshot followerToSnapshot = mapFollowerToSnapshot.get(followerId);
636 if (followerToSnapshot == null) {
637 followerToSnapshot = new FollowerToSnapshot(snapshotBytes);
638 mapFollowerToSnapshot.put(followerId, followerToSnapshot);
640 ByteString nextChunk = followerToSnapshot.getNextChunk();
642 LOG.debug("{}: next snapshot chunk size for follower {}: {}", logName(), followerId, nextChunk.size());
647 private void sendHeartBeat() {
648 if (!followerToLog.isEmpty()) {
649 LOG.trace("{}: Sending heartbeat", logName());
650 sendAppendEntries(context.getConfigParams().getHeartBeatInterval().toMillis(), true);
654 private void stopHeartBeat() {
655 if (heartbeatSchedule != null && !heartbeatSchedule.isCancelled()) {
656 heartbeatSchedule.cancel();
660 private void scheduleHeartBeat(FiniteDuration interval) {
661 if (followerToLog.isEmpty()) {
662 // Optimization - do not bother scheduling a heartbeat as there are
669 // Schedule a heartbeat. When the scheduler triggers a SendHeartbeat
670 // message is sent to itself.
671 // Scheduling the heartbeat only once here because heartbeats do not
672 // need to be sent if there are other messages being sent to the remote
674 heartbeatSchedule = context.getActorSystem().scheduler().scheduleOnce(
675 interval, context.getActor(), new SendHeartBeat(),
676 context.getActorSystem().dispatcher(), context.getActor());
680 public void close() throws Exception {
685 public String getLeaderId() {
686 return context.getId();
689 protected boolean isLeaderIsolated() {
690 int minPresent = minIsolatedLeaderPeerCount;
691 for (FollowerLogInformation followerLogInformation : followerToLog.values()) {
692 if (followerLogInformation.isFollowerActive()) {
694 if (minPresent == 0) {
699 return (minPresent != 0);
703 * Encapsulates the snapshot bytestring and handles the logic of sending
706 protected class FollowerToSnapshot {
707 private final ByteString snapshotBytes;
708 private int offset = 0;
709 // the next snapshot chunk is sent only if the replyReceivedForOffset matches offset
710 private int replyReceivedForOffset;
711 // if replyStatus is false, the previous chunk is attempted
712 private boolean replyStatus = false;
713 private int chunkIndex;
714 private final int totalChunks;
715 private int lastChunkHashCode = AbstractLeader.INITIAL_LAST_CHUNK_HASH_CODE;
716 private int nextChunkHashCode = AbstractLeader.INITIAL_LAST_CHUNK_HASH_CODE;
718 public FollowerToSnapshot(ByteString snapshotBytes) {
719 this.snapshotBytes = snapshotBytes;
720 int size = snapshotBytes.size();
721 totalChunks = ( size / context.getConfigParams().getSnapshotChunkSize()) +
722 ((size % context.getConfigParams().getSnapshotChunkSize()) > 0 ? 1 : 0);
723 if(LOG.isDebugEnabled()) {
724 LOG.debug("{}: Snapshot {} bytes, total chunks to send:{}",
725 logName(), size, totalChunks);
727 replyReceivedForOffset = -1;
728 chunkIndex = AbstractLeader.FIRST_CHUNK_INDEX;
731 public ByteString getSnapshotBytes() {
732 return snapshotBytes;
735 public int incrementOffset() {
737 // if prev chunk failed, we would want to sent the same chunk again
738 offset = offset + context.getConfigParams().getSnapshotChunkSize();
743 public int incrementChunkIndex() {
745 // if prev chunk failed, we would want to sent the same chunk again
746 chunkIndex = chunkIndex + 1;
751 public int getChunkIndex() {
755 public int getTotalChunks() {
759 public boolean canSendNextChunk() {
760 // we only send a false if a chunk is sent but we have not received a reply yet
761 return replyReceivedForOffset == offset;
764 public boolean isLastChunk(int chunkIndex) {
765 return totalChunks == chunkIndex;
768 public void markSendStatus(boolean success) {
770 // if the chunk sent was successful
771 replyReceivedForOffset = offset;
773 lastChunkHashCode = nextChunkHashCode;
775 // if the chunk sent was failure
776 replyReceivedForOffset = offset;
781 public ByteString getNextChunk() {
782 int snapshotLength = getSnapshotBytes().size();
783 int start = incrementOffset();
784 int size = context.getConfigParams().getSnapshotChunkSize();
785 if (context.getConfigParams().getSnapshotChunkSize() > snapshotLength) {
786 size = snapshotLength;
788 if ((start + context.getConfigParams().getSnapshotChunkSize()) > snapshotLength) {
789 size = snapshotLength - start;
794 LOG.debug("{}: Next chunk: length={}, offset={},size={}", logName(),
795 snapshotLength, start, size);
797 ByteString substring = getSnapshotBytes().substring(start, start + size);
798 nextChunkHashCode = substring.hashCode();
803 * reset should be called when the Follower needs to be sent the snapshot from the beginning
808 replyReceivedForOffset = offset;
809 chunkIndex = AbstractLeader.FIRST_CHUNK_INDEX;
810 lastChunkHashCode = AbstractLeader.INITIAL_LAST_CHUNK_HASH_CODE;
813 public int getLastChunkHashCode() {
814 return lastChunkHashCode;
818 // called from example-actor for printing the follower-states
819 public String printFollowerStates() {
820 final StringBuilder sb = new StringBuilder();
823 for (FollowerLogInformation followerLogInformation : followerToLog.values()) {
825 sb.append(followerLogInformation.getId());
826 sb.append(" state:");
827 sb.append(followerLogInformation.isFollowerActive());
832 return sb.toString();
836 public FollowerLogInformation getFollower(String followerId) {
837 return followerToLog.get(followerId);
841 protected void setFollowerSnapshot(String followerId, FollowerToSnapshot snapshot) {
842 mapFollowerToSnapshot.put(followerId, snapshot);
846 public int followerSnapshotSize() {
847 return mapFollowerToSnapshot.size();
851 public int followerLogSize() {
852 return followerToLog.size();