-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
133 lines (101 loc) · 2.19 KB
/
main.go
File metadata and controls
133 lines (101 loc) · 2.19 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
package main
import (
"encoding/gob"
"flag"
"fmt"
"github.com/chamlis/daft/raft"
"math/rand"
"strings"
"sync"
"time"
)
type Increment struct {
lock sync.RWMutex
value int
}
type IncrementCommand struct {
Id int
}
type TripleCommand struct {
Id int
}
type GetResponse struct {
Value int
}
func (i *Increment) Update(command interface{}) {
switch command.(type) {
case IncrementCommand:
i.value++
case TripleCommand:
i.value *= 3
}
}
func (i *Increment) Get(req interface{}) interface{} {
i.lock.RLock()
defer i.lock.RUnlock()
return GetResponse{
Value: i.value,
}
}
func sendCommands(cluster []string) {
client := raft.NewClient(cluster)
commandInterval := time.NewTicker(50 * time.Millisecond)
commandsSent := 0
for {
<-commandInterval.C
var resp interface{}
if rand.Intn(2) == 0 {
resp = client.AddLogEntry(IncrementCommand{
Id: rand.Intn(1000),
})
} else {
resp = client.AddLogEntry(TripleCommand{
Id: rand.Intn(1000),
})
}
fmt.Println("Reply", resp.(int))
commandsSent++
if commandsSent%10 == 0 {
resp := client.Get("GetValue", nil).(GetResponse)
fmt.Println("Read value", resp.Value)
}
}
}
func main() {
myAddr := flag.String("me", "", "This node ID")
cluster := flag.String("cluster", "", "Comma seperated nodes")
stateFile := flag.String("state", "", "File to store state")
flag.Parse()
if *myAddr == "" || *cluster == "" || *stateFile == "" {
fmt.Println("Bad options")
return
}
gob.Register(IncrementCommand{})
gob.Register(TripleCommand{})
gob.Register(GetResponse{})
rand.Seed(time.Now().UnixNano())
s := raft.NewSqliteStorage(*stateFile)
state := Increment{
value: 0,
}
commits := make(chan raft.Commit, 16)
clusterSplit := strings.Split(*cluster, ",")
r := raft.NewRaft(s, commits, *myAddr, clusterSplit)
r.RegisterGet("GetValue", state.Get)
go r.Serve()
commandsApplied := 0
go sendCommands(clusterSplit)
for {
commit := <-commits
state.lock.Lock()
state.Update(commit.Data)
commit.Response <- state.value
close(commit.Response)
state.lock.Unlock()
commandsApplied++
if commandsApplied%25 == 0 {
fmt.Println(commandsApplied, "state is", state.value)
}
}
r.Shutdown()
}