-
Notifications
You must be signed in to change notification settings - Fork 35
/
registry.go
565 lines (485 loc) · 11.7 KB
/
registry.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
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
package beehive
import (
"encoding/gob"
"errors"
"fmt"
"reflect"
"sync"
"github.com/kandoo/beehive/Godeps/_workspace/src/github.com/coreos/etcd/raft/raftpb"
"github.com/kandoo/beehive/Godeps/_workspace/src/github.com/golang/glog"
bhgob "github.com/kandoo/beehive/gob"
"github.com/kandoo/beehive/raft"
)
var (
ErrUnsupportedRequest = errors.New("registry: unsupported request")
ErrInvalidParam = errors.New("registry: invalid parameter")
ErrNoSuchHive = errors.New("registry: no such hive")
ErrDuplicateHive = errors.New("registry: duplicate hive")
ErrNoSuchBee = errors.New("registry: no such bee")
ErrDuplicateBee = errors.New("registry: duplicate bee")
)
// noOp is a barrier: a raft request to make sure all the updates are
// applied to store.
type noOp struct{}
// newHiveID is the registry request to create a unique 64-bit hive ID.
type newHiveID struct{}
// allocateBeeIDs is a registery request to allocate a range of bee IDs.
type allocateBeeIDs struct {
Len uint // Length of the range requested. Should not be zero.
}
// allocateBeeIDResult is the result of the allocateBeeIDs request.
//
// The allocated ID range is [From, To).
type allocateBeeIDResult struct {
From uint64
To uint64
}
// BeeInfo stores the metadata about a bee.
type BeeInfo struct {
ID uint64 `json:"id"`
Hive uint64 `json:"hive"`
App string `json:"app"`
Colony Colony `json:"colony"`
Detached bool `json:"detached"`
}
// addBee is a registery request to add a new bee.
type addBee BeeInfo
// delBee is a registery request to delete a bee.
type delBee uint64
// moveBee is a registery request to move a bee from a hive to another hive.
type moveBee struct {
ID uint64
FromHive uint64
ToHive uint64
}
// updateColony is a registery request to update a colony.
type updateColony struct {
Term uint64
Old Colony
New Colony
}
// lockMappedCell locks a mapped cell for a colony.
type lockMappedCell struct {
Colony Colony
App string
Cells MappedCells
}
// transferCells transfers cells of a colony to another colony.
type transferCells struct {
From Colony
To Colony
}
// batchReq is a batch of registery requests that should be processed in a
// seqeunce. The response to batch requests is batchRes.
//
// batchReq are not transactions. Each one of the requests is independently
// applied.
type batchReq struct {
Reqs []interface{}
}
// addReq adds a request to the batched request.
func (r *batchReq) addReq(req interface{}) {
r.Reqs = append(r.Reqs, req)
}
// batchRes is the response to a batch request.
type batchRes []struct {
Res interface{}
Err bhgob.Error
}
type registry struct {
m sync.RWMutex
name string
HiveID uint64
BeeID uint64
Hives map[uint64]HiveInfo
Bees map[uint64]BeeInfo
Store cellStore
}
func newRegistry(name string) *registry {
return ®istry{
name: name,
HiveID: 1, // To preserve the first hive's ID.
BeeID: hiveGroup + 1, // To avoid conflicting group IDs.
Hives: make(map[uint64]HiveInfo),
Bees: make(map[uint64]BeeInfo),
Store: newCellStore(),
}
}
func (r *registry) Save() ([]byte, error) {
r.m.RLock()
defer r.m.RUnlock()
glog.V(2).Info("registry saved")
return bhgob.Encode(r)
}
func (r *registry) Restore(b []byte) error {
r.m.Lock()
defer r.m.Unlock()
glog.V(2).Info("registry restored")
return bhgob.Decode(r, b)
}
func (r *registry) Apply(req interface{}) (interface{}, error) {
r.m.Lock()
defer r.m.Unlock()
return r.doApply(req)
}
func (r *registry) doApply(req interface{}) (interface{}, error) {
glog.V(2).Infof("%v applies: %#v", r, req)
switch req := req.(type) {
case noOp:
return nil, nil
case newHiveID:
return r.newHiveID(), nil
case allocateBeeIDs:
return r.allocBeeIDs(req)
case addBee:
return nil, r.addBee(BeeInfo(req))
case delBee:
return nil, r.delBee(uint64(req))
case moveBee:
return nil, r.moveBee(req)
case updateColony:
return nil, r.updateColony(req)
case lockMappedCell:
return r.lockCell(req)
case transferCells:
return nil, r.transfer(req)
case batchReq:
return r.handleBatch(req), nil
}
glog.Errorf("%v cannot handle %v", r, req)
return nil, ErrUnsupportedRequest
}
func (r *registry) String() string {
return fmt.Sprintf("registry for %v", r.name)
}
func (r *registry) ApplyConfChange(cc raftpb.ConfChange, gn raft.GroupNode) (
err error) {
r.m.Lock()
defer r.m.Unlock()
glog.V(2).Infof("%v applies conf change %#v for %v", r, cc, gn.Node)
switch cc.Type {
case raftpb.ConfChangeAddNode:
if gn.Node != cc.NodeID {
glog.Fatalf("invalid data in the config change: %v != %v", gn.Node,
cc.NodeID)
}
if gn.Data != nil {
hi := HiveInfo{
ID: gn.Node,
Addr: gn.Data.(string),
}
r.addHive(hi)
glog.V(2).Infof("%v adds hive %v@%v", r, hi.ID, hi.Addr)
}
case raftpb.ConfChangeRemoveNode:
r.delHive(cc.NodeID)
glog.V(2).Infof("%v deletes hive %v", r, cc.NodeID)
}
return nil
}
func (r *registry) newHiveID() uint64 {
r.HiveID++
glog.V(2).Infof("%v allocates new hive ID %v", r, r.HiveID)
return r.HiveID
}
func (r *registry) allocBeeIDs(a allocateBeeIDs) (allocateBeeIDResult, error) {
if a.Len == 0 {
return allocateBeeIDResult{}, ErrInvalidParam
}
var res allocateBeeIDResult
res.From = r.BeeID
r.BeeID += uint64(a.Len)
res.To = r.BeeID
glog.V(2).Infof("%v allocates new bee IDs up to %v", r, r.BeeID)
return res, nil
}
func (r *registry) delHive(id uint64) error {
if _, ok := r.Hives[id]; !ok {
return fmt.Errorf("no such hive %v", id)
}
delete(r.Hives, id)
return nil
}
func (r *registry) initHives(hives map[uint64]HiveInfo) error {
r.m.Lock()
defer r.m.Unlock()
for _, h := range hives {
if err := r.addHive(h); err != nil {
return err
}
}
return nil
}
func (r *registry) addHive(info HiveInfo) error {
glog.V(2).Infof("%v sets hive %v's address to %v", r, info.ID, info.Addr)
for _, h := range r.Hives {
if h.Addr == info.Addr && h.ID != info.ID {
return fmt.Errorf("%v has duplicate address %v for hives %v and %v", r,
info.Addr, info.ID, h.ID)
}
}
r.Hives[info.ID] = info
return nil
}
func (r *registry) addBee(info BeeInfo) error {
glog.V(2).Infof("%v add bee %v (detached=%v) for %v with %v,", r, info.ID,
info.Detached, info.App, info.Colony)
if info.ID == Nil {
glog.Fatalf("invalid bee info: %v", info)
}
if i, ok := r.Bees[info.ID]; ok {
if !reflect.DeepEqual(info, i) {
return ErrDuplicateBee
}
}
if r.BeeID < info.ID {
glog.Fatalf("%v has invalid bee ID: %v < %v", r, info.ID, r.HiveID)
}
r.Bees[info.ID] = info
return nil
}
func (r *registry) delBee(id uint64) error {
glog.V(2).Infof("%v removes bee %v", r, id)
if _, ok := r.Bees[id]; !ok {
return ErrNoSuchBee
}
delete(r.Bees, id)
return nil
}
func (r *registry) moveBee(m moveBee) error {
b, ok := r.Bees[m.ID]
if !ok {
return ErrNoSuchBee
}
if b.Hive != m.FromHive {
return ErrInvalidParam
}
if m.FromHive == m.ToHive {
return nil
}
b.Hive = m.ToHive
r.Bees[m.ID] = b
return nil
}
func (r *registry) updateColony(up updateColony) error {
if up.New.IsNil() || up.Old.IsNil() {
return ErrInvalidParam
}
glog.V(2).Infof("%v updates %v with %v", r, up.Old, up.New)
b := r.mustFindBee(up.New.Leader)
if err := r.Store.updateColony(b.App, up.Old, up.New, up.Term); err != nil {
return err
}
if up.Old.Leader != up.New.Leader {
b = r.mustFindBee(up.Old.Leader)
if up.New.Contains(up.Old.Leader) {
b.Colony = up.New
} else {
b.Colony = Colony{}
}
r.Bees[up.Old.Leader] = b
}
for _, f := range up.Old.Followers {
if !up.New.Contains(f) {
b = r.mustFindBee(f)
b.Colony = Colony{}
r.Bees[f] = b
}
}
for _, f := range up.New.Followers {
b = r.mustFindBee(f)
b.Colony = up.New
r.Bees[f] = b
}
b = r.mustFindBee(up.New.Leader)
b.Colony = up.New
r.Bees[up.New.Leader] = b
return nil
}
func (r *registry) mustFindBee(id uint64) BeeInfo {
info, ok := r.Bees[id]
if !ok {
glog.Fatalf("cannot find bee %v", id)
}
return info
}
func (r *registry) lockCell(l lockMappedCell) (Colony, error) {
if l.Colony.Leader == 0 {
return Colony{}, ErrInvalidParam
}
locked := false
openk := make(MappedCells, 0, 10)
for _, k := range l.Cells {
c, ok := r.Store.colony(l.App, k)
if !ok {
if locked {
r.Store.assign(l.App, k, l.Colony)
} else {
openk = append(openk, k)
}
continue
}
if locked && !c.Equals(l.Colony) {
// FIXME(soheil): Fix this bug after refactoring the code.
glog.Fatal("TODO registery conflict between colonies")
}
locked = true
l.Colony = c
}
if locked {
for _, k := range openk {
r.Store.assign(l.App, k, l.Colony)
}
return l.Colony, nil
}
for _, k := range l.Cells {
r.Store.assign(l.App, k, l.Colony)
}
return l.Colony, nil
}
func (r *registry) transfer(t transferCells) error {
i, ok := r.Bees[t.From.Leader]
if !ok {
return ErrNoSuchBee
}
keys := r.Store.cells(t.From.Leader)
if len(keys) == 0 {
return ErrInvalidParam
}
for _, k := range keys {
r.Store.assign(i.App, k, t.To)
}
return nil
}
func (r *registry) hives() []HiveInfo {
r.m.RLock()
hives := make([]HiveInfo, 0, len(r.Hives))
for _, h := range r.Hives {
hives = append(hives, h)
}
r.m.RUnlock()
return hives
}
func (r *registry) hive(id uint64) (HiveInfo, error) {
r.m.RLock()
i, ok := r.Hives[id]
r.m.RUnlock()
if !ok {
return i, ErrNoSuchHive
}
return i, nil
}
func (r *registry) bees() []BeeInfo {
r.m.RLock()
bees := make([]BeeInfo, 0, len(r.Bees))
for _, b := range r.Bees {
bees = append(bees, b)
}
r.m.RUnlock()
return bees
}
func (r *registry) beesOfHive(id uint64) []BeeInfo {
r.m.RLock()
var bees []BeeInfo
for _, b := range r.Bees {
if b.Hive == id {
bees = append(bees, b)
}
}
r.m.RUnlock()
return bees
}
func (r *registry) bee(id uint64) (BeeInfo, error) {
r.m.RLock()
i, ok := r.Bees[id]
r.m.RUnlock()
if !ok {
return i, ErrNoSuchBee
}
return i, nil
}
func (r *registry) beeAndHive(id uint64) (BeeInfo, HiveInfo, error) {
r.m.RLock()
defer r.m.RUnlock()
bi, ok := r.Bees[id]
if !ok {
return bi, HiveInfo{}, ErrNoSuchBee
}
if bi.ID != id {
glog.Fatalf("bee %v has invalid info: %#v", id, bi)
}
hi, ok := r.Hives[bi.Hive]
if !ok {
return bi, hi, ErrNoSuchHive
}
return bi, hi, nil
}
func (r *registry) beeForCells(app string, cells MappedCells) (info BeeInfo,
hasAll bool, err error) {
r.m.RLock()
defer r.m.RUnlock()
hasAll = true
for _, k := range cells {
col, ok := r.Store.colony(app, k)
if !ok {
hasAll = false
continue
}
if info.ID == 0 {
info = r.Bees[col.Leader]
if info.ID != col.Leader {
glog.Fatalf("bee %b has an invalid info %#v", col.Leader, info)
}
} else if info.ID != col.Leader {
// Incosistencies should be handled by consensus.
hasAll = false
}
if !hasAll {
return info, hasAll, nil
}
}
if info.ID == 0 {
return info, hasAll, ErrNoSuchBee
}
return info, hasAll, nil
}
func (r *registry) handleBatch(bReq batchReq) batchRes {
bRes := make(batchRes, 0, len(bReq.Reqs))
for _, req := range bReq.Reqs {
res, err := r.doApply(req)
bRes = append(bRes, struct {
Res interface{}
Err bhgob.Error
}{
Res: res,
Err: bhgob.NewError(err),
})
}
return bRes
}
func (r *registry) ProcessStatusChange(sch interface{}) {
switch ev := sch.(type) {
case raft.LeaderChanged:
if ev.New != r.HiveID {
return
}
glog.V(2).Infof("hive %v is the new leader", r.HiveID)
}
}
func init() {
gob.Register(BeeInfo{})
gob.Register(HiveInfo{})
gob.Register([]HiveInfo{})
gob.Register(addBee{})
gob.Register(allocateBeeIDResult{})
gob.Register(allocateBeeIDs{})
gob.Register(batchReq{})
gob.Register(batchRes{})
gob.Register(cellStore{})
gob.Register(delBee(0))
gob.Register(lockMappedCell{})
gob.Register(newHiveID{})
gob.Register(noOp{})
gob.Register(transferCells{})
gob.Register(updateColony{})
}