import threading
import time
import random
import queue
import logging
from enum import Enum, auto
from dataclasses import dataclass
from typing import List, Optional, Dict
# --- Configuration ---
# Configure logging to see what is happening
logging.basicConfig(level=logging.INFO, format='[%(threadName)s] %(message)s')
# --- Data Structures ---
class State(Enum):
FOLLOWER = auto()
CANDIDATE = auto()
LEADER = auto()
@dataclass
class LogEntry:
term: int
command: str
# RPC Payloads
@dataclass
class RequestVote:
term: int
candidate_id: int
last_log_index: int
last_log_term: int
@dataclass
class RequestVoteResponse:
term: int
vote_granted: bool
@dataclass
class AppendEntries:
term: int
leader_id: int
prev_log_index: int
prev_log_term: int
entries: List[LogEntry]
leader_commit: int
@dataclass
class AppendEntriesResponse:
term: int
success: bool
# --- The Node (The Core Logic) ---
class Node(threading.Thread):
def __init__(self, node_id: int, network: Dict[int, queue.Queue], cluster_size: int):
super().__init__()
self.node_id = node_id
self.network = network # Map of node_id -> message queue
self.cluster_size = cluster_size
# Inbox for this node
self.inbox = queue.Queue()
self.network[self.node_id] = self.inbox
# Persistent State (on all servers)
self.current_term = 0
self.voted_for: Optional[int] = None
self.log: List[LogEntry] = [] # Index 0 is dummy/placeholder for simplicity in 1-based indexing logic
# Volatile State
self.commit_index = 0
self.last_applied = 0
self.state = State.FOLLOWER
# Leader Volatile State (reinitialized after election)
self.next_index: Dict[int, int] = {}
self.match_index: Dict[int, int] = {}
# Timers
self.last_heartbeat = time.time()
self.election_timeout = random.uniform(1.5, 3.0) # Randomized timeout
self.running = True
self.lock = threading.Lock() # Protect shared state
def run(self):
logging.info(f"Node {self.node_id} started.")
while self.running:
# 1. Check for Election Timeout (if Follower or Candidate)
if self.state != State.LEADER:
if time.time() - self.last_heartbeat > self.election_timeout:
self.start_election()
# 2. Process Messages (Non-blocking)
try:
msg = self.inbox.get(timeout=0.1)
self.handle_message(msg)
except queue.Empty:
continue
# 3. Leader Duties: Send Heartbeats / Replicate Logs
if self.state == State.LEADER:
# We send heartbeats roughly every 0.5s
# In a real impl, this would be a separate timer event
time.sleep(0.5)
self.send_heartbeats()
def stop(self):
self.running = False
# --- RPC Handlers ---
def handle_message(self, msg):
# Generic router for incoming RPCs
sender_id, payload = msg
if isinstance(payload, RequestVote):
self.handle_request_vote(sender_id, payload)
elif isinstance(payload, RequestVoteResponse):
self.handle_request_vote_response(sender_id, payload)
elif isinstance(payload, AppendEntries):
self.handle_append_entries(sender_id, payload)
elif isinstance(payload, AppendEntriesResponse):
self.handle_append_entries_response(sender_id, payload)
def send_message(self, target_id, payload):
# Simulate network delay
time.sleep(random.uniform(0.01, 0.05))
if target_id in self.network:
self.network[target_id].put((self.node_id, payload))
# --- ELECTION LOGIC ---
def start_election(self):
with self.lock:
self.state = State.CANDIDATE
self.current_term += 1
self.voted_for = self.node_id
self.last_heartbeat = time.time() # Reset timer
self.election_timeout = random.uniform(1.5, 3.0) # New timeout
logging.info(f"Election started! Term {self.current_term}")
# Prepare RequestVote args
last_log_idx = len(self.log)
last_log_term = self.log[-1].term if self.log else 0
payload = RequestVote(
term=self.current_term,
candidate_id=self.node_id,
last_log_index=last_log_idx,
last_log_term=last_log_term
)
# Send RequestVote to all peers
for peer_id in self.network:
if peer_id != self.node_id:
self.send_message(peer_id, payload)
# Note: We track votes inside the response handler
# For simplicity in this demo, we reset voted count here or keep track in handler
# We will count votes in handle_request_vote_response
def handle_request_vote(self, sender_id, rv: RequestVote):
with self.lock:
# 1. Reply false if term < currentTerm
if rv.term < self.current_term:
self.send_message(sender_id, RequestVoteResponse(self.current_term, False))
return
# 2. If RPC request or response contains term T > currentTerm:
# set currentTerm = T, convert to follower
if rv.term > self.current_term:
self.current_term = rv.term
self.state = State.FOLLOWER
self.voted_for = None
# 3. If votedFor is null or candidateId, and candidate’s log is at least as up-to-date as receiver’s log, grant vote
if (self.voted_for is None or self.voted_for == rv.candidate_id):
# Log comparison logic omitted for brevity in demo, assume simple check
# Real Raft checks: rv.last_log_term >= self.log[-1].term etc.
self.voted_for = rv.candidate_id
self.last_heartbeat = time.time() # Important: reset timer to prevent immediate coup
self.send_message(sender_id, RequestVoteResponse(self.current_term, True))
return
self.send_message(sender_id, RequestVoteResponse(self.current_term, False))
def handle_request_vote_response(self, sender_id, rv: RequestVoteResponse):
with self.lock:
# Ignore old responses
if rv.term != self.current_term:
return
if rv.vote_granted:
logging.info(f"Received VOTE from Node {sender_id}")
# Check if we have majority
# In a real system, we need a counter variable.
# Here we simulate counting. Majority = (ClusterSize / 2) + 1
# Since we only track states, winning implies becoming Leader.
# For this demo, if we get ANY vote back while Candidate, we assume we might win
# (Simplified: Real Raft counts strictly).
# Let's assume strict majority needed:
# We don't have a vote counter variable in this simplified class,
# so let's say if we have 3 nodes, 1 self vote + 1 other = 2 (Majority).
# We transition to Leader immediately upon getting enough votes logic usually.
pass
else:
# Discovered higher term
if rv.term > self.current_term:
self.current_term = rv.term
self.state = State.FOLLOWER
self.voted_for = None
# Simplified Winning Logic: If we are candidate and got a vote, we just assume we are leader
# for this very small cluster (Size 3). 2 votes = Majority.
# In reality, you count votes.
if self.state == State.CANDIDATE:
# In a cluster of 3, getting 1 response (plus self vote) is majority
self.become_leader()
def become_leader(self):
with self.lock:
if self.state != State.LEADER:
logging.info(f"*** I AM THE LEADER! Term {self.current_term} ***")
self.state = State.LEADER
# Reinitialize leader state
for peer_id in self.network:
self.next_index[peer_id] = len(self.log) + 1
self.match_index[peer_id] = 0
# Force immediate heartbeat
self.last_heartbeat = 0
# --- LOG REPLICATION & HEARTBEATS ---
def send_heartbeats(self):
# Only leader runs this
if self.state != State.LEADER: return
with self.lock:
for peer_id in self.network:
if peer_id == self.node_id: continue
# Simple Heartbeat (Empty AppendEntries)
# In real Raft, we use next_index to send actual log entries
payload = AppendEntries(
term=self.current_term,
leader_id=self.node_id,
prev_log_index=len(self.log),
prev_log_term=self.log[-1].term if self.log else 0,
entries=[], # Empty for heartbeat
leader_commit=self.commit_index
)
self.send_message(peer_id, payload)
def handle_append_entries(self, sender_id, ae: AppendEntries):
with self.lock:
# 1. Reply false if term < currentTerm
if ae.term < self.current_term:
self.send_message(sender_id, AppendEntriesResponse(self.current_term, False))
return
# 2. If term > currentTerm, step down
if ae.term > self.current_term:
self.current_term = ae.term
self.voted_for = None
self.state = State.FOLLOWER
self.last_heartbeat = time.time() # Reset election timer
# 3. Log matching check (Simplified)
# If we have a conflict or missing entries, fail.
# For this demo, we just accept the heartbeat logic.
# Real implementation would check prev_log_index/term and append entries...
self.send_message(sender_id, AppendEntriesResponse(self.current_term, True))
def handle_append_entries_response(self, sender_id, ae: AppendEntriesResponse):
with self.lock:
if ae.term > self.current_term:
self.current_term = ae.term
self.state = State.FOLLOWER
return
if self.state == State.LEADER and ae.success:
# Update match_index/next_index for follower
pass
elif self.state == State.LEADER and not ae.success:
# Decrement next_index and retry...
pass
# --- Simulation Runner ---
def simulate_cluster():
cluster_size = 3
network_queues = {} # Shared message bus
nodes = []
for i in range(cluster_size):
node = Node(i, network_queues, cluster_size)
nodes.append(node)
node.start()
# Let them run for a bit
time.sleep(2)
# Simulate Leader Failure
logging.info("\n!!! SIMULATING LEADER FAILURE (Killing Node) !!!\n")
leader_killed = False
for node in nodes:
if node.state == State.LEADER:
node.stop()
node.join()
nodes.remove(node)
leader_killed = True
break
if not leader_killed:
logging.info("No leader found to kill (Election might be in progress).")
# Let remaining nodes elect new leader
time.sleep(3)
# Clean up
for node in nodes:
node.stop()
node.join()
if __name__ == "__main__":
simulate_cluster()