-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathheartbeat.go
More file actions
140 lines (123 loc) · 2.8 KB
/
Copy pathheartbeat.go
File metadata and controls
140 lines (123 loc) · 2.8 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
package main
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"time"
)
const heartbeatInterval = 50 * time.Millisecond
func (n *Node) runHeartbeat() {
ticker := time.NewTicker(heartbeatInterval)
defer ticker.Stop()
for {
select {
case <-ticker.C:
n.mu.Lock()
if n.role != Leader {
n.mu.Unlock()
return
}
peers := n.config.Peers
term := n.currentTerm
commitIndex := n.commitIndex
id := n.id
n.mu.Unlock()
// send heartbeat to all peers in parallel, including any missing entries
for _, peer := range peers {
if peer == id {
continue
}
go func(peer string) {
n.mu.Lock()
next := n.nextIndex[peer]
var entries []LogEntry
if next > 0 && next <= len(n.log) {
entries = n.log[next-1:]
}
n.mu.Unlock()
n.sendAppendEntries(peer, term, commitIndex, entries)
}(peer)
}
case <-n.stopHeartbeat:
return
}
}
}
func (n *Node) sendAppendEntries(peer string, term int, commitIndex int, entries []LogEntry) {
body := AppendEntriesRequest{
Term: term,
LeaderID: n.id,
CommitIndex: commitIndex,
Entries: entries,
}
data, err := json.Marshal(body)
if err != nil {
return
}
resp, err := http.Post(fmt.Sprintf("http://%s/append-entries", peer), "application/json", bytes.NewReader(data))
if err != nil {
return
}
defer resp.Body.Close()
var result AppendEntriesResponse
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
return
}
// if peer has a higher term we are stale, step down
n.mu.Lock()
defer n.mu.Unlock()
if result.Term > n.currentTerm {
n.currentTerm = result.Term
n.stepDown()
return
}
// update matchIndex and nextIndex for this peer
if result.Success && len(entries) > 0 {
lastEntry := entries[len(entries)-1]
n.matchIndex[peer] = lastEntry.Index
n.nextIndex[peer] = lastEntry.Index + 1
n.maybeCommit()
}
}
// checks if any new entries can be committed based on matchIndex. an entry is committed once a majority of nodes have it
func (n *Node) maybeCommit() {
quorum := n.config.Quorum()
for i := len(n.log) - 1; i >= 0; i-- {
entry := n.log[i]
if entry.Index <= n.commitIndex {
break
}
if entry.Term != n.currentTerm {
continue
}
// count how many nodes have this entry
count := 1 // count ourselves
for _, peer := range n.config.Peers {
if peer == n.id {
continue
}
if n.matchIndex[peer] >= entry.Index {
count++
}
}
if count >= quorum {
// commit everything up to this index
for j := 0; j <= i; j++ {
if n.log[j].Index > n.commitIndex {
n.applyEntry(n.log[j])
n.commitIndex = n.log[j].Index
}
}
break
}
}
}
func (n *Node) stepDown() {
if n.role == Leader {
close(n.stopHeartbeat)
n.stopHeartbeat = make(chan struct{})
}
n.role = Follower
n.currentLeader = ""
}