forked from dgraph-io/dgraph
-
Notifications
You must be signed in to change notification settings - Fork 1
/
draft.go
722 lines (643 loc) · 19.1 KB
/
draft.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
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
/*
* Copyright (C) 2017 Dgraph Labs, Inc. and Contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package worker
import (
"encoding/binary"
"log"
"math/rand"
"sync"
"time"
"github.com/coreos/etcd/raft"
"github.com/coreos/etcd/raft/raftpb"
"golang.org/x/net/context"
"golang.org/x/net/trace"
"github.com/dgraph-io/badger/y"
"gopkg.in/adibiarsotp/dgraph.v82/algo"
"gopkg.in/adibiarsotp/dgraph.v82/conn"
"gopkg.in/adibiarsotp/dgraph.v82/posting"
"gopkg.in/adibiarsotp/dgraph.v82/protos"
"gopkg.in/adibiarsotp/dgraph.v82/raftwal"
"gopkg.in/adibiarsotp/dgraph.v82/schema"
"gopkg.in/adibiarsotp/dgraph.v82/x"
)
const (
errorNodeIDExists = "Error Node ID already exists in the cluster"
)
type proposalCtx struct {
ch chan error
ctx context.Context
cnt int // used for reference counting
// Since each proposal consists of multiple tasks we need to store
// non-nil error returned by task
err error
index uint64
n *node
}
type proposals struct {
sync.RWMutex
ids map[uint32]*proposalCtx
}
func (p *proposals) Store(pid uint32, pctx *proposalCtx) bool {
p.Lock()
defer p.Unlock()
if _, has := p.ids[pid]; has {
return false
}
p.ids[pid] = pctx
return true
}
func (p *proposals) SetIndex(pid uint32, index uint64) {
p.Lock()
defer p.Unlock()
pd, has := p.ids[pid]
x.AssertTrue(has)
pd.index = index
pd.cnt = 1
return
}
func (p *proposals) IncRef(pid uint32, count int) {
p.Lock()
defer p.Unlock()
pd, has := p.ids[pid]
x.AssertTrue(has)
pd.cnt += count
return
}
func (p *proposals) Ctx(pid uint32) (context.Context, bool) {
p.RLock()
defer p.RUnlock()
if pd, has := p.ids[pid]; has {
return pd.ctx, true
}
return nil, false
}
func (p *proposals) Done(pid uint32, err error) {
p.Lock()
defer p.Unlock()
pd, has := p.ids[pid]
if !has {
return
}
x.AssertTrue(pd.cnt > 0 && pd.index != 0)
pd.cnt -= 1
if err != nil {
pd.err = err
}
if pd.cnt > 0 {
return
}
delete(p.ids, pid)
pd.ch <- pd.err
// We emit one pending watermark as soon as we read from rd.committedentries.
// Since the tasks are executed in goroutines we need one guarding watermark which
// is done only when all the pending sync/applied marks have been emitted.
pd.n.Applied.Done(pd.index)
posting.SyncMarks().Done(pd.index)
}
func (p *proposals) Has(pid uint32) bool {
p.RLock()
defer p.RUnlock()
_, has := p.ids[pid]
return has
}
type node struct {
*conn.Node
// Fields which are never changed after init.
applyCh chan raftpb.Entry
ctx context.Context
stop chan struct{} // to send the stop signal to Run
done chan struct{} // to check whether node is running or not
gid uint32
props proposals
canCampaign bool
sch *scheduler
}
func newNode(gid uint32, id uint64, myAddr string) *node {
x.Printf("Node ID: %v with GroupID: %v\n", id, gid)
rc := &protos.RaftContext{
Addr: myAddr,
Group: gid,
Id: id,
}
m := conn.NewNode(rc)
props := proposals{
ids: make(map[uint32]*proposalCtx),
}
n := &node{
Node: m,
ctx: context.Background(),
gid: gid,
// processConfChange etc are not throttled so some extra delta, so that we don't
// block tick when applyCh is full
applyCh: make(chan raftpb.Entry, Config.NumPendingProposals+1000),
props: props,
stop: make(chan struct{}),
done: make(chan struct{}),
sch: new(scheduler),
}
n.sch.init(n)
return n
}
type header struct {
proposalId uint32
msgId uint16
}
func (h *header) Length() int {
return 6 // 4 bytes for proposalId, 2 bytes for msgId.
}
func (h *header) Encode() []byte {
result := make([]byte, h.Length())
binary.LittleEndian.PutUint32(result[0:4], h.proposalId)
binary.LittleEndian.PutUint16(result[4:6], h.msgId)
return result
}
func (h *header) Decode(in []byte) {
h.proposalId = binary.LittleEndian.Uint32(in[0:4])
h.msgId = binary.LittleEndian.Uint16(in[4:6])
}
func (n *node) ProposeAndWait(ctx context.Context, proposal *protos.Proposal) error {
if n.Raft() == nil {
return x.Errorf("RAFT isn't initialized yet")
}
// TODO: Should be based on number of edges (amount of work)
pendingProposals <- struct{}{}
x.PendingProposals.Add(1)
defer func() { <-pendingProposals; x.PendingProposals.Add(-1) }()
if ctx.Err() != nil {
return ctx.Err()
}
// Do a type check here if schema is present
// In very rare cases invalid entries might pass through raft, which would
// be persisted, we do best effort schema check while writing
if proposal.Mutations != nil {
for _, edge := range proposal.Mutations.Edges {
if tablet := groups().Tablet(edge.Attr); tablet != nil && tablet.ReadOnly {
return errPredicateMoving
}
if typ, err := schema.State().TypeOf(edge.Attr); err != nil {
continue
} else if err := ValidateAndConvert(edge, typ); err != nil {
return err
}
}
for _, schema := range proposal.Mutations.Schema {
if tablet := groups().Tablet(schema.Predicate); tablet != nil && tablet.ReadOnly {
return errPredicateMoving
}
if err := checkSchema(schema); err != nil {
return err
}
}
}
che := make(chan error, 1)
pctx := &proposalCtx{
ch: che,
ctx: ctx,
n: n,
}
for {
id := rand.Uint32()
if n.props.Store(id, pctx) {
proposal.Id = id
break
}
}
sz := proposal.Size()
slice := make([]byte, sz)
upto, err := proposal.MarshalTo(slice)
if err != nil {
return err
}
// We don't timeout on a mutation which has already been proposed.
if err = n.Raft().Propose(ctx, slice[:upto]); err != nil {
return x.Wrapf(err, "While proposing")
}
// Wait for the proposal to be committed.
if proposal.Mutations != nil {
if tr, ok := trace.FromContext(ctx); ok {
tr.LazyPrintf("Waiting for the proposal: mutations.")
}
} else if len(proposal.Kv) > 0 {
if tr, ok := trace.FromContext(ctx); ok {
tr.LazyPrintf("Waiting for the proposal: key-values.")
}
} else {
if tr, ok := trace.FromContext(ctx); ok {
tr.LazyPrintf("Waiting for the proposal: %v.", proposal)
}
}
err = <-che
if err != nil {
if tr, ok := trace.FromContext(ctx); ok {
tr.LazyPrintf(err.Error())
}
}
return err
}
func (n *node) handleUpsert(task *task) (bool, error) {
if task.upsert == nil {
return true, nil
}
edge := task.edge
attr := task.upsert.Attr
if attr != edge.Attr {
return true, nil
}
gid := groups().BelongsTo(attr)
res, err := n.processUpsertTask(n.ctx, task, gid)
if err != nil {
return false, err
}
uids := algo.MergeSorted(res.UidMatrix)
if len(uids.Uids) > 0 {
return false, nil
}
return true, nil
}
func (n *node) processMutation(task *task) error {
pid := task.pid
ridx := task.rid
edge := task.edge
if cont, err := n.handleUpsert(task); err != nil {
return err
} else if !cont {
// We found a uid which has this value, so don't continue.
return nil
}
var ctx context.Context
var has bool
if ctx, has = n.props.Ctx(pid); !has {
ctx = n.ctx
}
rv := x.RaftValue{Group: n.gid, Index: ridx}
ctx = context.WithValue(ctx, "raft", rv)
if err := runMutation(ctx, edge); err != nil {
if tr, ok := trace.FromContext(ctx); ok {
tr.LazyPrintf(err.Error())
}
return err
}
return nil
}
func (n *node) processSchemaMutations(pid uint32, index uint64, s *protos.SchemaUpdate) error {
var ctx context.Context
var has bool
if ctx, has = n.props.Ctx(pid); !has {
ctx = n.ctx
}
rv := x.RaftValue{Group: n.gid, Index: index}
ctx = context.WithValue(n.ctx, "raft", rv)
if err := runSchemaMutation(ctx, s); err != nil {
if tr, ok := trace.FromContext(n.ctx); ok {
tr.LazyPrintf(err.Error())
}
return err
}
return nil
}
const numPendingMutations = 10000
func (n *node) applyConfChange(e raftpb.Entry) {
var cc raftpb.ConfChange
cc.Unmarshal(e.Data)
if len(cc.Context) > 0 {
var rc protos.RaftContext
x.Check(rc.Unmarshal(cc.Context))
n.Connect(rc.Id, rc.Addr)
}
cs := n.Raft().ApplyConfChange(cc)
n.SetConfState(cs)
// Not present in proposal map
n.Applied.Done(e.Index)
posting.SyncMarks().Done(e.Index)
groups().triggerMembershipSync()
}
func (n *node) processApplyCh() {
for e := range n.applyCh {
if len(e.Data) == 0 {
// This is not in the proposal map
n.Applied.Done(e.Index)
posting.SyncMarks().Done(e.Index)
continue
}
if e.Type == raftpb.EntryConfChange {
n.applyConfChange(e)
continue
}
x.AssertTrue(e.Type == raftpb.EntryNormal)
proposal := &protos.Proposal{}
if err := proposal.Unmarshal(e.Data); err != nil {
log.Fatalf("Unable to unmarshal proposal: %v %q\n", err, e.Data)
}
// One final applied and synced watermark would be emitted when proposal ctx ref count
// becomes zero.
if !n.props.Has(proposal.Id) {
pctx := &proposalCtx{
ch: make(chan error, 1),
ctx: n.ctx,
n: n,
index: e.Index,
cnt: 1,
}
n.props.Store(proposal.Id, pctx)
} else {
n.props.SetIndex(proposal.Id, e.Index)
}
if proposal.Mutations != nil {
n.sch.schedule(proposal, e.Index)
} else if proposal.Membership != nil {
x.Fatalf("Dgraph does not handle membership proposals anymore.")
} else if len(proposal.Kv) > 0 {
go n.processKeyValues(e.Index, proposal.Id, proposal.Kv)
} else if proposal.State != nil {
// This state needn't be snapshotted in this group, on restart we would fetch
// a state which is latest or equal to this.
groups().applyState(proposal.State)
// When proposal is done it emits done watermarks.
n.props.Done(proposal.Id, nil)
} else {
x.Fatalf("Unknown proposal")
}
}
}
func (n *node) processKeyValues(index uint64, pid uint32, kvs []*protos.KV) error {
ctx, _ := n.props.Ctx(pid)
err := populateKeyValues(ctx, kvs)
n.props.Done(pid, err)
return nil
}
func (n *node) retrieveSnapshot(peerID uint64) {
addr, _ := n.Peer(peerID)
pool, err := conn.Get().Get(addr)
if err != nil {
// err is just going to be errNoConnection
log.Fatalf("Cannot retrieve snapshot from peer %v, no connection. Error: %v\n",
peerID, err)
}
// Get index of last committed.
lastIndex, err := n.Store.LastIndex()
x.Checkf(err, "Error while getting last index")
// Wait for watermarks to sync since populateShard writes directly to db, otherwise
// the values might get overwritten
// Safe to keep this line
n.syncAllMarks(n.ctx, lastIndex)
// Need to clear pl's stored in memory for the case when retrieving snapshot with
// index greater than this node's last index
// Should invalidate/remove pl's to this group only ideally
posting.EvictLRU()
if _, err := populateShard(n.ctx, pstore, pool, n.gid); err != nil {
// TODO: We definitely don't want to just fall flat on our face if we can't
// retrieve a simple snapshot.
log.Fatalf("Cannot retrieve snapshot from peer %v, error: %v\n", peerID, err)
}
// Populate shard stores the streamed data directly into db, so we need to refresh
// schema for current group id
x.Checkf(schema.LoadFromDb(), "Error while initilizating schema")
groups().triggerMembershipSync()
}
func (n *node) Run() {
firstRun := true
var leader bool
// See also our configuration of HeartbeatTick and ElectionTick.
ticker := time.NewTicker(20 * time.Millisecond)
defer ticker.Stop()
rcBytes, err := n.RaftContext.Marshal()
x.Check(err)
// This chan could have capacity zero, because runReadIndexLoop never blocks without selecting
// on readStateCh. It's 2 so that sending rarely blocks (so the Go runtime doesn't have to
// switch threads as much.)
readStateCh := make(chan raft.ReadState, 2)
closer := y.NewCloser(1)
// We only stop runReadIndexLoop after the for loop below has finished interacting with it.
// That way we know sending to readStateCh will not deadlock.
defer closer.SignalAndWait()
go n.RunReadIndexLoop(closer, readStateCh)
for {
select {
case <-ticker.C:
n.Raft().Tick()
case rd := <-n.Raft().Ready():
for _, rs := range rd.ReadStates {
readStateCh <- rs
}
if rd.SoftState != nil {
groups().triggerMembershipSync()
leader = rd.RaftState == raft.StateLeader
}
if leader {
// Leader can send messages in parallel with writing to disk.
for _, msg := range rd.Messages {
// NOTE: We can do some optimizations here to drop messages.
msg.Context = rcBytes
n.Send(msg)
}
}
// First store the entries, then the hardstate and snapshot.
x.Check(n.Wal.Store(n.gid, rd.HardState, rd.Entries))
x.Check(n.Wal.StoreSnapshot(n.gid, rd.Snapshot))
// Now store them in the in-memory store.
n.SaveToStorage(rd.Snapshot, rd.HardState, rd.Entries)
if !raft.IsEmptySnap(rd.Snapshot) {
// We don't send snapshots to other nodes. But, if we get one, that means
// either the leader is trying to bring us up to state; or this is the
// snapshot that I created. Only the former case should be handled.
var rc protos.RaftContext
x.Check(rc.Unmarshal(rd.Snapshot.Data))
x.AssertTrue(rc.Group == n.gid)
if rc.Id != n.Id {
// NOTE: Retrieving snapshot here is OK, after storing it above in WAL, because
// rc.Id != n.Id.
x.Printf("-------> SNAPSHOT [%d] from %d\n", n.gid, rc.Id)
// It's ok to block tick while retrieving snapshot, since it's a follower
n.retrieveSnapshot(rc.Id)
x.Printf("-------> SNAPSHOT [%d]. DONE.\n", n.gid)
} else {
x.Printf("-------> SNAPSHOT [%d] from %d [SELF]. Ignoring.\n", n.gid, rc.Id)
}
}
if len(rd.CommittedEntries) > 0 {
if tr, ok := trace.FromContext(n.ctx); ok {
tr.LazyPrintf("Found %d committed entries", len(rd.CommittedEntries))
}
}
// Now schedule or apply committed entries.
for _, entry := range rd.CommittedEntries {
// Need applied watermarks for schema mutation also for read linearazibility
// Applied watermarks needs to be emitted as soon as possible sequentially.
// If we emit Mark{4, false} and Mark{4, true} before emitting Mark{3, false}
// then doneUntil would be set as 4 as soon as Mark{4,true} is done and before
// Mark{3, false} is emitted. So it's safer to emit watermarks as soon as
// possible sequentially
n.Applied.Begin(entry.Index)
posting.SyncMarks().Begin(entry.Index)
if !leader && entry.Type == raftpb.EntryConfChange {
// Config changes in followers must be applied straight away.
n.applyConfChange(entry)
} else {
// TODO: Stop accepting requests when applyCh is full
// Just queue up to be processed. Don't wait on them.
n.applyCh <- entry
}
}
if !leader {
// Followers should send messages later.
for _, msg := range rd.Messages {
// NOTE: We can do some optimizations here to drop messages.
msg.Context = rcBytes
n.Send(msg)
}
}
n.Raft().Advance()
if firstRun && n.canCampaign {
go n.Raft().Campaign(n.ctx)
firstRun = false
}
case <-n.stop:
if peerId, has := groups().MyPeer(); has && n.AmLeader() {
n.Raft().TransferLeadership(n.ctx, Config.RaftId, peerId)
go func() {
select {
case <-n.ctx.Done(): // time out
if tr, ok := trace.FromContext(n.ctx); ok {
tr.LazyPrintf("context timed out while transfering leadership")
}
case <-time.After(1 * time.Second):
if tr, ok := trace.FromContext(n.ctx); ok {
tr.LazyPrintf("Timed out transfering leadership")
}
}
n.Raft().Stop()
close(n.done)
}()
} else {
n.Raft().Stop()
close(n.done)
}
case <-n.done:
return
}
}
}
func (n *node) Stop() {
select {
case n.stop <- struct{}{}:
case <-n.done:
// already stopped.
return
}
<-n.done // wait for Run to respond.
}
func (n *node) snapshotPeriodically() {
if n.gid == 0 {
// Group zero is dedicated for membership information, whose state we don't persist.
// So, taking snapshots would end up deleting the RAFT entries that we need to
// regenerate the state on a crash. Therefore, don't take snapshots.
return
}
ticker := time.NewTicker(time.Minute)
defer ticker.Stop()
for {
select {
case <-ticker.C:
n.snapshot(Config.MaxPendingCount)
case <-n.done:
return
}
}
}
func (n *node) snapshot(skip uint64) {
if n.gid == 0 {
// Group zero is dedicated for membership information, whose state we don't persist.
// So, taking snapshots would end up deleting the RAFT entries that we need to
// regenerate the state on a crash. Therefore, don't take snapshots.
return
}
water := posting.SyncMarks()
le := water.DoneUntil()
existing, err := n.Store.Snapshot()
x.Checkf(err, "Unable to get existing snapshot")
si := existing.Metadata.Index
if le <= si+skip {
return
}
snapshotIdx := le - skip
if tr, ok := trace.FromContext(n.ctx); ok {
tr.LazyPrintf("Taking snapshot for group: %d at watermark: %d\n", n.gid, snapshotIdx)
}
rc, err := n.RaftContext.Marshal()
x.Check(err)
s, err := n.Store.CreateSnapshot(snapshotIdx, n.ConfState(), rc)
x.Checkf(err, "While creating snapshot")
x.Checkf(n.Store.Compact(snapshotIdx), "While compacting snapshot")
x.Check(n.Wal.StoreSnapshot(n.gid, s))
}
func (n *node) joinPeers() {
// Get leader information for MY group.
pl := groups().Leader(n.gid)
if pl == nil {
log.Fatalf("Unable to reach leader or any other server in group %d", n.gid)
}
// Bring the instance up to speed first.
// Raft would decide whether snapshot needs to fetched or not
// so populateShard is not needed
// _, err := populateShard(n.ctx, pool, n.gid)
// x.Checkf(err, "Error while populating shard")
gconn := pl.Get()
c := protos.NewRaftClient(gconn)
x.Printf("Calling JoinCluster")
_, err := c.JoinCluster(n.ctx, n.RaftContext)
// TODO: This should keep on indefinitely trying to join the cluster, instead of crashing.
x.Checkf(err, "Error while joining cluster")
x.Printf("Done with JoinCluster call\n")
}
// InitAndStartNode gets called after having at least one membership sync with the cluster.
func (n *node) InitAndStartNode(wal *raftwal.Wal) {
idx, restart, err := n.InitFromWal(wal)
x.Check(err)
n.Applied.SetDoneUntil(idx)
posting.SyncMarks().SetDoneUntil(idx)
if restart {
x.Printf("Restarting node for group: %d\n", n.gid)
found := groups().HasMeInState()
_, hasPeer := groups().MyPeer()
if !found && hasPeer {
n.joinPeers()
}
n.SetRaft(raft.RestartNode(n.Cfg))
} else {
x.Printf("New Node for group: %d\n", n.gid)
if _, hasPeer := groups().MyPeer(); hasPeer {
n.joinPeers()
n.SetRaft(raft.StartNode(n.Cfg, nil))
} else {
peers := []raft.Peer{{ID: n.Id}}
n.SetRaft(raft.StartNode(n.Cfg, peers))
// Trigger election, so this node can become the leader of this single-node cluster.
n.canCampaign = true
}
}
go n.processApplyCh()
go n.Run()
go n.snapshotPeriodically()
go n.BatchAndSendMessages()
}
func (n *node) AmLeader() bool {
if n.Raft() == nil {
return false
}
r := n.Raft()
return r.Status().Lead == r.Status().ID
}