/
raft.go
3186 lines (2845 loc) · 73 KB
/
raft.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
// Copyright 2020-2021 The NATS Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package server
import (
"bytes"
"crypto/sha256"
"encoding/binary"
"errors"
"fmt"
"hash"
"io/ioutil"
"math/rand"
"net"
"os"
"path"
"path/filepath"
"sync"
"sync/atomic"
"time"
"github.com/minio/highwayhash"
)
type RaftNode interface {
Propose(entry []byte) error
ProposeDirect(entries []*Entry) error
ForwardProposal(entry []byte) error
InstallSnapshot(snap []byte) error
SendSnapshot(snap []byte) error
NeedSnapshot() bool
Applied(index uint64) (entries uint64, bytes uint64)
Compact(index uint64) error
State() RaftState
Size() (entries, bytes uint64)
Progress() (index, commit, applied uint64)
Leader() bool
Quorum() bool
Current() bool
GroupLeader() string
HadPreviousLeader() bool
StepDown(preferred ...string) error
Campaign() error
ID() string
Group() string
Peers() []*Peer
ProposeAddPeer(peer string) error
ProposeRemovePeer(peer string) error
ApplyC() <-chan *CommittedEntry
PauseApply()
ResumeApply()
LeadChangeC() <-chan bool
QuitC() <-chan struct{}
Created() time.Time
Stop()
Delete()
}
type WAL interface {
Type() StorageType
StoreMsg(subj string, hdr, msg []byte) (uint64, int64, error)
LoadMsg(index uint64) (subj string, hdr, msg []byte, ts int64, err error)
RemoveMsg(index uint64) (bool, error)
Compact(index uint64) (uint64, error)
Purge() (uint64, error)
Truncate(seq uint64) error
State() StreamState
FastState(*StreamState)
Stop() error
Delete() error
}
type LeadChange struct {
Leader bool
Previous string
}
type Peer struct {
ID string
Current bool
Last time.Time
Lag uint64
}
type RaftState uint8
// Allowable states for a NATS Consensus Group.
const (
Follower RaftState = iota
Leader
Candidate
Observer
Closed
)
func (state RaftState) String() string {
switch state {
case Follower:
return "FOLLOWER"
case Candidate:
return "CANDIDATE"
case Leader:
return "LEADER"
case Observer:
return "OBSERVER"
case Closed:
return "CLOSED"
}
return "UNKNOWN"
}
type raft struct {
sync.RWMutex
created time.Time
group string
sd string
id string
wal WAL
wtype StorageType
track bool
werr error
state RaftState
hh hash.Hash64
snapfile string
csz int
qn int
peers map[string]*lps
acks map[uint64]map[string]struct{}
pae map[uint64]*appendEntry
elect *time.Timer
active time.Time
llqrt time.Time
term uint64
pterm uint64
pindex uint64
commit uint64
applied uint64
leader string
vote string
hash string
s *Server
c *client
js *jetStream
dflag bool
pleader bool
// Subjects for votes, updates, replays.
psubj string
rpsubj string
vsubj string
vreply string
asubj string
areply string
sq *sendq
aesub *subscription
// Are we doing a leadership transfer.
lxfer bool
// For holding term and vote and peerstate to be written.
wtv []byte
wps []byte
wtvch chan struct{}
wpsch chan struct{}
// For when we need to catch up as a follower.
catchup *catchupState
// For leader or server catching up a follower.
progress map[string]chan uint64
// For when we have paused our applyC.
paused bool
hcommit uint64
// Channels
propc chan *Entry
entryc chan *appendEntry
respc chan *appendEntryResponse
applyc chan *CommittedEntry
quit chan struct{}
reqs chan *voteRequest
votes chan *voteResponse
leadc chan bool
stepdown chan string
}
// cacthupState structure that holds our subscription, and catchup term and index
// as well as starting term and index and how many updates we have seen.
type catchupState struct {
sub *subscription
cterm uint64
cindex uint64
pterm uint64
pindex uint64
active time.Time
}
// lps holds peer state of last time and last index replicated.
type lps struct {
ts int64
li uint64
}
const (
minElectionTimeout = 1000 * time.Millisecond
maxElectionTimeout = 5 * minElectionTimeout
minCampaignTimeout = 100 * time.Millisecond
maxCampaignTimeout = 4 * minCampaignTimeout
hbInterval = 500 * time.Millisecond
lostQuorumInterval = hbInterval * 5
)
type RaftConfig struct {
Name string
Store string
Log WAL
Track bool
}
var (
errProposalFailed = errors.New("raft: proposal failed")
errNotLeader = errors.New("raft: not leader")
errAlreadyLeader = errors.New("raft: already leader")
errNilCfg = errors.New("raft: no config given")
errUnknownPeer = errors.New("raft: unknown peer")
errCorruptPeers = errors.New("raft: corrupt peer state")
errStepdownFailed = errors.New("raft: stepdown failed")
errEntryLoadFailed = errors.New("raft: could not load entry from WAL")
errNodeClosed = errors.New("raft: node is closed")
errBadSnapName = errors.New("raft: snapshot name could not be parsed")
errNoSnapAvailable = errors.New("raft: no snapshot available")
errCatchupsRunning = errors.New("raft: snapshot can not be installed while catchups running")
errSnapshotCorrupt = errors.New("raft: snapshot corrupt")
errTooManyPrefs = errors.New("raft: stepdown requires at most one preferred new leader")
errStepdownNoPeer = errors.New("raft: stepdown failed, could not match new leader")
)
// This will bootstrap a raftNode by writing its config into the store directory.
func (s *Server) bootstrapRaftNode(cfg *RaftConfig, knownPeers []string, allPeersKnown bool) error {
if cfg == nil {
return errNilCfg
}
// Check validity of peers if presented.
for _, p := range knownPeers {
if len(p) != idLen {
return fmt.Errorf("raft: illegal peer: %q", p)
}
}
expected := len(knownPeers)
// We need to adjust this is all peers are not known.
if !allPeersKnown {
s.Debugf("Determining expected peer size for JetStream metacontroller")
if expected < 2 {
expected = 2
}
opts := s.getOpts()
nrs := len(opts.Routes)
cn := s.ClusterName()
ngwps := 0
for _, gw := range opts.Gateway.Gateways {
// Ignore our own cluster if specified.
if gw.Name == cn {
continue
}
for _, u := range gw.URLs {
host := u.Hostname()
// If this is an IP just add one.
if net.ParseIP(host) != nil {
ngwps++
} else {
addrs, _ := net.LookupHost(host)
ngwps += len(addrs)
}
}
}
if expected < nrs+ngwps {
expected = nrs + ngwps
s.Debugf("Adjusting expected peer set size to %d with %d known", expected, len(knownPeers))
}
}
// Check the store directory. If we have a memory based WAL we need to make sure the directory is setup.
if stat, err := os.Stat(cfg.Store); os.IsNotExist(err) {
if err := os.MkdirAll(cfg.Store, 0750); err != nil {
return fmt.Errorf("raft: could not create storage directory - %v", err)
}
} else if stat == nil || !stat.IsDir() {
return fmt.Errorf("raft: storage directory is not a directory")
}
tmpfile, err := ioutil.TempFile(cfg.Store, "_test_")
if err != nil {
return fmt.Errorf("raft: storage directory is not writable")
}
os.Remove(tmpfile.Name())
return writePeerState(cfg.Store, &peerState{knownPeers, expected})
}
// startRaftNode will start the raft node.
func (s *Server) startRaftNode(cfg *RaftConfig) (RaftNode, error) {
if cfg == nil {
return nil, errNilCfg
}
s.mu.Lock()
if s.sys == nil {
s.mu.Unlock()
return nil, ErrNoSysAccount
}
sq := s.sys.sq
sacc := s.sys.account
hash := s.sys.shash
s.mu.Unlock()
ps, err := readPeerState(cfg.Store)
if err != nil {
return nil, err
}
if ps == nil {
return nil, errors.New("raft: no peerstate")
}
n := &raft{
created: time.Now(),
id: hash[:idLen],
group: cfg.Name,
sd: cfg.Store,
wal: cfg.Log,
wtype: cfg.Log.Type(),
track: cfg.Track,
state: Follower,
csz: ps.clusterSize,
qn: ps.clusterSize/2 + 1,
hash: hash,
peers: make(map[string]*lps),
acks: make(map[uint64]map[string]struct{}),
pae: make(map[uint64]*appendEntry),
s: s,
c: s.createInternalSystemClient(),
js: s.getJetStream(),
sq: sq,
quit: make(chan struct{}),
wtvch: make(chan struct{}, 1),
wpsch: make(chan struct{}, 1),
reqs: make(chan *voteRequest, 8),
votes: make(chan *voteResponse, 32),
propc: make(chan *Entry, 8192),
entryc: make(chan *appendEntry, 32768),
respc: make(chan *appendEntryResponse, 32768),
applyc: make(chan *CommittedEntry, 8192),
leadc: make(chan bool, 8),
stepdown: make(chan string, 8),
}
n.c.registerWithAccount(sacc)
if atomic.LoadInt32(&s.logging.debug) > 0 {
n.dflag = true
}
key := sha256.Sum256([]byte(n.group))
n.hh, _ = highwayhash.New64(key[:])
if term, vote, err := n.readTermVote(); err != nil && term > 0 {
n.term = term
n.vote = vote
}
if err := os.MkdirAll(path.Join(cfg.Store, snapshotsDir), 0750); err != nil {
return nil, fmt.Errorf("could not create snapshots directory - %v", err)
}
// Can't recover snapshots if memory based.
if _, ok := n.wal.(*memStore); ok {
snapDir := path.Join(n.sd, snapshotsDir, "*")
os.RemoveAll(snapDir)
} else {
// See if we have any snapshots and if so load and process on startup.
n.setupLastSnapshot()
}
var state StreamState
n.wal.FastState(&state)
if state.Msgs > 0 {
// TODO(dlc) - Recover our state here.
if first, err := n.loadFirstEntry(); err == nil {
n.pterm, n.pindex = first.pterm, first.pindex
if first.commit > 0 && first.commit > n.commit {
n.commit = first.commit
}
}
// Replay the log.
// Since doing this in place we need to make sure we have enough room on the applyc.
needed := state.Msgs + 1 // 1 is for nil to mark end of replay.
if uint64(cap(n.applyc)) < needed {
n.applyc = make(chan *CommittedEntry, needed)
}
for index := state.FirstSeq; index <= state.LastSeq; index++ {
ae, err := n.loadEntry(index)
if err != nil {
n.warn("Could not load %d from WAL [%+v] with error: %v", index, state, err)
continue
}
if ae.pindex != index-1 {
n.warn("Corrupt WAL, truncating and fixing")
n.truncateWal(ae)
break
}
n.processAppendEntry(ae, nil)
}
}
// Send nil entry to signal the upper layers we are done doing replay/restore.
n.applyc <- nil
// Setup our internal subscriptions.
if err := n.createInternalSubs(); err != nil {
n.shutdown(true)
return nil, err
}
// Make sure to track ourselves.
n.trackPeer(n.id)
// Track known peers
for _, peer := range ps.knownPeers {
// Set these to 0 to start.
if peer != n.id {
n.peers[peer] = &lps{0, 0}
}
}
n.debug("Started")
n.Lock()
n.resetElectionTimeout()
n.llqrt = time.Now()
n.Unlock()
s.registerRaftNode(n.group, n)
s.startGoRoutine(n.run)
s.startGoRoutine(n.fileWriter)
return n, nil
}
// outOfResources checks to see if we are out of resources.
func (n *raft) outOfResources() bool {
if !n.track || n.js == nil || n.js.disabled {
return false
}
return n.js.limitsExceeded(n.wtype)
}
// Maps node names back to server names.
func (s *Server) serverNameForNode(node string) string {
if si, ok := s.nodeToInfo.Load(node); ok && si != nil {
return si.(nodeInfo).name
}
return _EMPTY_
}
// Maps node names back to cluster names.
func (s *Server) clusterNameForNode(node string) string {
if si, ok := s.nodeToInfo.Load(node); ok && si != nil {
return si.(nodeInfo).cluster
}
return _EMPTY_
}
// Server will track all raft nodes.
func (s *Server) registerRaftNode(group string, n RaftNode) {
s.rnMu.Lock()
defer s.rnMu.Unlock()
if s.raftNodes == nil {
s.raftNodes = make(map[string]RaftNode)
}
s.raftNodes[group] = n
}
func (s *Server) unregisterRaftNode(group string) {
s.rnMu.Lock()
defer s.rnMu.Unlock()
if s.raftNodes != nil {
delete(s.raftNodes, group)
}
}
func (s *Server) lookupRaftNode(group string) RaftNode {
s.rnMu.RLock()
defer s.rnMu.RUnlock()
var n RaftNode
if s.raftNodes != nil {
n = s.raftNodes[group]
}
return n
}
func (s *Server) reloadDebugRaftNodes() {
if s == nil {
return
}
debug := atomic.LoadInt32(&s.logging.debug) > 0
s.rnMu.RLock()
for _, ni := range s.raftNodes {
n := ni.(*raft)
n.Lock()
n.dflag = debug
n.Unlock()
}
s.rnMu.RUnlock()
}
func (s *Server) shutdownRaftNodes() {
if s == nil {
return
}
var nodes []RaftNode
s.rnMu.RLock()
if len(s.raftNodes) > 0 {
s.Debugf("Shutting down all raft nodes")
}
for _, n := range s.raftNodes {
nodes = append(nodes, n)
}
s.rnMu.RUnlock()
for _, node := range nodes {
if node.Leader() {
node.StepDown()
}
node.Stop()
}
}
func (s *Server) transferRaftLeaders() bool {
if s == nil {
return false
}
var nodes []RaftNode
s.rnMu.RLock()
if len(s.raftNodes) > 0 {
s.Debugf("Transferring any raft leaders")
}
for _, n := range s.raftNodes {
nodes = append(nodes, n)
}
s.rnMu.RUnlock()
var didTransfer bool
for _, node := range nodes {
if node.Leader() {
node.StepDown()
didTransfer = true
}
}
return didTransfer
}
// Formal API
// Propose will propose a new entry to the group.
// This should only be called on the leader.
func (n *raft) Propose(data []byte) error {
n.RLock()
if n.state != Leader {
n.RUnlock()
n.debug("Proposal ignored, not leader")
return errNotLeader
}
// Error if we had a previous write error.
if werr := n.werr; werr != nil {
n.RUnlock()
return werr
}
propc := n.propc
n.RUnlock()
// For entering and exiting the system, proposals and apply
// we will block.
propc <- &Entry{EntryNormal, data}
return nil
}
// ProposeDirect will propose entries directly.
// This should only be called on the leader.
func (n *raft) ProposeDirect(entries []*Entry) error {
n.RLock()
if n.state != Leader {
n.RUnlock()
n.debug("Proposal ignored, not leader")
return errNotLeader
}
// Error if we had a previous write error.
if werr := n.werr; werr != nil {
n.RUnlock()
return werr
}
n.RUnlock()
n.sendAppendEntry(entries)
return nil
}
// ForwardProposal will forward the proposal to the leader if known.
// If we are the leader this is the same as calling propose.
// FIXME(dlc) - We could have a reply subject and wait for a response
// for retries, but would need to not block and be in separate Go routine.
func (n *raft) ForwardProposal(entry []byte) error {
if n.Leader() {
return n.Propose(entry)
}
n.sendRPC(n.psubj, _EMPTY_, entry)
return nil
}
// ProposeAddPeer is called to add a peer to the group.
func (n *raft) ProposeAddPeer(peer string) error {
n.RLock()
if n.state != Leader {
n.RUnlock()
return errNotLeader
}
// Error if we had a previous write error.
if werr := n.werr; werr != nil {
n.RUnlock()
return werr
}
propc := n.propc
n.RUnlock()
select {
case propc <- &Entry{EntryAddPeer, []byte(peer)}:
default:
return errProposalFailed
}
return nil
}
// ProposeRemovePeer is called to remove a peer from the group.
func (n *raft) ProposeRemovePeer(peer string) error {
n.RLock()
propc, subj := n.propc, n.rpsubj
isUs, isLeader := peer == n.id, n.state == Leader
werr := n.werr
n.RUnlock()
// Error if we had a previous write error.
if werr != nil {
return werr
}
if isLeader {
if isUs {
n.StepDown()
} else {
select {
case propc <- &Entry{EntryRemovePeer, []byte(peer)}:
default:
return errProposalFailed
}
}
return nil
}
// Need to forward.
n.sendRPC(subj, _EMPTY_, []byte(peer))
return nil
}
// PauseApply will allow us to pause processing of append entries onto our
// external apply chan.
func (n *raft) PauseApply() {
n.Lock()
defer n.Unlock()
n.debug("Pausing apply channel")
n.paused = true
n.hcommit = n.commit
}
func (n *raft) ResumeApply() {
n.Lock()
defer n.Unlock()
n.debug("Resuming apply channel")
n.paused = false
// Run catchup..
if n.hcommit > n.commit {
n.debug("Resuming %d replays", n.hcommit+1-n.commit)
for index := n.commit + 1; index <= n.hcommit; index++ {
if err := n.applyCommit(index); err != nil {
break
}
}
}
n.hcommit = 0
}
// Compact will compact our WAL.
// This is for when we know we have our state on stable storage.
// E.g. snapshots.
func (n *raft) Compact(index uint64) error {
n.Lock()
defer n.Unlock()
// Error if we had a previous write error.
if n.werr != nil {
return n.werr
}
_, err := n.wal.Compact(index)
if err != nil {
n.setWriteErrLocked(err)
}
return err
}
// Applied is to be called when the FSM has applied the committed entries.
// Applied will return the number of entries and an estimation of the
// byte size that could be removed with a snapshot/compact.
func (n *raft) Applied(index uint64) (entries uint64, bytes uint64) {
n.Lock()
defer n.Unlock()
// Ignore if already applied.
if index > n.applied {
n.applied = index
}
var state StreamState
n.wal.FastState(&state)
if n.applied > state.FirstSeq {
entries = n.applied - state.FirstSeq
}
if state.Msgs > 0 {
bytes = entries * state.Bytes / state.Msgs
}
return entries, bytes
}
// For capturing data needed by snapshot.
type snapshot struct {
lastTerm uint64
lastIndex uint64
peerstate []byte
data []byte
}
const minSnapshotLen = 28
// Encodes a snapshot into a buffer for storage.
// Lock should be held.
func (n *raft) encodeSnapshot(snap *snapshot) []byte {
if snap == nil {
return nil
}
var le = binary.LittleEndian
buf := make([]byte, minSnapshotLen+len(snap.peerstate)+len(snap.data))
le.PutUint64(buf[0:], snap.lastTerm)
le.PutUint64(buf[8:], snap.lastIndex)
// Peer state
le.PutUint32(buf[16:], uint32(len(snap.peerstate)))
wi := 20
copy(buf[wi:], snap.peerstate)
wi += len(snap.peerstate)
// data itself.
copy(buf[wi:], snap.data)
wi += len(snap.data)
// Now do the hash for the end.
n.hh.Reset()
n.hh.Write(buf[:wi])
checksum := n.hh.Sum(nil)
copy(buf[wi:], checksum)
wi += len(checksum)
return buf[:wi]
}
// SendSnapshot will send the latest snapshot as a normal AE.
// Should only be used when the upper layers know this is most recent.
// Used when restoring streams etc.
func (n *raft) SendSnapshot(data []byte) error {
n.sendAppendEntry([]*Entry{&Entry{EntrySnapshot, data}})
return nil
}
// Used to install a snapshot for the given term and applied index. This will release
// all of the log entries up to and including index. This should not be called with
// entries that have been applied to the FSM but have not been applied to the raft state.
func (n *raft) InstallSnapshot(data []byte) error {
n.Lock()
if n.state == Closed {
n.Unlock()
return errNodeClosed
}
if werr := n.werr; werr != nil {
n.Unlock()
return werr
}
if len(n.progress) > 0 {
n.Unlock()
return errCatchupsRunning
}
var state StreamState
n.wal.FastState(&state)
if n.snapfile != _EMPTY_ && state.FirstSeq >= n.applied {
n.Unlock()
return nil
}
n.debug("Installing snapshot of %d bytes", len(data))
var term uint64
if ae, _ := n.loadEntry(n.applied); ae != nil {
term = ae.term
} else if ae, _ = n.loadFirstEntry(); ae != nil {
term = ae.term
} else {
term = n.pterm
}
snap := &snapshot{
lastTerm: term,
lastIndex: n.applied,
peerstate: encodePeerState(&peerState{n.peerNames(), n.csz}),
data: data,
}
snapDir := path.Join(n.sd, snapshotsDir)
sn := fmt.Sprintf(snapFileT, snap.lastTerm, snap.lastIndex)
sfile := path.Join(snapDir, sn)
// Remember our latest snapshot file.
n.snapfile = sfile
if err := ioutil.WriteFile(sfile, n.encodeSnapshot(snap), 0640); err != nil {
n.Unlock()
n.setWriteErr(err)
return err
}
if _, err := n.wal.Compact(snap.lastIndex + 1); err != nil {
n.Unlock()
n.setWriteErr(err)
return err
}
n.Unlock()
psnaps, _ := ioutil.ReadDir(snapDir)
// Remove any old snapshots.
for _, fi := range psnaps {
pn := fi.Name()
if pn != sn {
os.Remove(path.Join(snapDir, pn))
}
}
return nil
}
func (n *raft) NeedSnapshot() bool {
n.RLock()
defer n.RUnlock()
return n.snapfile == _EMPTY_ && n.applied > 0
}
const (
snapshotsDir = "snapshots"
snapFileT = "snap.%d.%d"
)
func termAndIndexFromSnapFile(sn string) (term, index uint64, err error) {
if sn == _EMPTY_ {
return 0, 0, errBadSnapName
}
fn := filepath.Base(sn)
if n, err := fmt.Sscanf(fn, snapFileT, &term, &index); err != nil || n != 2 {
return 0, 0, errBadSnapName
}
return term, index, nil
}
func (n *raft) setupLastSnapshot() {
snapDir := path.Join(n.sd, snapshotsDir)
psnaps, err := ioutil.ReadDir(snapDir)
if err != nil {
return
}
var lterm, lindex uint64
var latest string
for _, sf := range psnaps {
sfile := path.Join(snapDir, sf.Name())
var term, index uint64
term, index, err := termAndIndexFromSnapFile(sf.Name())
if err == nil {
if term > lterm {
lterm, lindex = term, index
latest = sfile
} else if term == lterm && index > lindex {
lindex = index
latest = sfile
}
} else {
// Clean this up, can't parse the name.
// TODO(dlc) - We could read in and check actual contents.
n.debug("Removing snapshot, can't parse name: %q", sf.Name())
os.Remove(sfile)
}
}
// Now cleanup any old entries
for _, sf := range psnaps {
sfile := path.Join(snapDir, sf.Name())
if sfile != latest {
n.debug("Removing old snapshot: %q", sfile)
os.Remove(sfile)
}
}
if latest == _EMPTY_ {
return
}
// Set latest snapshot we have.
n.Lock()
defer n.Unlock()
n.snapfile = latest
snap, err := n.loadLastSnapshot()
if err != nil {
os.Remove(n.snapfile)
n.snapfile = _EMPTY_
} else {
n.pindex = snap.lastIndex
n.pterm = snap.lastTerm
n.commit = snap.lastIndex
n.applyc <- &CommittedEntry{n.commit, []*Entry{&Entry{EntrySnapshot, snap.data}}}
if _, err := n.wal.Compact(snap.lastIndex + 1); err != nil {
n.setWriteErrLocked(err)
}
}
}
// loadLastSnapshot will load and return our last snapshot.
// Lock should be held.
func (n *raft) loadLastSnapshot() (*snapshot, error) {
if n.snapfile == _EMPTY_ {
return nil, errNoSnapAvailable
}
buf, err := ioutil.ReadFile(n.snapfile)
if err != nil {
n.warn("Error reading snapshot: %v", err)
os.Remove(n.snapfile)
n.snapfile = _EMPTY_
return nil, err
}
if len(buf) < minSnapshotLen {
n.warn("Snapshot corrupt, too short")
os.Remove(n.snapfile)
n.snapfile = _EMPTY_
return nil, errSnapshotCorrupt
}
// Check to make sure hash is consistent.
hoff := len(buf) - 8
lchk := buf[hoff:]
n.hh.Reset()
n.hh.Write(buf[:hoff])
if !bytes.Equal(lchk[:], n.hh.Sum(nil)) {
n.warn("Snapshot corrupt, checksums did not match")
os.Remove(n.snapfile)
n.snapfile = _EMPTY_
return nil, errSnapshotCorrupt
}
var le = binary.LittleEndian
lps := le.Uint32(buf[16:])
snap := &snapshot{
lastTerm: le.Uint64(buf[0:]),
lastIndex: le.Uint64(buf[8:]),
peerstate: buf[20 : 20+lps],
data: buf[20+lps : hoff],
}