-
Notifications
You must be signed in to change notification settings - Fork 0
/
leader.go
119 lines (107 loc) · 2.29 KB
/
leader.go
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
package main
import (
"context"
"encoding/json"
"fmt"
"os"
"time"
)
var TERM_OVER = fmt.Errorf("A new term has started")
func (s *Server) becomeLeader() {
s.mu.Lock()
s.State = LEADER
s.currentLeader = s.n.ID()
for _, id := range s.n.NodeIDs() {
lastEntry := s.Log[len(s.Log)-1]
s.NextIndex[id] = lastEntry.Index + 1
s.MatchIndex[id] = 0
}
s.mu.Unlock()
ctx, cancel := context.WithCancel(context.Background())
for _, id := range s.n.NodeIDs() {
id := id
go func() {
err := s.sendAppendEntries(id)
if err == TERM_OVER {
cancel()
} else if err != nil {
fmt.Fprintf(os.Stderr, err.Error())
}
}()
}
go func() {
t := time.NewTicker(50 * time.Millisecond)
for {
select {
case <-ctx.Done():
return
case <-t.C:
for _, id := range s.n.NodeIDs() {
id := id
go func() {
err := s.sendAppendEntries(id)
if err == TERM_OVER {
cancel()
} else if err != nil {
fmt.Fprintf(os.Stderr, err.Error())
}
}()
}
}
}
}()
go func() {
<-ctx.Done()
s.becomeFollower()
}()
}
func (s *Server) sendAppendEntries(id string) error {
if id == s.n.ID() {
return nil
}
s.mu.Lock()
lastEntry := s.Log[len(s.Log)-1]
lastReplicatedEntry := s.Log[s.NextIndex[id]-1]
entries := []LogEntry{}
for i := s.NextIndex[id]; i < len(s.Log); i++ {
entries = append(entries, s.Log[i])
}
inputBody := AppendEntriesInput{
Type: "append_entries",
Term: s.CurrentTerm,
LeaderId: s.n.ID(),
PrevLogIndex: lastReplicatedEntry.Index,
PrevLogTerm: lastReplicatedEntry.Term,
Entries: entries,
LeaderCommit: s.CommitIndex,
}
s.mu.Unlock()
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
res, err := s.n.SyncRPC(ctx, id, inputBody)
if err != nil {
return err
} else if inputBody.Term > s.CurrentTerm {
s.mu.Lock()
s.CurrentTerm = inputBody.Term
s.mu.Unlock()
return TERM_OVER
}
var outputBody AppendEntriesOutput
if err := json.Unmarshal(res.Body, &outputBody); err != nil {
return err
}
s.mu.Lock()
if outputBody.Success {
s.NextIndex[id] = lastEntry.Index + 1
s.MatchIndex[id] = lastEntry.Index
} else {
if s.NextIndex[id] > 1 {
s.NextIndex[id]--
}
s.mu.Unlock()
return s.sendAppendEntries(id)
}
s.mu.Unlock()
return nil
}