summaryrefslogtreecommitdiff
path: root/src/main/java/protocols/implementations/VSRaftProtocol.java
blob: d0066e0d793b032f9e52f3afb3d2295c2f1ef54f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
package protocols.implementations;

import java.util.ArrayList;
import java.util.Vector;

import core.VSInternalProcess;
import core.VSMessage;
import protocols.VSAbstractProtocol;

/**
 * The class VSRaftProtocol, a skeleton for a Raft-based protocol.
 *
 * @author Paul C. Buetow
 */
public class VSRaftProtocol extends VSAbstractProtocol {
    /** The current Raft term. */
    private int currentTerm;

    /** The PID voted for in the current term. */
    private int votedFor;

    /** The number of votes received while acting as a candidate. */
    private int votesReceived;

    /** The current leader PID. */
    private int leaderId;

    /** True if this process currently acts as the leader. */
    private boolean isLeader;

    /** True if this process currently acts as a candidate. */
    private boolean isCandidate;

    /** The local time when the last heartbeat was observed. */
    private long lastHeartbeatTime;

    /** The randomized local deadline for the next election timeout. */
    private long electionDeadline;

    /** PIDs which still have to acknowledge the current operation. */
    private ArrayList<Integer> ackPids;

    /** Peer PIDs whose vote responses have been counted in this election. */
    private ArrayList<Integer> voteResponsePids;

    /** The local log index. */
    private int logIndex;

    /** The last committed log index. */
    private int commitIndex;

    /**
     * Instantiates a new Raft protocol skeleton.
     */
    public VSRaftProtocol() {
        super(VSAbstractProtocol.HAS_ON_SERVER_START);
        setClassname(getClass().toString());
        resetState();
    }

    /* (non-Javadoc)
     * @see events.VSAbstractProtocol#onServerInit()
     */
    public void onServerInit() {
        Vector<Integer> vec = new Vector<Integer>();
        vec.add(2);
        vec.add(3);

        initVector("pids", vec, "PIDs of participating follower processes");
        initLong("heartbeatInterval", 1500, "Heartbeat interval", "ms");
        initString("logEntry", "cmd1", "Log entry to replicate");
    }

    /* (non-Javadoc)
     * @see events.VSAbstractProtocol#onClientInit()
     */
    public void onClientInit() {
        initLong("electionTimeout", 4000, "Base election timeout", "ms");
        initLong("electionJitter", 2000, "Election timeout jitter", "ms");
        resetElectionTimeout();
    }

    /* (non-Javadoc)
     * @see protocols.VSAbstractProtocol#onServerStart()
     */
    public void onServerStart() {
        becomeLeader();
    }

    /* (non-Javadoc)
     * @see protocols.VSAbstractProtocol#onServerRecv(core.VSMessage)
     */
    public void onServerRecv(VSMessage recvMessage) {
        handleMessage(recvMessage);
    }

    /* (non-Javadoc)
     * @see protocols.VSAbstractProtocol#onClientRecv(core.VSMessage)
     */
    public void onClientRecv(VSMessage recvMessage) {
        handleMessage(recvMessage);
    }

    /* (non-Javadoc)
     * @see protocols.VSAbstractProtocol#onServerSchedule()
     */
    public void onServerSchedule() {
        if (isLeader) {
            sendHeartbeat();
        }
    }

    /* (non-Javadoc)
     * @see protocols.VSAbstractProtocol#onClientSchedule()
     */
    public void onClientSchedule() {
        long currentTime = process.getTime();

        if (!isLeader && currentTime >= electionDeadline) {
            startElection();
        }
    }

    /* (non-Javadoc)
     * @see protocols.VSAbstractProtocol#onServerReset()
     */
    public void onServerReset() {
        resetState();
    }

    /* (non-Javadoc)
     * @see protocols.VSAbstractProtocol#onClientReset()
     */
    public void onClientReset() {
        resetState();
    }

    /**
     * Resets the shared Raft state to its initial values.
     */
    private void resetState() {
        currentTerm = 0;
        votedFor = -1;
        votesReceived = 0;
        leaderId = -1;
        isLeader = false;
        isCandidate = false;
        lastHeartbeatTime = 0;
        electionDeadline = 0;
        logIndex = 0;
        commitIndex = 0;

        if (ackPids == null) {
            ackPids = new ArrayList<Integer>();
        } else {
            ackPids.clear();
        }

        if (voteResponsePids == null) {
            voteResponsePids = new ArrayList<Integer>();
        } else {
            voteResponsePids.clear();
        }
    }

    /**
     * Transitions this process into the leader role and starts heartbeats.
     */
    private void becomeLeader() {
        isLeader = true;
        isCandidate = false;
        votesReceived = 0;
        voteResponsePids.clear();
        ackPids.clear();
        leaderId = process.getProcessID();
        lastHeartbeatTime = process.getTime();
        isServer(true);

        if (!getLongKeySet().contains("heartbeatInterval")) {
            onServerInit();
        }

        boolean previousContextIsServer = currentContextIsServer();

        currentContextIsServer(false);
        removeSchedules();

        currentContextIsServer(true);
        sendHeartbeat();
        sendAppendEntry();
        currentContextIsServer(previousContextIsServer);
    }

    /**
     * Transitions this process into the follower role for the supplied term.
     *
     * @param term the term to adopt
     * @param newLeaderId the known leader in that term, or -1 if unknown
     */
    private void becomeFollower(int term, int newLeaderId) {
        clearServerSchedules();
        isLeader = false;
        isCandidate = false;
        currentTerm = term;
        leaderId = newLeaderId;
        votedFor = -1;
        votesReceived = 0;
        voteResponsePids.clear();
        resetElectionTimeout();
    }

    /**
     * Resets the follower election timeout using a randomized client schedule.
     */
    private void resetElectionTimeout() {
        long jitterPercentage = Math.abs(process.getRandomPercentage());
        long jitter = (getLong("electionJitter") * jitterPercentage) / 100L;
        boolean previousContextIsServer = currentContextIsServer();
        electionDeadline = process.getTime() + getLong("electionTimeout") + jitter;

        currentContextIsServer(false);
        removeSchedules();
        scheduleAt(electionDeadline);
        currentContextIsServer(previousContextIsServer);
    }

    /**
     * Clears any active server-side schedules while preserving the caller
     * context.
     */
    private void clearServerSchedules() {
        boolean previousContextIsServer = currentContextIsServer();

        currentContextIsServer(true);
        removeSchedules();
        currentContextIsServer(previousContextIsServer);
    }

    /**
     * Starts a new election and re-arms the candidate timeout.
     */
    private void startElection() {
        currentTerm++;
        votedFor = process.getProcessID();
        votesReceived = 1;
        voteResponsePids.clear();
        isLeader = false;
        isCandidate = true;
        leaderId = -1;
        lastHeartbeatTime = process.getTime();
        isServer(true);

        VSMessage voteRequest = new VSMessage();
        voteRequest.setString("type", "voteRequest");
        voteRequest.setInteger("term", currentTerm);
        voteRequest.setInteger("candidateId", process.getProcessID());
        sendMessage(voteRequest);

        resetElectionTimeout();
    }

    /**
     * Sends a heartbeat and schedules the next leader heartbeat interval.
     */
    private void sendHeartbeat() {
        VSMessage heartbeat = new VSMessage();
        heartbeat.setString("type", "heartbeat");
        heartbeat.setInteger("term", currentTerm);
        heartbeat.setInteger("leaderId", leaderId);
        sendMessage(heartbeat);

        lastHeartbeatTime = process.getTime();
        scheduleAt(process.getTime() + getLong("heartbeatInterval"));
    }

    /**
     * Sends a simplified append-entry request for the configured log entry.
     */
    private void sendAppendEntry() {
        ackPids.clear();

        if (getVectorKeySet().contains("pids")) {
            ackPids.addAll(getVector("pids"));
        }

        if (ackPids.isEmpty()) {
            return;
        }

        logIndex++;

        VSMessage appendEntry = new VSMessage();
        appendEntry.setString("type", "appendEntry");
        appendEntry.setInteger("term", currentTerm);
        appendEntry.setInteger("leaderId", leaderId);
        appendEntry.setString("entry", getString("logEntry"));
        appendEntry.setInteger("logIndex", logIndex);
        sendMessage(appendEntry);
    }

    /**
     * Dispatches Raft messages to the relevant handlers.
     *
     * @param recvMessage the received message
     */
    private void handleMessage(VSMessage recvMessage) {
        String messageType = recvMessage.getString("type");

        if ("voteRequest".equals(messageType)) {
            handleVoteRequest(recvMessage);
        } else if ("voteResponse".equals(messageType)) {
            handleVoteResponse(recvMessage);
        } else if ("appendEntry".equals(messageType)) {
            handleAppendEntry(recvMessage);
        } else if ("appendAck".equals(messageType)) {
            handleAppendAck(recvMessage);
        }
    }

    /**
     * Handles an incoming vote request from a candidate.
     *
     * @param recvMessage the vote request
     */
    private void handleVoteRequest(VSMessage recvMessage) {
        int messageTerm = recvMessage.getInteger("term");
        int candidateId = recvMessage.getInteger("candidateId");
        boolean voteGranted = false;

        if (messageTerm > currentTerm) {
            becomeFollower(messageTerm, -1);
        }

        if (messageTerm == currentTerm &&
                (votedFor == -1 || votedFor == candidateId)) {
            votedFor = candidateId;
            voteGranted = true;
        }

        VSMessage voteResponse = new VSMessage();
        voteResponse.setString("type", "voteResponse");
        voteResponse.setInteger("term", currentTerm);
        voteResponse.setInteger("pid", process.getProcessID());
        voteResponse.setBoolean("voteGranted", voteGranted);
        voteResponse.setInteger("targetPid", candidateId);
        sendMessage(voteResponse);
    }

    /**
     * Handles an incoming vote response for an active election.
     *
     * @param recvMessage the vote response
     */
    private void handleVoteResponse(VSMessage recvMessage) {
        int messageTerm = recvMessage.getInteger("term");
        Integer responderPid = recvMessage.getIntegerObj("pid");

        if (messageTerm > currentTerm) {
            becomeFollower(messageTerm, -1);
            return;
        }

        if (!isCandidate || !isForMe(recvMessage) ||
                !recvMessage.getBoolean("voteGranted") ||
                messageTerm != currentTerm ||
                voteResponsePids.contains(responderPid)) {
            return;
        }

        voteResponsePids.add(responderPid);
        votesReceived++;

        if (votesReceived > getClusterSize() / 2) {
            becomeLeader();
        }
    }

    /**
     * Handles an incoming append-entry request from the current leader.
     *
     * @param recvMessage the append-entry message
     */
    private void handleAppendEntry(VSMessage recvMessage) {
        int messageTerm = recvMessage.getInteger("term");
        int messageLeaderId = recvMessage.getInteger("leaderId");
        int messageLogIndex = recvMessage.getInteger("logIndex");

        if (messageTerm > currentTerm) {
            becomeFollower(messageTerm, messageLeaderId);
        } else {
            return;
        }

        if (messageLogIndex != logIndex + 1) {
            return;
        }

        if (messageTerm == currentTerm) {
            leaderId = messageLeaderId;
            isLeader = false;
            isCandidate = false;
            resetElectionTimeout();
        }

        logIndex = messageLogIndex;

        VSMessage appendAck = new VSMessage();
        appendAck.setString("type", "appendAck");
        appendAck.setInteger("term", currentTerm);
        appendAck.setInteger("pid", process.getProcessID());
        appendAck.setInteger("logIndex", messageLogIndex);
        appendAck.setInteger("targetPid", messageLeaderId);
        sendMessage(appendAck);
    }

    /**
     * Handles an append-entry acknowledgement on the leader.
     *
     * @param recvMessage the append acknowledgement
     */
    private void handleAppendAck(VSMessage recvMessage) {
        int messageTerm = recvMessage.getInteger("term");
        Integer responderPid = recvMessage.getIntegerObj("pid");
        int ackLogIndex = recvMessage.getInteger("logIndex");

        if (messageTerm > currentTerm) {
            becomeFollower(messageTerm, -1);
            return;
        }

        if (!isLeader || !isForMe(recvMessage) || responderPid == null ||
                messageTerm != currentTerm || ackLogIndex != logIndex ||
                !ackPids.contains(responderPid)) {
            return;
        }

        ackPids.remove(responderPid);

        if (ackPids.isEmpty() && commitIndex < ackLogIndex) {
            commitIndex = ackLogIndex;
            log("Committed log index " + commitIndex);
        }
    }

    /**
     * Checks whether a directed response is meant for this process.
     *
     * @param recvMessage the received message
     * @return true if the message targets this process or has no target field
     */
    private boolean isForMe(VSMessage recvMessage) {
        if (!recvMessage.getIntegerKeySet().contains("targetPid")) {
            return true;
        }

        return recvMessage.getInteger("targetPid") == process.getProcessID();
    }

    /**
     * Determines the cluster size used for majority calculations.
     *
     * @return the number of processes participating in the election
     */
    private int getClusterSize() {
        VSInternalProcess internalProcess = (VSInternalProcess) process;
        int numProcesses = internalProcess.getSimulatorCanvas().getNumProcesses();

        if (numProcesses > 0) {
            return numProcesses;
        }

        if (getVectorKeySet().contains("pids")) {
            return getVector("pids").size() + 1;
        }

        return 1;
    }
}