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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
|
package quorum
import (
"context"
"fmt"
"log"
"os"
"sort"
"strconv"
"strings"
"time"
"codeberg.org/snonux/gorum/internal/config"
"codeberg.org/snonux/gorum/internal/vote"
)
type Quorum struct {
conf config.Config
// My own vote, sending to the partners
myVote vote.Vote
// From partners received votes
voteCh chan vote.Vote
votes map[string]vote.Vote
}
type Score struct {
ID string
Value int
}
func (s Score) Is(other Score) bool {
return s.ID == other.ID && s.Value == other.Value
}
type Scores []Score
func (s Scores) Winner() (Score, error) {
if len(s) == 0 {
return Score{}, fmt.Errorf("emtpy score, no winner")
}
return s[0], nil
}
func New(conf config.Config) Quorum {
return Quorum{
conf: conf,
votes: make(map[string]vote.Vote),
voteCh: make(chan vote.Vote),
}
}
func (quo Quorum) Start(ctx context.Context) <-chan vote.Vote {
ch := make(chan vote.Vote)
interval := time.Second * time.Duration(quo.conf.LoopIntervalS)
if vote.Expiry <= interval {
log.Fatal("quorum: LoopIntervalS ", quo.conf.LoopIntervalS,
" should be less than the vote expiry of ", vote.Expiry)
}
go func() {
defer close(ch)
var (
myVote vote.Vote
changed bool
)
for {
select {
case <-time.After(interval):
myVote, _ = quo.makeMyVote()
log.Println("quorum: made my vote:", myVote)
ch <- myVote
case v := <-quo.voteCh:
quo.vote(v)
if myVote, changed = quo.makeMyVote(); changed {
log.Println("quorum: changed my vote:", myVote)
ch <- myVote
}
case <-ctx.Done():
return
}
if err := quo.persist(changed); err != nil {
log.Println("quorum:", err)
notifyError(quo.conf, err)
}
}
}()
return ch
}
func (quo Quorum) Vote(v vote.Vote) {
log.Printf("quorum: queing vote %v", v)
quo.voteCh <- v
}
func (quo Quorum) vote(v vote.Vote) {
log.Printf("quorum: adding vote %v", v)
quo.votes[v.FromID] = v
}
func (quo Quorum) scores() (scores Scores) {
scoreMap := make(map[string]int)
for _, vote := range quo.votes {
if vote.Expired() {
continue
}
for _, id := range vote.IDs {
score := scoreMap[id]
nodeNumber := quo.conf.NodeNumber(id)
scoreMap[id] = score + 100 + (len(quo.conf.Nodes) - nodeNumber)
}
}
for id, score_ := range scoreMap {
scores = append(scores, Score{id, score_})
}
sort.Slice(scores, func(i, j int) bool {
return scores[i].Value > scores[j].Value
})
return
}
func (quo *Quorum) strs() (string, string) {
scores := quo.scores()
log.Println("quorum scores:", scores)
winner, err := scores.Winner()
if err != nil {
log.Println("the winner is", winner.ID)
}
var sb strings.Builder
winnerStr := ""
for i, score := range scores {
sb.WriteString("At position ")
sb.WriteString(strconv.Itoa(i + 1))
if score.ID == quo.conf.MyID {
sb.WriteString(" is current node ")
if score.Is(winner) {
winnerStr = fmt.Sprintf("Yeah, I, %s, am the winner!", winner.ID)
}
} else {
sb.WriteString(" is partner node ")
}
sb.WriteString(score.ID)
sb.WriteString(" (node #")
sb.WriteString(strconv.Itoa(quo.conf.NodeNumber(score.ID)))
sb.WriteString(") with total score of ")
sb.WriteString(strconv.Itoa(score.Value))
sb.WriteString("\n")
}
return winnerStr, sb.String()
}
func (quo *Quorum) persist(changed bool) error {
winnerStr, scoresStr := quo.strs()
if changed {
if err := notify(quo.conf, "GORUM: Quorum changed", scoresStr); err != nil {
return err
}
}
if _, err := os.Stat(quo.conf.StateDir); os.IsNotExist(err) {
if err := os.MkdirAll(quo.conf.StateDir, 0755); err != nil {
return err
}
}
if err := quo.persistWinner(winnerStr); err != nil {
return err
}
return writeFileViaTmp(fmt.Sprintf("%s/%s", quo.conf.StateDir, quo.conf.ScoreFile), scoresStr)
}
func (quo *Quorum) persistWinner(winnerStr string) error {
winnerFile := fmt.Sprintf("%s/%s", quo.conf.StateDir, quo.conf.WinnerFile)
if winnerStr == "" {
if _, err := os.Stat(winnerFile); err != nil {
return os.Remove(winnerFile)
}
return nil
}
return writeFileViaTmp(winnerFile, winnerStr)
}
func (quo *Quorum) makeMyVote() (vote.Vote, bool) {
newVote, err := quo.expireOldVotes()
if err != nil {
log.Println("quorum:", err)
return quo.myVote, false
}
if quo.myVote.Equal(newVote) {
return quo.myVote, false
}
quo.myVote = newVote
return quo.myVote, true
}
func (quo Quorum) expireOldVotes() (vote.Vote, error) {
var expired []string
var live []string
for fromNode, vote := range quo.votes {
if vote.Expired() {
log.Println("quorum: vote", vote, "from node", fromNode, "expired!")
expired = append(expired, fromNode)
continue
}
live = append(live, fromNode)
}
for _, e := range expired {
delete(quo.votes, e)
}
return vote.New(quo.conf, live...)
}
// Create tmp file first, and then, once written, rename it.
func writeFileViaTmp(filePath, content string) error {
tmpFilePath := fmt.Sprintf("%s.tmp", filePath)
fd, err := os.Create(tmpFilePath)
if err != nil {
return err
}
defer fd.Close()
if _, err := fd.WriteString(content); err != nil {
return err
}
if err := fd.Sync(); err != nil {
return err
}
return os.Rename(tmpFilePath, filePath)
}
|