40 lines
1.8 KiB
Python
40 lines
1.8 KiB
Python
import MyRaft.state as state
|
|
import MyRaft.candidate as candidate
|
|
import MyRaft.raft_pb2 as raft_pb2
|
|
|
|
class Follower(state.State):
|
|
def __init__(self, context):
|
|
state.State.__init__(self, context)
|
|
self._context.set_timeout(self._context._min_timout, self._context._vary_timeout)
|
|
|
|
def heartbeat_elapsed(self):
|
|
print("Becoming a candidate")
|
|
self._context.set_state(candidate.Candidate(self._context))
|
|
|
|
def rcv_AppendEntries(self, request):
|
|
"""Called when an append entries message is received"""
|
|
|
|
self._context.set_timeout(self._context._min_timout, self._context._vary_timeout)
|
|
|
|
def rcv_RequestVote(self, request):
|
|
print("Received a vote request")
|
|
# Ignoring log for now.
|
|
if request.term < self._context.currentTerm:
|
|
print("They're term is worse than ours.")
|
|
# If our current term is already the same, then we must have voted already.
|
|
return raft_pb2.RequestVoteResponse(term = self._context.currentTerm, voteGranted = False)
|
|
elif request.term == self._context.currentTerm and self._context.votedFor is not None:
|
|
return raft_pb2.RequestVoteResponse(term = self._context.currentTerm, voteGranted = False)
|
|
else:
|
|
print("We'll be voting for them!")
|
|
# We vote yes, so reset our timeout.
|
|
self._context.set_timeout(self._context._min_timout, self._context._vary_timeout)
|
|
self._context.currentTerm = request.term
|
|
print("setting candidate id")
|
|
self._context.votedFor = request.candidateId
|
|
print("Returning result.")
|
|
return raft_pb2.RequestVoteResponse(term = self._context.currentTerm,
|
|
voteGranted = True,
|
|
voterId = self._context._id)
|
|
|