-
Notifications
You must be signed in to change notification settings - Fork 0
/
alternator.go
534 lines (465 loc) · 14.4 KB
/
alternator.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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
// Package alternator implements a distributed, fault-tolerant key-value store. Node nodes arrange
// themselves into a ring, where each node maintains a complete membership list, which is kept
// up-to-date by distributing membership changes (as a history) by a gossip algorithm. Alternator's
// main feature is that the user can choose arbitrarily the nodes in the system that will replicate
// any given entry. This gives the user full control of the data-flow in the system.
package alternator
import (
"container/list"
"fmt"
"log"
"net"
"net/http"
"runtime"
"strings"
// For profile
_ "net/http/pprof"
"net/rpc"
"os"
"os/signal"
"sync"
"time"
)
// Config stores a node's configuration settings.
type Config struct {
// FullKeys, when true, makes all console output print complete keys. Otherwise, abbreviations
// are used.
FullKeys bool
// MemberSyncTime is the time (in ms) between history syncs with a random peer.
MemberSyncTime int
// HeartbeatTime is the time (in ms) between heartbeats.
HeartbeatTime int
// ResolvePendingTime is the time (in ms) between attempts to resolve pending put operations.
ResolvePendingTime int
// HeatbeatTimeout is the time (in ms) before a heartbeat times out.
HeartbeatTimeout int
// PutMDTimeout is the time (in ms) before a PutMD times out.
PutMDTimeout int
// PutDataTimeout is the time (in ms) before a PutData times out.
PutDataTimeout int
// N is the number of nodes in which metadata is replicated (size of the replication chain).
N int
// Directory for alternator's data, including database files.
DotPath string
// CPUProfile enables profiling when set to true.
CPUProfile bool
}
// To avoid passing to methods not belonging to altNode
var fullKeys = false
// Node is a member of the DHT. All methods belonging to Node that are exported are also accessible
// through RPC (hence the arguments to exported methods are always those required by the rpc
// package)
type Node struct {
ID Key
Address string
Port string
Members Members
memberHist history
historyMutex sync.RWMutex
DB *dB
Config Config
RPCListener net.Listener
rpcServ RPCService
}
// CreateNode creates a new node, initializes all of its fields, and exposes its
// exported methods through RPC.
func CreateNode(conf Config, port string, address string) {
// Register node as RPC server
node := new(Node)
rpc.Register(node)
rpc.HandleHTTP()
l, err := net.Listen("tcp", ":"+port)
checkErr("listen error ", err)
// Get port selected by server
addrstr := l.Addr().String()
colon := strings.LastIndex(addrstr, ":")
port = addrstr[colon+1:]
// Initialize Node fields
node.Address = getIP() + ":" + port
node.Port = port
node.ID = GenID(node.Address)
node.RPCListener = l
node.Config = conf
node.Members.init()
node.initDB()
node.rpcServ.Init()
if conf.CPUProfile {
go func() {
log.Println(http.ListenAndServe("localhost:6060", nil))
}()
}
if node.Config.FullKeys {
fullKeys = true
}
// Join a ring if address is specified
if address != "" {
// We do not know the ID of the node connecting to, use stand-in
var k Key
broker := Peer{ID: k, Address: address}
err = node.joinRing(&broker)
if err != nil {
log.Print("Failed to join ring: ", err)
os.Exit(1)
}
} else { // Else make a new ring
node.createRing()
}
var wg sync.WaitGroup
wg.Add(1)
go node.autoCheckPredecessor()
go node.autoSyncMembers()
go node.autoResolvePending()
go node.sigHandler()
if node.Config.CPUProfile {
runtime.SetCPUProfileRate(10)
runtime.SetBlockProfileRate(1)
go func() {
fmt.Println("starting server")
log.Println(http.ListenAndServe("localhost:6060", nil))
}()
}
fmt.Println(node.string())
fmt.Println("Listening on port " + port)
http.Serve(l, nil)
// TODO: undo hackyness
wg.Wait()
return
}
func (altNode *Node) shutdown() {
altNode.DB.close()
fmt.Println("Goodbye!")
os.Exit(0)
}
/* Ring join functions */
// JoinRequestResp is the set of return parameters to a JoinRequest. The response to a
// join request contains a set of key-value pairs that should be inserted by the new node into
// its metadata database.
type JoinRequestResp struct {
Keys []Key
Vals [][]byte
}
// JoinRequest handles a request by another node to join the ring.
func (altNode *Node) JoinRequest(other *Peer, response *JoinRequestResp) error {
// Find pairs in joiner's range
keys, vals := altNode.DB.getMDRange(altNode.getNthPredecessor(1).ID, other.ID)
fmt.Printf("Giving pairs in range %v to %v\n", altNode.getNthPredecessor(1).ID, other.ID)
// Add join to history
newEntry := histEntry{Time: time.Now(), Class: histJoin, Node: *other}
altNode.insertToHistory(newEntry)
altNode.Members.Lock()
altNode.Members.insert(other)
altNode.Members.Unlock()
fmt.Println("Members changed:")
altNode.Members.RLock()
fmt.Println(altNode.Members)
altNode.Members.RUnlock()
response.Keys = keys
response.Vals = vals
return nil
}
// joinRing joins a node into the ring to which 'broker' belongs.
func (altNode *Node) joinRing(broker *Peer) error {
var successor Peer
// Find future successor using some broker in ring
err := altNode.rpcServ.MakeRemoteCall(broker, "FindSuccessor", altNode.ID, &successor)
if err != nil {
return ErrJoinFail
}
// Do join through future successor
var kvPairs JoinRequestResp
err = altNode.rpcServ.MakeRemoteCall(&successor, "JoinRequest", altNode.selfExt(), &kvPairs)
if err != nil {
return ErrJoinFail
}
// Store keys received from successor
altNode.DB.batchPut(metaDataBucket, &kvPairs.Keys, &kvPairs.Vals)
// Synchronize history with successor
altNode.syncMembers(&successor)
fmt.Println("Successfully joined ring")
return nil
}
/* Ring leave functions */
// LeaveRequestArgs holds arguments for a leave request
type LeaveRequestArgs struct {
Keys []Key
Vals [][]byte
Leaver Peer
}
// LeaveRequest handles a leave request. It appends the departure entry to the node's history.
func (altNode *Node) LeaveRequest(args *LeaveRequestArgs, _ *struct{}) error {
// Insert received keys
batchArgs := BatchPutArgs{metaDataBucket, args.Keys, args.Vals}
altNode.BatchPut(batchArgs, &struct{}{})
departureEntry := histEntry{Time: time.Now(), Class: histLeave, Node: args.Leaver}
altNode.insertToHistory(departureEntry)
altNode.Members.Lock()
altNode.Members.remove(&args.Leaver)
altNode.Members.Unlock()
fmt.Println("Members changed:")
altNode.Members.RLock()
fmt.Println(altNode.Members)
altNode.Members.RUnlock()
// Replicate in one more
err := altNode.rpcServ.MakeRemoteCall(altNode.getNthSuccessor(altNode.Config.N-1), "BatchPut", batchArgs, &struct{}{})
checkErr("Unhandled error", err)
return nil
}
// LeaveRing makes the node leave the ring to which it belongs.
func (altNode *Node) leaveRing() error {
// Stop accepting RPC calls
altNode.RPCListener.Close()
// RePut each entry into the ring
altNode.rePutAllData()
successor := altNode.getSuccessor()
if *successor == altNode.selfExt() {
os.Exit(0)
return nil
}
// Hand keys to successor
mdKeys, mdVals := altNode.DB.getMDRange(altNode.getPredecessor().ID, altNode.ID) // Gather entries
args := LeaveRequestArgs{mdKeys, mdVals, altNode.selfExt()}
// Leave by notifying successor
err := altNode.rpcServ.MakeRemoteCall(successor, "LeaveRequest", &args, &struct{}{})
if err != nil {
return ErrLeaveFail
}
altNode.shutdown()
return nil
}
/* Ring maintenance and stabilization functions */
// createRing creates a ring with this node as its only member.
func (altNode *Node) createRing() {
// Add own join to ring
self := altNode.selfExt()
altNode.insertToHistory(histEntry{Time: time.Now(), Class: histJoin, Node: self})
altNode.Members.Lock()
altNode.Members.insert(&self)
altNode.Members.Unlock()
}
// syncMembers synchronizes the membership list with a peer by synchronizing histories
// and then rebuilding the list if necessary.
func (altNode *Node) syncMembers(peer *Peer) {
if changes := altNode.syncMemberHist(peer); changes {
altNode.rebuildMembers()
fmt.Println("Members changed:")
altNode.Members.RLock()
fmt.Println(altNode.Members)
altNode.Members.RUnlock()
}
}
// Heartbeat returns an 'OK' to the caller.
func (altNode *Node) Heartbeat(_ struct{}, ret *string) error {
*ret = "OK"
return nil
}
// checkPredecessor checks if the predecessor has failed. If the predecessor has
// failed then it closes the RPC connection.
func (altNode *Node) checkPredecessor() {
predecessor := altNode.getPredecessor()
if predecessor.ID.Compare(altNode.ID) == 0 {
return
}
// Ping
c := make(chan error, 1)
beat := ""
go func() {
c <- altNode.rpcServ.MakeRemoteCall(predecessor, "Heartbeat", struct{}{}, &beat)
}()
// TODO: do something smart with heartbeat failures to autodetect departures
select {
case err := <-c:
// Something wrong
if (err != nil) || (beat != "OK") {
altNode.rpcServ.CloseIfBad(err, predecessor)
}
case <-time.After(time.Duration(altNode.Config.HeartbeatTimeout) * time.Millisecond):
// Call timed out
// fmt.Println("Predecessor stopped responding, ceasing connection")
}
}
/* Ring lookup */
// FindSuccessor sets 'succ' to the successor of the key 'k'.
func (altNode *Node) FindSuccessor(k Key, succ *Peer) error {
altNode.Members.RLock()
*succ = *getPeer(altNode.Members.findSuccessor(k))
altNode.Members.RUnlock()
return nil
}
// fingListSuccessor is similar to 'FindSuccessor', except that it returns
// a list element in altNode.Members.List, instead of the value of the
// element.
func (altNode *Node) findListSuccessor(k Key) *list.Element {
altNode.Members.RLock()
succ := altNode.Members.findSuccessor(k)
altNode.Members.RUnlock()
return succ
}
// rebuildMembers rebuilds the membership list of the node from the node's history.
func (altNode *Node) rebuildMembers() {
var newMembers Members
newMembers.init()
for _, entry := range altNode.memberHist {
switch entry.Class {
case histJoin:
copy := entry.Node
newMembers.insert(©)
case histLeave:
newMembers.remove(&entry.Node)
}
}
altNode.Members.Lock()
oldMembers := altNode.Members
altNode.Members = newMembers
// Unlock the old, the new are unlocked from creation
oldMembers.Unlock()
}
/* Membership maintenance functions */
// syncMemberHist synchronizes the node's member history with a peer node
func (altNode *Node) syncMemberHist(peer *Peer) bool {
if peer == nil {
return false
}
var peerHist history
err := altNode.rpcServ.MakeRemoteCall(peer, "GetMemberHist", struct{}{}, &peerHist)
if err != nil {
return false
}
merged, changes := mergeHistories(altNode.memberHist, peerHist)
altNode.historyMutex.Lock()
altNode.memberHist = merged
altNode.historyMutex.Unlock()
return changes
}
// insertToHistory inserts an entry to the node's history
func (altNode *Node) insertToHistory(entry histEntry) {
altNode.historyMutex.Lock()
altNode.memberHist.InsertEntry(entry)
altNode.historyMutex.Unlock()
}
/* Background task functions */
// autoSyncMembers syncs the membership list with a random peer at an interval.
func (altNode *Node) autoSyncMembers() {
for {
altNode.Members.RLock()
random := altNode.Members.getRandom()
altNode.Members.RUnlock()
altNode.syncMembers(random)
// altNode.printHist()
time.Sleep(time.Duration(altNode.Config.MemberSyncTime) * time.Millisecond)
}
}
// autoCheckPredecessor calls checkPredecessor at a time interval.
func (altNode *Node) autoCheckPredecessor() {
for {
altNode.checkPredecessor()
time.Sleep(time.Duration(altNode.Config.HeartbeatTime) * time.Millisecond)
}
}
/* Getters */
// GetMembers returns an array of peers with all the members in the ring through 'ret'.
func (altNode *Node) GetMembers(_ struct{}, ret *[]Peer) error {
var members []Peer
altNode.Members.RLock()
for current := altNode.Members.List.Front(); current != nil; current = current.Next() {
members = append(members, *getPeer(current))
}
altNode.Members.RUnlock()
*ret = members
return nil
}
// GetMemberHist returns the node's membership history through 'ret'.
func (altNode *Node) GetMemberHist(_ struct{}, ret *[]histEntry) error {
altNode.historyMutex.RLock()
*ret = altNode.memberHist
altNode.historyMutex.RUnlock()
return nil
}
// getSuccessor returns the successor of the node.
func (altNode *Node) getSuccessor() *Peer {
altNode.Members.RLock()
succElt := altNode.Members.Map[altNode.ID]
succElt = succElt.Next()
if succElt == nil {
succElt = altNode.Members.List.Front()
}
altNode.Members.RUnlock()
return getPeer(succElt)
}
// getListSuccessor is just like getSuccesor, but returns list element.
// Useful because the list element can be used to iterate through the ring.
func (altNode *Node) getListSuccessor() *list.Element {
altNode.Members.RLock()
succElt := altNode.Members.Map[altNode.ID]
succElt = succElt.Next()
if succElt == nil {
succElt = altNode.Members.List.Front()
}
altNode.Members.RUnlock()
return succElt
}
// getPredecessor returns the predecessor of the node.
func (altNode *Node) getPredecessor() *Peer {
altNode.Members.RLock()
predElt := altNode.Members.Map[altNode.ID]
predElt = predElt.Prev()
if predElt == nil {
predElt = altNode.Members.List.Back()
}
altNode.Members.RUnlock()
return getPeer(predElt)
}
// getNthSuccessor returns the nth successor of the node.
func (altNode *Node) getNthSuccessor(n int) *Peer {
altNode.Members.RLock()
current := altNode.Members.Map[altNode.ID]
for i := 0; i < n; i++ {
current = current.Next()
if current == nil {
current = altNode.Members.List.Front()
}
}
if current == nil {
current = altNode.Members.List.Front()
}
altNode.Members.RUnlock()
return getPeer(current)
}
// getNthPredecessor returns the nth predecessor of the node.
func (altNode *Node) getNthPredecessor(n int) *Peer {
altNode.Members.RLock()
current := altNode.Members.Map[altNode.ID]
for i := 0; i < n; i++ {
current = current.Prev()
if current == nil {
current = altNode.Members.List.Back()
}
}
if current == nil {
current = altNode.Members.List.Back()
}
altNode.Members.RUnlock()
return getPeer(current)
}
func (altNode *Node) string() (str string) {
str += "ID: " + altNode.ID.String() + "\n"
return
}
// selfExt returns an peerNode equivalent of altNode
func (altNode *Node) selfExt() Peer {
return Peer{ID: altNode.ID, Address: altNode.Address}
}
/* Misc */
// sigHandler catches signals sent to the node
func (altNode *Node) sigHandler() {
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, os.Interrupt, os.Kill)
for {
sig := <-sigChan
switch sig {
case os.Interrupt:
altNode.leaveRing()
case os.Kill:
os.Exit(1)
}
}
}