-
Notifications
You must be signed in to change notification settings - Fork 0
/
dkv.go
255 lines (198 loc) · 4.35 KB
/
dkv.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
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
package dkv
import (
"bytes"
"encoding/gob"
"errors"
"fmt"
"io"
"log"
"maps"
"net"
"os"
"sync"
"time"
"github.com/hashicorp/raft"
)
const raftTimeout = 10 * time.Second
var ErrKeyDoesNotExist = errors.New("key does not exist")
func init() {
gob.Register(&Command{})
}
type CommandType int
const (
SET CommandType = iota
GET
DEL
)
type Command struct {
Cmd CommandType
Key string
Val string
}
type DKV struct {
kv map[string]string
mu sync.RWMutex
raft *raft.Raft
}
func newDKV(single bool, raftAddr string) (*DKV, error) {
d := &DKV{
kv: make(map[string]string),
}
config := raft.DefaultConfig()
config.LocalID = raft.ServerID(raftAddr)
addr, err := net.ResolveTCPAddr("tcp", raftAddr)
if err != nil {
return nil, err
}
logStore := raft.NewInmemStore()
stableStore := raft.NewInmemStore()
snapshot := raft.NewInmemSnapshotStore()
transport, err := raft.NewTCPTransport(raftAddr, addr, 3, 10*time.Second, os.Stderr)
if err != nil {
return nil, err
}
r, err := raft.NewRaft(config, d, logStore, stableStore, snapshot, transport)
if err != nil {
return nil, err
}
d.raft = r
if single {
d.raft.BootstrapCluster(raft.Configuration{Servers: []raft.Server{
{
ID: config.LocalID,
Address: transport.LocalAddr(),
},
}})
}
return d, nil
}
type NotLeaderError struct {
LeaderAddr string
}
func (e *NotLeaderError) Error() string {
return "not leader"
}
func (d *DKV) Set(k string, v string) error {
if d.raft.State() != raft.Leader {
addr, _ := d.raft.LeaderWithID()
return &NotLeaderError{LeaderAddr: string(addr)}
}
cmd := Command{
Cmd: SET,
Key: k,
Val: v,
}
buf := bytes.Buffer{}
err := gob.NewEncoder(&buf).Encode(&cmd)
if err != nil {
return err
}
future := d.raft.Apply(buf.Bytes(), raftTimeout)
return future.Error()
}
func (d *DKV) Get(k string) (string, error) {
// TODO: eventual consistency?
// if d.raft.State() != raft.Leader {
// addr, _ := d.raft.LeaderWithID()
// return "", &NotLeaderError{LeaderAddr: string(addr)}
// }
d.mu.RLock()
defer d.mu.RUnlock()
v, ok := d.kv[k]
if !ok {
return "", ErrKeyDoesNotExist
}
return v, nil
}
func (d *DKV) Del(k string) error {
if d.raft.State() != raft.Leader {
addr, _ := d.raft.LeaderWithID()
return &NotLeaderError{LeaderAddr: string(addr)}
}
cmd := Command{
Cmd: DEL,
Key: k,
}
buf := bytes.Buffer{}
err := gob.NewEncoder(&buf).Encode(&cmd)
if err != nil {
return err
}
future := d.raft.Apply(buf.Bytes(), raftTimeout)
return future.Error()
}
func (d *DKV) Join(raftAddr string) error {
if d.raft.State() != raft.Leader {
addr, _ := d.raft.LeaderWithID()
return &NotLeaderError{LeaderAddr: string(addr)}
}
futureConfig := d.raft.GetConfiguration()
if err := futureConfig.Error(); err != nil {
log.Println("unable to get config")
return err
}
config := futureConfig.Configuration()
for _, server := range config.Servers {
if server.ID == raft.ServerID(raftAddr) || server.Address == raft.ServerAddress(raftAddr) {
if server.ID == raft.ServerID(raftAddr) && server.Address == raft.ServerAddress(raftAddr) {
return nil
}
future := d.raft.RemoveServer(server.ID, 0, 0)
if err := future.Error(); err != nil {
return fmt.Errorf("error %s %s", raftAddr, err)
}
}
}
future := d.raft.AddVoter(raft.ServerID(raftAddr), raft.ServerAddress(raftAddr), 0, 0)
if err := future.Error(); err != nil {
return err
}
return nil
}
func (d *DKV) Apply(l *raft.Log) interface{} {
var req Command
err := gob.NewDecoder(bytes.NewReader(l.Data)).Decode(&req)
if err != nil {
return err
}
d.mu.Lock()
defer d.mu.Unlock()
switch req.Cmd {
case SET:
d.kv[req.Key] = req.Val
case DEL:
delete(d.kv, req.Key)
default:
log.Fatal("not handled operation")
}
return nil
}
func (d *DKV) Snapshot() (raft.FSMSnapshot, error) {
d.mu.Lock()
defer d.mu.Unlock()
clone := maps.Clone(d.kv)
snapshot := &snapshot{kv: clone}
return snapshot, nil
}
func (d *DKV) Restore(rc io.ReadCloser) error {
var store map[string]string
err := gob.NewDecoder(rc).Decode(&store)
if err != nil {
return err
}
d.kv = store
return nil
}
type snapshot struct {
kv map[string]string
}
func (s *snapshot) Persist(sink raft.SnapshotSink) error {
err := gob.NewEncoder(sink).Encode(&s.kv)
if err != nil {
sink.Cancel()
return err
}
return sink.Close()
}
func (s *snapshot) Release() {
}