Implemented functionality to add voter to raft cluster upon leader receiving join request broadcast.

Servers broadcast join cluster message until they receive a message confirming they have successfully joined.
This commit is contained in:
Kelvin Clement Mwinuka
2023-07-31 00:18:26 +08:00
parent 094d44c9a0
commit 989e19e6ba
3 changed files with 58 additions and 16 deletions

View File

@@ -1,6 +1,7 @@
package main
import (
"errors"
"fmt"
"io"
"log"
@@ -114,6 +115,41 @@ func (server *Server) isRaftLeader() bool {
return server.raft.State() == raft.Leader
}
func (server *Server) addVoter(
id raft.ServerID,
address raft.ServerAddress,
prevIndex uint64,
timeout time.Duration,
) error {
if server.isRaftLeader() {
raftConfig := server.raft.GetConfiguration()
if err := raftConfig.Error(); err != nil {
return errors.New("could not retrieve raft config")
}
for _, s := range raftConfig.Configuration().Servers {
// Check if a server already exists with the current attribtues
if s.ID == id && s.Address == address {
return fmt.Errorf("server with id %s and address %s already exists", id, address)
}
}
err := server.raft.AddVoter(id, address, prevIndex, timeout).Error()
if err != nil {
return err
}
// After successfully adding the voter node, broadcast the success message
msg := BroadcastMessage{
Action: "RaftJoinSuccess",
ServerID: id,
ServerAddr: address,
}
server.broadcastQueue.QueueBroadcast(&msg)
}
return nil
}
func (server *Server) RaftShutdown() {
// Triggered before MemberListShutdown
// Leadership transfer if current node is the leader