Bibliothèque Lua pour algorithmes de consensus simplifiés type Raft light, adaptée aux systèmes embarqués avec ressources limitées et communication JSON.
-- Bibliothèque Lua pour algorithme de consensus simplifié type Raft light
-- Auteur : Senior Software Engineer
-- Description : implémente élection du leader, réplication du journal et gestion de l'état du nœud
local socket = require("socket") -- LuaSocket pour communication
local json = require("json") -- Bibliothèque JSON pour sérialisation
local Raft = {}
-- Constantes de rôle
local ROLE_FOLLOWER = "follower"
local ROLE_CANDIDATE = "candidate"
local ROLE_LEADER = "leader"
-- Configuration par défaut
local DEFAULT_ELECTION_TIMEOUT_MIN = 1500 -- ms
local DEFAULT_ELECTION_TIMEOUT_MAX = 3000 -- ms
local DEFAULT_HEARTBEAT_INTERVAL = 500 -- ms
-- Fonction auxiliaire pour générer un timeout aléatoire entre min et max
local function random_timeout(min, max)
return math.random(min, max)
end
-- Nœud Raft
local Node = {}
Node.__index = Node
function Node:new(config)
-- Configuration du nœud
local o = {
id = config.id, -- ID du nœud local
peers = config.peers, -- table {id -> {host, port}}
currentTerm = 0,
votedFor = nil,
log = {}, -- tableau de commandes {term, command}
commitIndex = 0,
lastApplied = 0,
state = ROLE_FOLLOWER,
votesReceived = {},
electionTimeout = random_timeout(DEFAULT_ELECTION_TIMEOUT_MIN, DEFAULT_ELECTION_TIMEOUT_MAX),
heartbeatInterval = DEFAULT_HEARTBEAT_INTERVAL,
electionTimer = nil,
heartbeatTimer = nil,
socket = nil,
lastHeartbeat = socket.gettime(),
callbacks = {
onCommit = config.onCommit or function() end,
sendMessage = config.sendMessage or function() end
}
}
setmetatable(o, self)
return o
end
-- Initialise le socket UDP pour la communication
function Node:initSocket()
local udp = socket.udp()
udp:settimeout(0) -- non bloquant
udp:setsockname("*", self.peers[self.id].port)
self.socket = udp
end
-- Envoie un message JSON à un pair
function Node:send(toId, message)
local peer = self.peers[toId]
if not peer then return end
local msgStr = json.encode(message)
self.socket:sendto(msgStr, peer.host, peer.port)
end
-- Diffuse un message à tous les pairs sauf soi-même
function Node:broadcast(message)
for peerId, _ in pairs(self.peers) do
if peerId ~= self.id then
self:send(peerId, message)
end
end
end
-- Réinitialise le timer d'élection
function Node:resetElectionTimer()
self.electionTimeout = random_timeout(DEFAULT_ELECTION_TIMEOUT_MIN, DEFAULT_ELECTION_TIMEOUT_MAX)
self.electionTimer = socket.gettime() + self.electionTimeout / 1000
end
-- Réinitialise le timer de battement de cœur
function Node:resetHeartbeatTimer()
self.heartbeatTimer = socket.gettime() + self.heartbeatInterval / 1000
end
-- Gestion du message RequestVote RPC
function Node:onRequestVote(msg, fromId)
local granted = false
if msg.term < self.currentTerm then
granted = false
else
if msg.term > self.currentTerm then
self.currentTerm = msg.term
self.votedFor = nil
self.state = ROLE_FOLLOWER
end
if (self.votedFor == nil or self.votedFor == fromId) and
(msg.lastLogTerm > (self.log[#self.log] and self.log[#self.log].term or 0) or
(msg.lastLogTerm == (self.log[#self.log] and self.log[#self.log].term or 0) and msg.lastLogIndex >= #self.log)) then
granted = true
self.votedFor = fromId
self:resetElectionTimer()
end
end
local reply = {
type = "RequestVoteResponse",
term = self.currentTerm,
voteGranted = granted
}
self:send(fromId, reply)
end
-- Gestion du message AppendEntries RPC (battement de cœur ou réplication)
function Node:onAppendEntries(msg, fromId)
if msg.term < self.currentTerm then
local reply = {type = "AppendEntriesResponse", term = self.currentTerm, success = false}
self:send(fromId, reply)
return
end
self.currentTerm = msg.term
self.state = ROLE_FOLLOWER
self.votedFor = nil
self:resetElectionTimer()
-- Vérifie la correspondance du journal
local prevLogIndex = msg.prevLogIndex
local prevLogTerm = msg.prevLogTerm
if prevLogIndex > 0 then
if not self.log[prevLogIndex] or self.log[prevLogIndex].term ~= prevLogTerm then
local reply = {type = "AppendEntriesResponse", term = self.currentTerm, success = false}
self:send(fromId, reply)
return
end
end
-- Ajoute les nouvelles entrées
for i, entry in ipairs(msg.entries) do
local idx = prevLogIndex + i
if self.log[idx] and self.log[idx].term ~= entry.term then
-- tronque le journal divergent
for j = #self.log, idx, -1 do
table.remove(self.log, j)
end
end
if not self.log[idx] then
self.log[idx] = entry
end
end
-- Met à jour commitIndex
if msg.leaderCommit > self.commitIndex then
self.commitIndex = math.min(msg.leaderCommit, #self.log)
self:applyLogEntries()
end
local reply = {type = "AppendEntriesResponse", term = self.currentTerm, success = true}
self:send(fromId, reply)
end
-- Applique les commandes du journal jusqu'à commitIndex
function Node:applyLogEntries()
while self.lastApplied < self.commitIndex do
self.lastApplied = self.lastApplied + 1
local entry = self.log[self.lastApplied]
if entry then
self.callbacks.onCommit(entry.command)
end
end
end
-- Démarre une élection
function Node:startElection()
self.state = ROLE_CANDIDATE
self.currentTerm = self.currentTerm + 1
self.votedFor = self.id
self.votesReceived = {[self.id] = true}
self:resetElectionTimer()
local lastLogIndex = #self.log
local lastLogTerm = (lastLogIndex > 0) and self.log[lastLogIndex].term or 0
local msg = {
type = "RequestVote",
term = self.currentTerm,
candidateId = self.id,
lastLogIndex = lastLogIndex,
lastLogTerm = lastLogTerm
}
self:broadcast(msg)
end
-- Gestion des messages entrants
function Node:handleMessage(msgStr, fromHost, fromPort)
local msg = json.decode(msgStr)
if not msg or not msg.type then return end
local fromId = nil
for id, peer in pairs(self.peers) do
if peer.host == fromHost and peer.port == fromPort then
fromId = id
break
end
end
if not fromId then return end
if msg.type == "RequestVote" then
self:onRequestVote(msg, fromId)
elseif msg.type == "RequestVoteResponse" then
if self.state == ROLE_CANDIDATE and msg.term == self.currentTerm and msg.voteGranted then
self.votesReceived[fromId] = true
local votesCount = 0
for _ in pairs(self.votesReceived) do votesCount = votesCount + 1 end
if votesCount > (#self.peers // 2) then
self.state = ROLE_LEADER
self:resetHeartbeatTimer()
end
elseif msg.term > self.currentTerm then
self.currentTerm = msg.term
self.state = ROLE_FOLLOWER
self.votedFor = nil
self:resetElectionTimer()
end
elseif msg.type == "AppendEntries" then
self:onAppendEntries(msg, fromId)
elseif msg.type == "AppendEntriesResponse" then
-- Pour simplifier, la réplication avancée n'est pas gérée
if msg.term > self.currentTerm then
self.currentTerm = msg.term
self.state = ROLE_FOLLOWER
self.votedFor = nil
self:resetElectionTimer()
end
end
end
-- Fonction à appeler périodiquement pour gérer les timers et envoyer les battements de cœur
function Node:tick()
local now = socket.gettime()
-- Réception des messages
while true do
local msgStr, ip, port = self.socket:receivefrom()
if not msgStr then break end
self:handleMessage(msgStr, ip, port)
end
-- Gestion du timeout d'élection
if self.state ~= ROLE_LEADER and now >= self.electionTimer then
self:startElection()
end
-- Gestion du battement de cœur
if self.state == ROLE_LEADER and now >= self.heartbeatTimer then
local msg = {
type = "AppendEntries",
term = self.currentTerm,
leaderId = self.id,
prevLogIndex = #self.log,
prevLogTerm = (#self.log > 0) and self.log[#self.log].term or 0,
entries = {}, -- battement de cœur vide
leaderCommit = self.commitIndex
}
self:broadcast(msg)
self:resetHeartbeatTimer()
end
end
-- Ajoute une commande au journal (leader uniquement)
function Node:appendCommand(command)
if self.state ~= ROLE_LEADER then
return false, "Pas leader"
end
local entry = {term = self.currentTerm, command = command}
table.insert(self.log, entry)
-- Pour simplifier, commit immédiat
self.commitIndex = #self.log
self:applyLogEntries()
return true
end
-- API publique
Raft.Node = Node
return Raft-- Exemple complet pour tester la bibliothèque Raft
local Raft = require("raft") -- suppose que le code est dans raft.lua
local socket = require("socket")
-- Configuration des nœuds
local peers = {
[1] = {host = "127.0.0.1", port = 8001},
[2] = {host = "127.0.0.1", port = 8002},
[3] = {host = "127.0.0.1", port = 8003}
}
-- Fonction pour afficher les commandes appliquées
local function onCommit(command)
print("Commande appliquée :", command)
end
-- Fonction pour envoyer un message (non utilisé ici car socket est géré dans Node)
local function sendMessage() end
-- Création des nœuds
local nodes = {}
for id, _ in pairs(peers) do
nodes[id] = Raft.Node:new({
id = id,
peers = peers,
onCommit = onCommit,
sendMessage = sendMessage
})
nodes[id]:initSocket()
end
-- Fonction pour simuler la boucle d'événements
local function runSimulation(durationSeconds)
local startTime = socket.gettime()
while socket.gettime() - startTime < durationSeconds do
for _, node in pairs(nodes) do
node:tick()
end
socket.sleep(0.05) -- pause pour éviter CPU à 100%
end
end
print("Démarrage de la simulation Raft simplifiée...")
runSimulation(5) -- exécute 5 secondes
-- Tente d'ajouter une commande sur le leader (si trouvé)
for _, node in pairs(nodes) do
if node.state == "leader" then
local ok, err = node:appendCommand("commande_test")
if ok then
print("Commande ajoutée au leader", node.id)
else
print("Erreur lors de l'ajout de commande :", err)
end
break
end
end
runSimulation(2) -- laisse le temps de réplication
print("Fin de la simulation.")
-- Note :
-- Ce script crée 3 nœuds Raft sur localhost avec des ports différents.
-- Il exécute une boucle de tick pour simuler le fonctionnement.
-- Il tente d'ajouter une commande sur le leader détecté.
-- Les commandes appliquées sont affichées dans la console.
-- Le code original de la bibliothèque Raft est supposé être dans raft.lua et est identique à celui fourni.Nœud : représente un seul nœud dans le cluster avec état (follower, candidate, leader), journal et terme courant.
Messagerie : gestion asynchrone des messages entre nœuds (RequestVote, AppendEntries) via des callbacks configurables.
Timer : gestion des timeouts pour l'élection et le battement de cœur avec des fonctions de planification configurables.
Configuration réseau : définition des adresses IP et ports des nœuds pour communication via sockets UDP/TCP.
Câblage/pinout Arduino : non applicable directement, mais peut s'intégrer avec des modules ESP8266/ESP32 pour communication WiFi (ex. pins GPIO pour LED d'état, boutons pour reset).
Dépendances logicielles : LuaSocket pour communication réseau, LuaTimer ou équivalent pour gestion des timers, JSON.lua pour sérialisation des messages.
Configuration : fichier de configuration Lua pour définir les paramètres du cluster (nombre de nœuds, ID du nœud local, timeout d'élection, intervalle de battement de cœur).