/
store.go
295 lines (250 loc) · 6.83 KB
/
store.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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
// Package store provides a simple distributed key-value store. The keys and
// associated values are changed via distributed consensus, meaning that the
// values are changed only when a majority of nodes in the cluster agree on
// the new value.
//
// Distributed consensus is provided via the Raft algorithm, specifically the
// Hashicorp implementation.
package store
import (
"fmt"
"io"
"log"
"net"
"os"
"sync"
"time"
"github.com/hashicorp/raft"
"github.com/thesyncim/raft-badger"
"path/filepath"
"github.com/vmihailenco/msgpack"
)
const (
retainSnapshotCount = 2
raftTimeout = 10 * time.Second
)
type command struct {
Op string `json:"op,omitempty"`
Key string `json:"key,omitempty"`
Value string `json:"value,omitempty"`
}
// Store is a simple key-value store, where all changes are made via Raft consensus.
type Store struct {
RaftDir string
RaftBind string
mu sync.Mutex
m map[string]string // The key-value store for the system.
raftStore [2]io.Closer
raft *raft.Raft // The consensus mechanism
logger *log.Logger
}
// New returns a new Store.
func New() *Store {
return &Store{
m: make(map[string]string),
logger: log.New(os.Stderr, "[store] ", log.LstdFlags),
}
}
// Open opens the store. If enableSingle is set, and there are no existing peers,
// then this node becomes the first node, and therefore leader, of the cluster.
// localID should be the server identifier for this node.
func (s *Store) Open(enableSingle bool, localID string) error {
// Setup Raft configuration.
config := raft.DefaultConfig()
config.LocalID = raft.ServerID(localID)
// Setup Raft communication.
addr, err := net.ResolveTCPAddr("tcp", s.RaftBind)
if err != nil {
return err
}
transport, err := raft.NewTCPTransport(s.RaftBind, addr, 3, 10*time.Second, os.Stderr)
if err != nil {
return err
}
// Create the snapshot store. This allows the Raft to truncate the log.
snapshots, err := raft.NewFileSnapshotStore(s.RaftDir, retainSnapshotCount, os.Stderr)
if err != nil {
return fmt.Errorf("file snapshot store: %s", err)
}
// Create the log store and stable store.
logStore, err := raftbadger.NewLogStore(filepath.Join(localID, "log"), nil)
if err != nil {
return err
}
stable, err := raftbadger.NewStableStore(filepath.Join(localID, "stable"), nil)
if err != nil {
return err
}
s.raftStore[0] = logStore
s.raftStore[1] = stable
// Instantiate the Raft systems.
ra, err := raft.NewRaft(config, (*fsm)(s), logStore, stable, snapshots, transport)
if err != nil {
return fmt.Errorf("new raft: %s", err)
}
s.raft = ra
if enableSingle {
configuration := raft.Configuration{
Servers: []raft.Server{
{
ID: config.LocalID,
Address: transport.LocalAddr(),
},
},
}
ra.BootstrapCluster(configuration)
}
return nil
}
// Get returns the value for the given key.
func (s *Store) Get(key string) (string, error) {
s.mu.Lock()
defer s.mu.Unlock()
return s.m[key], nil
}
// Set sets the value for the given key.
func (s *Store) Set(key, value string) error {
if s.raft.State() != raft.Leader {
return fmt.Errorf("not leader")
}
c := &command{
Op: "set",
Key: key,
Value: value,
}
b, err := msgpack.Marshal(c)
if err != nil {
return err
}
f := s.raft.Apply(b, raftTimeout)
return f.Error()
}
// Delete deletes the given key.
func (s *Store) Delete(key string) error {
if s.raft.State() != raft.Leader {
return fmt.Errorf("not leader")
}
c := &command{
Op: "delete",
Key: key,
}
b, err := msgpack.Marshal(c)
if err != nil {
return err
}
f := s.raft.Apply(b, raftTimeout)
return f.Error()
}
// Join joins a node, identified by nodeID and located at addr, to this store.
// The node must be ready to respond to Raft communications at that address.
func (s *Store) Join(nodeID, addr string) error {
s.logger.Printf("received join request for remote node %s at %s", nodeID, addr)
configFuture := s.raft.GetConfiguration()
if err := configFuture.Error(); err != nil {
s.logger.Printf("failed to get raft configuration: %v", err)
return err
}
for _, srv := range configFuture.Configuration().Servers {
// If a node already exists with either the joining node's ID or address,
// that node may need to be removed from the config first.
if srv.ID == raft.ServerID(nodeID) || srv.Address == raft.ServerAddress(addr) {
// However if *both* the ID and the address are the same, then nothing -- not even
// a join operation -- is needed.
if srv.Address == raft.ServerAddress(addr) && srv.ID == raft.ServerID(nodeID) {
s.logger.Printf("node %s at %s already member of cluster, ignoring join request", nodeID, addr)
return nil
}
future := s.raft.RemoveServer(srv.ID, 0, 0)
if err := future.Error(); err != nil {
return fmt.Errorf("error removing existing node %s at %s: %s", nodeID, addr, err)
}
}
}
f := s.raft.AddVoter(raft.ServerID(nodeID), raft.ServerAddress(addr), 0, 0)
if f.Error() != nil {
return f.Error()
}
s.logger.Printf("node %s at %s joined successfully", nodeID, addr)
return nil
}
func (s *Store) Close() error {
for i := range s.raftStore {
if err := s.raftStore[i].Close(); err != nil {
return err
}
}
return nil
}
type fsm Store
// Apply applies a Raft log entry to the key-value store.
func (f *fsm) Apply(l *raft.Log) interface{} {
var c command
if err := msgpack.Unmarshal(l.Data, &c); err != nil {
panic(fmt.Sprintf("failed to unmarshal command: %s", err.Error()))
}
switch c.Op {
case "set":
return f.applySet(c.Key, c.Value)
case "delete":
return f.applyDelete(c.Key)
default:
panic(fmt.Sprintf("unrecognized command op: %s", c.Op))
}
}
// Snapshot returns a snapshot of the key-value store.
func (f *fsm) Snapshot() (raft.FSMSnapshot, error) {
f.mu.Lock()
defer f.mu.Unlock()
// Clone the map.
o := make(map[string]string)
for k, v := range f.m {
o[k] = v
}
return &fsmSnapshot{store: o}, nil
}
// Restore stores the key-value store to a previous state.
func (f *fsm) Restore(rc io.ReadCloser) error {
o := make(map[string]string)
if err := msgpack.NewDecoder(rc).Decode(&o); err != nil {
return err
}
// Set the state from the snapshot, no lock required according to
// Hashicorp docs.
f.m = o
return nil
}
func (f *fsm) applySet(key, value string) interface{} {
f.mu.Lock()
defer f.mu.Unlock()
f.m[key] = value
return nil
}
func (f *fsm) applyDelete(key string) interface{} {
f.mu.Lock()
defer f.mu.Unlock()
delete(f.m, key)
return nil
}
type fsmSnapshot struct {
store map[string]string
}
func (f *fsmSnapshot) Persist(sink raft.SnapshotSink) error {
err := func() error {
// Encode data.
b, err := msgpack.Marshal(f.store)
if err != nil {
return err
}
// Write data to sink.
if _, err := sink.Write(b); err != nil {
return err
}
// Close the sink.
return sink.Close()
}()
if err != nil {
sink.Cancel()
}
return err
}
func (f *fsmSnapshot) Release() {}