-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathelection.go
More file actions
203 lines (180 loc) · 4.45 KB
/
Copy pathelection.go
File metadata and controls
203 lines (180 loc) · 4.45 KB
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
package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"log"
"net/http"
"sync"
"sync/atomic"
"time"
)
var (
leaderID atomic.Int32
electionMu sync.Mutex
inElection atomic.Bool
)
func getLeaderID() int {
return int(leaderID.Load())
}
func setLeaderID(id int) {
old := int(leaderID.Load())
leaderID.Store(int32(id))
if old != id {
log.Printf("[Election] leader changed %d -> %d", old, id)
broadcastEvent("LEADER_CHANGE", map[string]int{"leader_id": id})
}
}
func isLeader() bool {
return nodeID != 0 && getLeaderID() == nodeID
}
// runElection is the background goroutine that monitors leader liveness.
func runElection() {
// Give other nodes time to start
time.Sleep(3 * time.Second)
// Initial election
triggerElection()
ticker := time.NewTicker(2 * time.Second)
defer ticker.Stop()
for range ticker.C {
lid := getLeaderID()
if lid == 0 {
triggerElection()
continue
}
if lid == nodeID {
// We are the leader; nothing to check
continue
}
// Ping leader
port := getPeerPort(lid)
if port == "" {
triggerElection()
continue
}
if !pingNode(port) {
log.Printf("[Election] leader %d unreachable, starting election", lid)
triggerElection()
}
}
}
func pingNode(port string) bool {
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
defer cancel()
req, err := http.NewRequestWithContext(ctx, "GET",
peerURL(port, "/health"), nil)
if err != nil {
return false
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return false
}
resp.Body.Close()
return resp.StatusCode == http.StatusOK
}
// triggerElection runs the Bully algorithm.
// The node with the highest ID among online nodes becomes the leader.
func triggerElection() {
if !inElection.CompareAndSwap(false, true) {
return
}
defer inElection.Store(false)
electionMu.Lock()
defer electionMu.Unlock()
log.Printf("[Election] node %d starting bully election", nodeID)
// Find highest online ID >= our own
highestID := nodeID
nodes := getOnlineNodes()
for _, n := range nodes {
if n.ID > nodeID {
// Send election message to higher node
port := getPeerPort(n.ID)
if port == "" {
continue
}
if sendElectionMsg(port, nodeID) {
// Higher node acknowledged – it will take over
log.Printf("[Election] node %d defers to node %d", nodeID, n.ID)
time.Sleep(500 * time.Millisecond)
return
}
}
}
// No higher node responded – we are the new leader
_ = highestID
log.Printf("[Election] node %d declaring itself leader", nodeID)
setLeaderID(nodeID)
// Announce to all peers
for _, n := range nodes {
if n.ID != nodeID {
port := getPeerPort(n.ID)
if port != "" {
go sendCoordinatorMsg(port, nodeID)
}
}
}
}
func sendElectionMsg(port string, fromID int) bool {
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
defer cancel()
body, _ := json.Marshal(map[string]int{"from_id": fromID})
req, err := http.NewRequestWithContext(ctx, "POST",
peerURL(port, "/internal/election"),
bytes.NewReader(body))
if err != nil {
return false
}
req.Header.Set("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(req)
if err != nil {
return false
}
resp.Body.Close()
return resp.StatusCode == http.StatusOK
}
func sendCoordinatorMsg(port string, newLeader int) {
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
defer cancel()
body, _ := json.Marshal(map[string]int{"leader_id": newLeader})
req, err := http.NewRequestWithContext(ctx, "POST",
peerURL(port, "/internal/coordinator"),
bytes.NewReader(body))
if err != nil {
return
}
req.Header.Set("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(req)
if err != nil {
return
}
resp.Body.Close()
}
// ---- Internal HTTP handlers ----
func handleElectionMsg(w http.ResponseWriter, r *http.Request) {
var msg struct {
FromID int `json:"from_id"`
}
json.NewDecoder(r.Body).Decode(&msg)
if msg.FromID < nodeID {
// We are higher – acknowledge and start our own election
w.WriteHeader(http.StatusOK)
go triggerElection()
} else {
// Sender is higher or equal – defer
w.WriteHeader(http.StatusConflict)
}
}
func handleCoordinatorMsg(w http.ResponseWriter, r *http.Request) {
var msg struct {
LeaderID int `json:"leader_id"`
}
json.NewDecoder(r.Body).Decode(&msg)
if msg.LeaderID > 0 {
setLeaderID(msg.LeaderID)
markPeer(msg.LeaderID, true, 0)
}
w.WriteHeader(http.StatusOK)
fmt.Fprint(w, `{"ok":true}`)
}