9fd2edcb0e1d2dda3ad8e32c2ed6c6cfdca2ee8e
[controller.git] / opendaylight / md-sal / sal-akka-raft / src / main / java / org / opendaylight / controller / cluster / raft / FollowerLogInformation.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;
10
11 import com.google.common.annotations.VisibleForTesting;
12 import com.google.common.base.Preconditions;
13 import com.google.common.base.Stopwatch;
14 import java.util.concurrent.TimeUnit;
15 import javax.annotation.Nonnull;
16 import javax.annotation.Nullable;
17 import org.opendaylight.controller.cluster.raft.behaviors.LeaderInstallSnapshotState;
18
19 /**
20  * The state of the followers log as known by the Leader.
21  *
22  * @author Moiz Raja
23  * @author Thomas Pantelis
24  */
25 public final class FollowerLogInformation {
26     public static final long NO_INDEX = -1;
27
28     private final Stopwatch stopwatch = Stopwatch.createUnstarted();
29
30     private final RaftActorContext context;
31
32     private long nextIndex;
33
34     private long matchIndex;
35
36     private long lastReplicatedIndex = -1L;
37
38     private final Stopwatch lastReplicatedStopwatch = Stopwatch.createUnstarted();
39
40     private short payloadVersion = -1;
41
42     // Assume the HELIUM_VERSION version initially for backwards compatibility until we obtain the follower's
43     // actual version via AppendEntriesReply. Although we no longer support the Helium version, a pre-Boron
44     // follower will not have the version field in AppendEntriesReply so it will be set to 0 which is
45     // HELIUM_VERSION.
46     private short raftVersion = RaftVersions.HELIUM_VERSION;
47
48     private final PeerInfo peerInfo;
49
50     private LeaderInstallSnapshotState installSnapshotState;
51
52     private long slicedLogEntryIndex = NO_INDEX;
53
54     /**
55      * Constructs an instance.
56      *
57      * @param peerInfo the associated PeerInfo of the follower.
58      * @param matchIndex the initial match index.
59      * @param context the RaftActorContext.
60      */
61     @VisibleForTesting
62     FollowerLogInformation(final PeerInfo peerInfo, final long matchIndex, final RaftActorContext context) {
63         this.nextIndex = context.getCommitIndex();
64         this.matchIndex = matchIndex;
65         this.context = context;
66         this.peerInfo = Preconditions.checkNotNull(peerInfo);
67     }
68
69     /**
70      * Constructs an instance with no matching index.
71      *
72      * @param peerInfo the associated PeerInfo of the follower.
73      * @param context the RaftActorContext.
74      */
75     public FollowerLogInformation(final PeerInfo peerInfo, final RaftActorContext context) {
76         this(peerInfo, NO_INDEX, context);
77     }
78
79     /**
80      * Increments the value of the follower's next index.
81      *
82      * @return the new value of nextIndex.
83      */
84     @VisibleForTesting
85     long incrNextIndex() {
86         return nextIndex++;
87     }
88
89     /**
90      * Decrements the value of the follower's next index.
91      *
92      * @return true if the next index was decremented, ie it was previously >= 0, false otherwise.
93      */
94     public boolean decrNextIndex() {
95         if (nextIndex < 0) {
96             return false;
97         }
98
99         nextIndex--;
100         return true;
101     }
102
103     /**
104      * Sets the index of the follower's next log entry.
105      *
106      * @param nextIndex the new index.
107      * @return true if the new index differed from the current index and the current index was updated, false
108      *              otherwise.
109      */
110     @SuppressWarnings("checkstyle:hiddenField")
111     public boolean setNextIndex(final long nextIndex) {
112         if (this.nextIndex != nextIndex) {
113             this.nextIndex = nextIndex;
114             return true;
115         }
116
117         return false;
118     }
119
120     /**
121      * Increments the value of the follower's match index.
122      *
123      * @return the new value of matchIndex.
124      */
125     public long incrMatchIndex() {
126         return matchIndex++;
127     }
128
129     /**
130      * Sets the index of the follower's highest log entry.
131      *
132      * @param matchIndex the new index.
133      * @return true if the new index differed from the current index and the current index was updated, false
134      *              otherwise.
135      */
136     @SuppressWarnings("checkstyle:hiddenField")
137     public boolean setMatchIndex(final long matchIndex) {
138         // If the new match index is the index of the entry currently being sliced, then we know slicing is complete
139         // and the follower received the entry and responded so clear the slicedLogEntryIndex
140         if (isLogEntrySlicingInProgress() && slicedLogEntryIndex == matchIndex) {
141             slicedLogEntryIndex = NO_INDEX;
142         }
143
144         if (this.matchIndex != matchIndex) {
145             this.matchIndex = matchIndex;
146             return true;
147         }
148
149         return false;
150     }
151
152     /**
153      * Returns the identifier of the follower.
154      *
155      * @return the identifier of the follower.
156      */
157     public String getId() {
158         return peerInfo.getId();
159     }
160
161     /**
162      * Returns the index of the next log entry to send to the follower.
163      *
164      * @return index of the follower's next log entry.
165      */
166     public long getNextIndex() {
167         return nextIndex;
168     }
169
170     /**
171      * Returns the index of highest log entry known to be replicated on the follower.
172      *
173      * @return the index of highest log entry.
174      */
175     public long getMatchIndex() {
176         return matchIndex;
177     }
178
179     /**
180      * Checks if the follower is active by comparing the time of the last activity with the election time out. The
181      * follower is active if some activity has occurred for the follower within the election time out interval.
182      *
183      * @return true if follower is active, false otherwise.
184      */
185     public boolean isFollowerActive() {
186         if (peerInfo.getVotingState() == VotingState.VOTING_NOT_INITIALIZED) {
187             return false;
188         }
189
190         long elapsed = stopwatch.elapsed(TimeUnit.MILLISECONDS);
191         return stopwatch.isRunning()
192                 && elapsed <= context.getConfigParams().getElectionTimeOutInterval().toMillis();
193     }
194
195     /**
196      * Marks the follower as active. This should be called when some activity has occurred for the follower.
197      */
198     public void markFollowerActive() {
199         if (stopwatch.isRunning()) {
200             stopwatch.reset();
201         }
202         stopwatch.start();
203     }
204
205     /**
206      * Marks the follower as inactive. This should only be called from unit tests.
207      */
208     @VisibleForTesting
209     public void markFollowerInActive() {
210         if (stopwatch.isRunning()) {
211             stopwatch.stop();
212         }
213     }
214
215     /**
216      * Returns the time since the last activity occurred for the follower.
217      *
218      * @return time in milliseconds since the last activity from the follower.
219      */
220     public long timeSinceLastActivity() {
221         return stopwatch.elapsed(TimeUnit.MILLISECONDS);
222     }
223
224     /**
225      * This method checks if the next replicate message can be sent to the follower. This is an optimization to avoid
226      * sending duplicate message too frequently if the last replicate message was sent and no reply has been received
227      * yet within the current heart beat interval
228      *
229      * @return true if it is OK to replicate, false otherwise
230      */
231     public boolean okToReplicate() {
232         if (peerInfo.getVotingState() == VotingState.VOTING_NOT_INITIALIZED) {
233             return false;
234         }
235
236         // Return false if we are trying to send duplicate data before the heartbeat interval
237         if (getNextIndex() == lastReplicatedIndex && lastReplicatedStopwatch.elapsed(TimeUnit.MILLISECONDS)
238                 < context.getConfigParams().getHeartBeatInterval().toMillis()) {
239             return false;
240         }
241
242         resetLastReplicated();
243         return true;
244     }
245
246     private void resetLastReplicated() {
247         lastReplicatedIndex = getNextIndex();
248         if (lastReplicatedStopwatch.isRunning()) {
249             lastReplicatedStopwatch.reset();
250         }
251         lastReplicatedStopwatch.start();
252     }
253
254     /**
255      * Returns the log entry payload data version of the follower.
256      *
257      * @return the payload data version.
258      */
259     public short getPayloadVersion() {
260         return payloadVersion;
261     }
262
263     /**
264      * Sets the payload data version of the follower.
265      *
266      * @param payloadVersion the payload data version.
267      */
268     public void setPayloadVersion(final short payloadVersion) {
269         this.payloadVersion = payloadVersion;
270     }
271
272     /**
273      * Returns the the raft version of the follower.
274      *
275      * @return the raft version of the follower.
276      */
277     public short getRaftVersion() {
278         return raftVersion;
279     }
280
281     /**
282      * Sets the raft version of the follower.
283      *
284      * @param raftVersion the raft version.
285      */
286     public void setRaftVersion(final short raftVersion) {
287         this.raftVersion = raftVersion;
288     }
289
290     /**
291      * Returns the LeaderInstallSnapshotState for the in progress install snapshot.
292      *
293      * @return the LeaderInstallSnapshotState if a snapshot install is in progress, null otherwise.
294      */
295     @Nullable
296     public LeaderInstallSnapshotState getInstallSnapshotState() {
297         return installSnapshotState;
298     }
299
300     /**
301      * Sets the LeaderInstallSnapshotState when an install snapshot is initiated.
302      *
303      * @param state the LeaderInstallSnapshotState
304      */
305     public void setLeaderInstallSnapshotState(@Nonnull final LeaderInstallSnapshotState state) {
306         if (this.installSnapshotState == null) {
307             this.installSnapshotState = Preconditions.checkNotNull(state);
308         }
309     }
310
311     /**
312      * Clears the LeaderInstallSnapshotState when an install snapshot is complete.
313      */
314     public void clearLeaderInstallSnapshotState() {
315         Preconditions.checkState(installSnapshotState != null);
316         installSnapshotState.close();
317         installSnapshotState = null;
318     }
319
320     /**
321      * Sets the index of the log entry whose payload size exceeds the maximum size for a single message and thus
322      * needs to be sliced into smaller chunks.
323      *
324      * @param index the log entry index or NO_INDEX to clear it
325      */
326     public void setSlicedLogEntryIndex(final long index) {
327         slicedLogEntryIndex  = index;
328     }
329
330     /**
331      * Return whether or not log entry slicing is currently in progress.
332      *
333      * @return true if slicing is currently in progress, false otherwise
334      */
335     public boolean isLogEntrySlicingInProgress() {
336         return slicedLogEntryIndex != NO_INDEX;
337     }
338
339     @Override
340     public String toString() {
341         return "FollowerLogInformation [id=" + getId() + ", nextIndex=" + nextIndex + ", matchIndex=" + matchIndex
342                 + ", lastReplicatedIndex=" + lastReplicatedIndex + ", votingState=" + peerInfo.getVotingState()
343                 + ", stopwatch=" + stopwatch.elapsed(TimeUnit.MILLISECONDS) + ", followerTimeoutMillis="
344                 + context.getConfigParams().getElectionTimeOutInterval().toMillis() + "]";
345     }
346 }