forked from influxdata/influxdb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
log.go
1994 lines (1677 loc) · 47.1 KB
/
log.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
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package raft
import (
"bytes"
"encoding/binary"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"log"
"math/rand"
"net/http"
"net/url"
"os"
"path/filepath"
"runtime/debug"
"sort"
"strconv"
"strings"
"sync"
"time"
)
// FSM represents the state machine that the log is applied to.
// The FSM must maintain the highest index that it has seen.
type FSM interface {
// These implement the snapshot and restore.
io.WriterTo
io.ReaderFrom
// Executes a log entry against the state machine.
// Non-repeatable errors such as system and disk errors must panic.
Apply(*LogEntry) error
// Returns the applied index saved to the state machine.
Index() uint64
}
const logEntryHeaderSize = 8 + 8 + 8 // sz+index+term
// WaitInterval represents the amount of time between checks to the applied index.
// This is used by clients wanting to wait until a given index is processed.
const WaitInterval = 1 * time.Millisecond
// State represents whether the log is a follower, candidate, or leader.
type State int
// String returns the string representation of the state.
func (s State) String() string {
switch s {
case Stopped:
return "stopped"
case Follower:
return "follower"
case Candidate:
return "candidate"
case Leader:
return "leader"
}
return "unknown"
}
const (
Stopped State = iota
Follower
Candidate
Leader
)
// Log represents a replicated log of commands based on the Raft protocol.
//
// The log can exist in one of four states that transition based on the following rules:
//
// ┌───────────┐
// ┌─▶│ Stopped │
// │ └───────────┘
// │ │
// │ ▼
// │ ┌───────────┐
// ├──│ Follower │◀─┐
// │ └───────────┘ │
// close │ │ │
// log │ ▼ │
// │ ┌───────────┐ │
// ├──│ Candidate │──┤ higher
// │ └───────────┘ │ term
// │ │ │
// │ ▼ │
// │ ┌───────────┐ │
// └──│ Leader │──┘
// └───────────┘
//
// - Stopped moves to Follower when initialized or joined.
// - Follower moves to Candidate after election timeout.
// - Candidate moves to Leader after a quorum of votes.
// - Leader or Candidate moves to Follower if higher term seen.
// - Any state moves to Stopped if log is closed.
type Log struct {
mu sync.Mutex
// The directory where the id, term and config are written to.
path string
// The log identifier. This is set when the log initializes
// or when the log joins to another cluster.
id uint64
// Config stores all nodes in the cluster.
config *Config
// The ID of the current leader.
leaderID uint64
// Current state of the log.
// The transitioning channel is closed whenever state is changed.
state State
transitioning chan struct{}
// In-memory log entries.
// Followers replicate these entries from the Leader.
// Leader appends to the end of these entries.
// Truncated and trimmed as needed.
entries []*LogEntry
// Highest term & index in the log.
// These are initialially read from the id/term files but otherwise
// should always match the index/term of the last 'entries' element.
lastLogTerm uint64
lastLogIndex uint64
// Highest entry to be committed.
// An entry can be committed once a quorum of nodes have received the entry.
// Because streaming raft asyncronously replicates entries, the lastLogIndex
// may be lower than the commitIndex. The commitIndex is always higher than
// or equal to the FSM.Index().
commitIndex uint64
// The current term the log is in. This increases when the log starts a
// new election term or when the log sees a higher election term.
term uint64
// The node this log voted for in the current term.
votedFor uint64
// Incoming stream from the leader.
// This is disconnected when the leader is deposed or the log changes state.
reader io.ReadCloser
// Outgoing streams to the followers to replicate the log.
// These are closed when the leader is deposed.
writers []*logWriter // outgoing streams to followers
// Incoming heartbeats and term changes go to these channels
// and are picked up by the current state.
heartbeats chan heartbeat
terms chan uint64
// Close notification and wait.
wg sync.WaitGroup
closing chan struct{}
// Network address to the reach the log.
url url.URL
// The state machine that log entries will be applied to.
FSM FSM
// The transport used to communicate with other nodes in the cluster.
Transport interface {
Join(u url.URL, nodeURL url.URL) (id uint64, leaderID uint64, config *Config, err error)
Leave(u url.URL, id uint64) error
Heartbeat(u url.URL, term, commitIndex, leaderID uint64) (lastIndex uint64, err error)
ReadFrom(u url.URL, id, term, index uint64) (io.ReadCloser, error)
RequestVote(u url.URL, term, candidateID, lastLogIndex, lastLogTerm uint64) (peerTerm uint64, err error)
}
// Clock is an abstraction of time.
Clock interface {
Now() time.Time
AfterApplyInterval() <-chan chan struct{}
AfterElectionTimeout() <-chan chan struct{}
AfterHeartbeatInterval() <-chan chan struct{}
AfterReconnectTimeout() <-chan chan struct{}
}
// Rand returns a random number.
Rand func() int64
// Sets whether trace messages are logged.
DebugEnabled bool
// This logs some asynchronous errors that occur within the log.
Logger *log.Logger
}
// NewLog creates a new instance of Log with reasonable defaults.
func NewLog() *Log {
l := &Log{
Clock: NewClock(),
Transport: &HTTPTransport{},
Rand: rand.NewSource(time.Now().UnixNano()).Int63,
heartbeats: make(chan heartbeat, 10),
terms: make(chan uint64, 10),
Logger: log.New(os.Stderr, "[raft] ", log.LstdFlags),
}
l.updateLogPrefix()
return l
}
// Path returns the data path of the Raft log.
// Returns an empty string if the log is closed.
func (l *Log) Path() string {
l.mu.Lock()
defer l.mu.Unlock()
return l.path
}
// URL returns the URL for the log.
func (l *Log) URL() url.URL {
l.mu.Lock()
defer l.mu.Unlock()
return l.url
}
// SetURL sets the URL for the log. This must be set before opening.
func (l *Log) SetURL(u url.URL) {
l.mu.Lock()
defer l.mu.Unlock()
assert(!l.opened(), "url cannot be set while log is open")
l.url = u
}
// URLs returns a list of all URLs in the cluster.
func (l *Log) URLs() []url.URL {
l.mu.Lock()
defer l.mu.Unlock()
if l.config == nil {
return nil
}
var a []url.URL
for _, n := range l.config.Nodes {
a = append(a, n.URL)
}
return a
}
func (l *Log) idPath() string { return filepath.Join(l.path, "id") }
func (l *Log) termPath() string { return filepath.Join(l.path, "term") }
func (l *Log) configPath() string { return filepath.Join(l.path, "config") }
// Opened returns true if the log is currently open.
func (l *Log) Opened() bool {
l.mu.Lock()
defer l.mu.Unlock()
return l.opened()
}
func (l *Log) opened() bool { return l.path != "" }
// ID returns the log's identifier.
func (l *Log) ID() uint64 {
l.mu.Lock()
defer l.mu.Unlock()
return l.id
}
// State returns the current state.
func (l *Log) State() State {
l.mu.Lock()
defer l.mu.Unlock()
return l.state
}
// LastLogIndexTerm returns the last index & term from the log.
func (l *Log) LastLogIndexTerm() (index, term uint64) {
l.mu.Lock()
defer l.mu.Unlock()
return l.lastLogIndex, l.lastLogTerm
}
// CommtIndex returns the highest committed index.
func (l *Log) CommitIndex() uint64 {
l.mu.Lock()
defer l.mu.Unlock()
return l.commitIndex
}
// Term returns the current term.
func (l *Log) Term() uint64 {
l.mu.Lock()
defer l.mu.Unlock()
return l.term
}
// Config returns a the log's current configuration.
func (l *Log) Config() *Config {
l.mu.Lock()
defer l.mu.Unlock()
if l.config != nil {
return l.config.Clone()
}
return nil
}
// Open initializes the log from a path.
// If the path does not exist then it is created.
func (l *Log) Open(path string) error {
var closing chan struct{}
var config *Config
if err := func() error {
l.mu.Lock()
defer l.mu.Unlock()
// Validate initial log state.
if l.opened() {
return ErrOpen
}
// Create directory, if not exists.
if err := os.MkdirAll(path, 0755); err != nil {
return err
}
l.path = path
// Initialize log identifier.
id, err := l.readID()
if err != nil {
return fmt.Errorf("read id: %s", err)
}
l.setID(id)
// Initialize log term.
term, err := l.readTerm()
if err != nil {
return fmt.Errorf("read term: %s", err)
}
l.term = term
l.votedFor = 0
l.lastLogTerm = term
// Read config.
c, err := l.readConfig()
if err != nil {
return fmt.Errorf("read config: %s", err)
}
l.config = c
// Determine last applied index from FSM.
index := l.FSM.Index()
l.tracef("Open: fsm: index=%d", index)
l.lastLogIndex = index
l.commitIndex = index
// Start goroutine to apply logs.
l.wg.Add(1)
l.closing = make(chan struct{})
go l.applier(l.closing)
if l.config != nil {
l.Logger.Printf("log open: created at %s, with ID %d, term %d, last applied index of %d", path, l.id, l.term, l.lastLogIndex)
}
// Retrieve variables to use while starting state loop.
config = l.config
closing = l.closing
return nil
}(); err == ErrOpen {
return err
} else if err != nil {
_ = l.close()
return err
}
// If a log exists then start the state loop.
if config != nil {
// If the config only has one node then start it as the leader.
// Otherwise start as a follower.
if len(config.Nodes) == 1 && config.Nodes[0].ID == l.ID() {
l.Logger.Println("log open: promoting to leader immediately")
l.startStateLoop(closing, Leader)
} else {
l.startStateLoop(closing, Follower)
}
} else {
l.Logger.Printf("log pending: waiting for initialization or join")
}
return nil
}
// Close closes the log.
func (l *Log) Close() error {
l.mu.Lock()
defer l.mu.Unlock()
return l.close()
}
// close should be called under lock.
func (l *Log) close() error {
l.tracef("closing...")
// Remove the reader.
_ = l.setReader(nil)
// Notify goroutines of closing and wait outside of lock.
if l.closing != nil {
close(l.closing)
l.closing = nil
l.mu.Unlock()
l.wg.Wait()
l.mu.Lock()
}
// Close the writers.
for _, w := range l.writers {
_ = w.Close()
}
l.writers = nil
// Clear log info.
l.setID(0)
l.path = ""
l.lastLogIndex, l.lastLogTerm = 0, 0
l.term, l.votedFor = 0, 0
l.config = nil
l.tracef("closed")
return nil
}
func (l *Log) setReaderWithLock(r io.ReadCloser) error {
l.mu.Lock()
defer l.mu.Unlock()
return l.setReader(r)
}
func (l *Log) setReader(r io.ReadCloser) error {
if l.reader != nil {
_ = l.reader.Close()
l.reader = nil
}
// Ignore if there is no new reader.
if r == nil {
return nil
}
// Close reader immediately and ignore if log is closed.
if !l.opened() {
_ = r.Close()
return ErrClosed
}
// Ignore if setting while transitioning state.
select {
case <-l.transitioning:
return errTransitioning
default:
}
// Set new reader.
l.reader = r
return nil
}
func (l *Log) setID(id uint64) {
l.id = id
l.updateLogPrefix()
}
// readID reads the log identifier from file.
func (l *Log) readID() (uint64, error) {
// Read identifier from disk.
b, err := ioutil.ReadFile(l.idPath())
if os.IsNotExist(err) {
return 0, nil
} else if err != nil {
return 0, err
}
// Parse identifier.
id, err := strconv.ParseUint(string(b), 10, 64)
if err != nil {
return 0, err
}
return id, nil
}
// writeID writes the log identifier to file.
func (l *Log) writeID(id uint64) error {
b := []byte(strconv.FormatUint(id, 10))
return ioutil.WriteFile(l.idPath(), b, 0666)
}
// readTerm reads the log term from file.
func (l *Log) readTerm() (uint64, error) {
// Read term from disk.
b, err := ioutil.ReadFile(l.termPath())
if os.IsNotExist(err) {
return 0, nil
} else if err != nil {
return 0, err
}
// Parse term.
id, err := strconv.ParseUint(string(b), 10, 64)
if err != nil {
return 0, err
}
return id, nil
}
// writeTerm writes the current log term to file.
func (l *Log) writeTerm(term uint64) error {
b := []byte(strconv.FormatUint(term, 10))
return ioutil.WriteFile(l.termPath(), b, 0666)
}
// setTerm sets the current term and clears the vote.
func (l *Log) setTerm(term uint64) error {
l.Logger.Printf("changing term: %d => %d", l.term, term)
if err := l.writeTerm(term); err != nil {
return err
}
l.term = term
l.votedFor = 0
return nil
}
// mustSetTerm sets the current term and clears the vote. Panic on error.
func (l *Log) mustSetTerm(term uint64) {
if err := l.setTerm(term); err != nil {
panic("unable to set term: " + err.Error())
}
}
// readConfig reads the configuration from disk.
func (l *Log) readConfig() (*Config, error) {
// Read config from disk.
f, err := os.Open(l.configPath())
if os.IsNotExist(err) {
return nil, nil
} else if err != nil {
return nil, err
}
defer func() { _ = f.Close() }()
// Marshal file to a config type.
config := &Config{}
if err := NewConfigDecoder(f).Decode(config); err != nil {
return nil, err
}
return config, nil
}
// writeConfig writes the configuration to disk.
func (l *Log) writeConfig(config *Config) error {
// FIX(benbjohnson): Atomic write.
// Open file.
f, err := os.Create(l.configPath())
if err != nil {
return err
}
defer func() { _ = f.Close() }()
// Marshal config into file.
if err := NewConfigEncoder(f).Encode(config); err != nil {
return err
}
return nil
}
// Initialize a new log.
// Returns an error if log data already exists.
func (l *Log) Initialize() error {
var config *Config
if err := func() error {
l.mu.Lock()
defer l.mu.Unlock()
// Return error if log is not open or is already a member of a cluster.
if !l.opened() {
return ErrClosed
} else if l.id != 0 {
return ErrInitialized
}
// Start first node at id 1.
id := uint64(1)
// Generate a new configuration with one node.
config = &Config{MaxNodeID: id}
config.AddNode(id, l.url)
// Generate new 8-hex digit cluster identifier.
config.ClusterID = uint64(l.Rand())
// Generate log id.
if err := l.writeID(id); err != nil {
return err
}
l.setID(id)
// Automatically promote to leader.
term := uint64(1)
if err := l.setTerm(term); err != nil {
return fmt.Errorf("set term: %s", err)
}
l.lastLogTerm = term
l.leaderID = l.id
return nil
}(); err != nil {
return err
}
// Begin state loop as leader.
l.startStateLoop(l.closing, Leader)
l.Logger.Printf("log initialize: promoted to 'leader' with cluster ID %d, log ID %d, term %d",
config.ClusterID, l.id, l.term)
// Set initial configuration.
var buf bytes.Buffer
_ = NewConfigEncoder(&buf).Encode(config)
index, err := l.internalApply(LogEntryInitialize, buf.Bytes())
if err != nil {
return err
}
// Wait until entry is applied.
return l.Wait(index)
}
func (l *Log) updateLogPrefix() {
var host string
if l.url.Host != "" {
host = l.url.Host
}
l.Logger.SetPrefix(fmt.Sprintf("[raft] %s ", host))
}
// trace writes a log message if DebugEnabled is true.
func (l *Log) trace(v ...interface{}) {
if l.DebugEnabled {
l.Logger.Print(v...)
}
}
// trace writes a formatted log message if DebugEnabled is true.
func (l *Log) tracef(msg string, v ...interface{}) {
if l.DebugEnabled {
l.Logger.Printf(msg+"\n", v...)
}
}
// IsLeader returns true if the log is the current leader.
func (l *Log) IsLeader() bool {
l.mu.Lock()
defer l.mu.Unlock()
return l.id != 0 && l.id == l.leaderID
}
// Leader returns the id and URL associated with the current leader.
// Returns zero if there is no current leader.
func (l *Log) Leader() (id uint64, u url.URL) {
l.mu.Lock()
defer l.mu.Unlock()
return l.leader()
}
func (l *Log) leader() (id uint64, u url.URL) {
// Ignore if there's no configuration set.
if l.config == nil {
return
}
// Find node by identifier.
n := l.config.NodeByID(l.leaderID)
if n == nil {
return
}
return n.ID, n.URL
}
// ClusterID returns the identifier for the cluster.
// Returns zero if the cluster has not been initialized yet.
func (l *Log) ClusterID() uint64 {
l.mu.Lock()
defer l.mu.Unlock()
if l.config == nil {
return 0
}
return l.config.ClusterID
}
// Join contacts a node in the cluster to request membership.
// A log cannot join a cluster if it has already been initialized.
func (l *Log) Join(u url.URL) error {
// Validate under lock.
var nodeURL url.URL
if err := func() error {
l.mu.Lock()
defer l.mu.Unlock()
if !l.opened() {
return ErrClosed
} else if l.id != 0 {
return ErrInitialized
} else if l.url.Host == "" {
return ErrURLRequired
}
nodeURL = l.url
return nil
}(); err != nil {
return err
}
l.tracef("Join: %s", u)
// Send join request.
id, leaderID, config, err := l.Transport.Join(u, nodeURL)
if err != nil {
return err
}
l.leaderID = leaderID
l.tracef("Join: confirmed")
// Lock once the join request is returned.
if err := func() error {
l.mu.Lock()
defer l.mu.Unlock()
// Write identifier.
if err := l.writeID(id); err != nil {
return err
}
l.setID(id)
// Write config.
if err := l.writeConfig(config); err != nil {
return err
}
l.config = config
return nil
}(); err != nil {
return err
}
// Begin state loop as follower.
l.startStateLoop(l.closing, Follower)
// Change to a follower state.
l.Logger.Println("log join: entered 'follower' state for cluster at", u, " with log ID", l.id)
// Wait for anything to be applied.
return l.Wait(1)
}
// Leave removes the log from cluster membership and removes the log data.
func (l *Log) Leave() error {
l.mu.Lock()
defer l.mu.Unlock()
// TODO(benbjohnson): Check if open.
// TODO(benbjohnson): Apply remove peer command.
// TODO(benbjohnson): Remove underlying data.
return nil
}
// startStateLoop begins the state loop in a separate goroutine.
// Returns once the state has transitioned to the initial state passed in.
func (l *Log) startStateLoop(closing <-chan struct{}, state State) {
l.wg.Add(1)
stateChanged := make(chan struct{})
go l.stateLoop(closing, state, stateChanged)
// Wait until state change.
<-stateChanged
}
// stateLoop runs in a separate goroutine and runs the appropriate state loop.
func (l *Log) stateLoop(closing <-chan struct{}, state State, stateChanged chan struct{}) {
defer l.wg.Done()
for {
// Transition to new state.
var transitioning chan struct{}
func() {
l.mu.Lock()
defer l.mu.Unlock()
l.Logger.Printf("log state change: %s => %s (term=%d)", l.state, state, l.term)
l.state = state
l.transitioning = make(chan struct{}, 0)
transitioning = l.transitioning
// Remove previous reader, if one exists.
_ = l.setReader(nil)
}()
// Notify caller on first state changes.
if stateChanged != nil {
close(stateChanged)
stateChanged = nil
}
// Execute the appropriate state loop.
// Each loop returns the next state to transition to.
switch state {
case Stopped:
return
case Follower:
state = l.followerLoop(closing)
case Candidate:
state = l.candidateLoop(closing)
case Leader:
state = l.leaderLoop(closing)
}
}
}
func (l *Log) followerLoop(closing <-chan struct{}) State {
l.tracef("followerLoop")
defer l.tracef("followerLoop: exit")
// Ensure all follower goroutines complete before transitioning to another state.
var wg sync.WaitGroup
defer wg.Wait()
defer l.setReaderWithLock(nil)
defer close(l.transitioning)
// Read log from leader in a separate goroutine.
wg.Add(1)
go l.readFromLeader(&wg)
for {
select {
case <-closing:
return Stopped
case ch := <-l.Clock.AfterElectionTimeout():
close(ch)
return Candidate
case hb := <-l.heartbeats:
l.tracef("followerLoop: heartbeat: term=%d, idx=%d", hb.term, hb.commitIndex)
// Update term, commit index & leader.
l.mu.Lock()
if hb.term > l.term {
l.mustSetTerm(hb.term)
}
if hb.commitIndex > l.commitIndex {
l.commitIndex = hb.commitIndex
}
l.leaderID = hb.leaderID
l.mu.Unlock()
case term := <-l.terms:
l.mu.Lock()
if term > l.term {
l.mustSetTerm(term)
}
l.mu.Unlock()
}
}
}
func (l *Log) readFromLeader(wg *sync.WaitGroup) {
defer wg.Done()
l.tracef("readFromLeader:")
for {
select {
case <-l.transitioning:
l.tracef("readFromLeader: exiting")
return
default:
}
// Retrieve the term, last log index, & leader URL.
l.mu.Lock()
id, lastLogIndex, term := l.id, l.lastLogIndex, l.term
_, u := l.leader()
l.mu.Unlock()
// If no leader exists then wait momentarily and retry.
if u.Host == "" {
l.tracef("readFromLeader: no leader")
time.Sleep(500 * time.Millisecond)
continue
}
// Connect to leader.
l.tracef("readFromLeader: read from: %s, id=%d, term=%d, index=%d", u.String(), id, term, lastLogIndex)
r, err := l.Transport.ReadFrom(u, id, term, lastLogIndex)
if err != nil {
l.Logger.Printf("connect stream: %s", err)
time.Sleep(500 * time.Millisecond)
continue
}
// Attach the stream to the log.
if err := l.ReadFrom(r); err != nil {
l.tracef("readFromLeader: read from: disconnect: %s", err)
}
}
}
// truncateTo removes all uncommitted entries up to index.
func (l *Log) truncateTo(index uint64) {
assert(index >= l.commitIndex, "cannot truncate to before the commit index: index=%d, commit=%d", index, l.commitIndex)
// Ignore if there are no entries.
// Ignore if all entries are before the index.
if len(l.entries) == 0 {
return
} else if l.entries[len(l.entries)-1].Index < index {
return
}
// If all entries are after the index, remove all.
if l.entries[0].Index > index {
l.entries = nil
l.lastLogIndex, l.lastLogTerm = index, l.term
return
}
// Otherwise slice entries starting from index.
emin, emax := l.entries[0].Index, l.entries[len(l.entries)-1].Index
l.tracef("trunc: entries=[%d,%d], index=%d", emin, emax, index)
l.entries = l.entries[:index-emin+1]
l.lastLogIndex = index
assert(l.entries[len(l.entries)-1].Index == index, "last entry in truncation not index: emax=%d, index=%d", l.entries[len(l.entries)-1].Index, index)
}
// candidateLoop requests vote from other nodes in an attempt to become leader.
func (l *Log) candidateLoop(closing <-chan struct{}) State {
l.tracef("candidateLoop")
defer l.tracef("candidateLoop: exit")
// TODO: prevote
// Increment term and request votes.
l.mu.Lock()
l.mustSetTerm(l.term + 1)
l.votedFor = l.id
term := l.term
l.mu.Unlock()
// Ensure all candidate goroutines complete before transitioning to another state.
var wg sync.WaitGroup
defer wg.Wait()
defer close(l.transitioning)
// Read log from leader in a separate goroutine.
wg.Add(1)
elected := make(chan struct{}, 1)
go l.elect(term, elected, &wg)
for {
select {
case <-closing:
return Stopped
case hb := <-l.heartbeats:
l.mu.Lock()
if hb.term >= term {
l.mustSetTerm(hb.term)
l.leaderID = hb.leaderID
l.mu.Unlock()
return Follower
}
l.mu.Unlock()
case newTerm := <-l.terms:
// Ignore if it's not after this current term.
if newTerm <= term {
continue
}
// Check against the current term since that may have changed.
l.mu.Lock()
if newTerm > l.term {
l.mustSetTerm(newTerm)