-
Notifications
You must be signed in to change notification settings - Fork 98
/
store.go
1981 lines (1656 loc) · 55 KB
/
store.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 litefs
import (
"bytes"
"context"
crand "crypto/rand"
"encoding/binary"
"encoding/json"
"errors"
"expvar"
"fmt"
"io"
"log"
"math/rand"
"os"
"path/filepath"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"github.com/superfly/litefs/internal"
"github.com/superfly/litefs/internal/chunk"
"github.com/superfly/ltx"
"golang.org/x/exp/slog"
"golang.org/x/sync/errgroup"
)
// Default store settings.
const (
DefaultReconnectDelay = 1 * time.Second
DefaultDemoteDelay = 10 * time.Second
DefaultRetention = 10 * time.Minute
DefaultRetentionMonitorInterval = 1 * time.Minute
DefaultHaltAcquireTimeout = 10 * time.Second
DefaultHaltLockTTL = 30 * time.Second
DefaultHaltLockMonitorInterval = 5 * time.Second
DefaultBackupDelay = 1 * time.Second
DefaultBackupFullSyncInterval = 10 * time.Second
)
const (
// MaxBackupLTXFileN is the number of LTX files that can be compacted
// together at a time when sending data to the backup service.
MaxBackupLTXFileN = 256
MetricsMonitorInterval = 1 * time.Second
)
var ErrStoreClosed = fmt.Errorf("store closed")
// GlobalStore represents a single store used for metrics collection.
var GlobalStore atomic.Value
// Store represents a collection of databases.
type Store struct {
mu sync.Mutex
path string
id uint64 // unique node id
clusterID atomic.Value
dbs map[string]*DB
changeSetSubscribers map[*ChangeSetSubscriber]struct{}
eventSubscribers map[*EventSubscriber]struct{}
primaryTimestamp atomic.Int64 // ms since epoch of last update from primary. -1 if primary
lease Lease // if not nil, store is current primary
primaryCh chan struct{} // closed when primary loses leadership
primaryInfo *PrimaryInfo // contains info about the current primary
candidate bool // if true, we are eligible to become the primary
readyCh chan struct{} // closed when primary found or acquired
demoteCh chan struct{} // closed when Demote() is called
ctx context.Context
cancel context.CancelCauseFunc
g errgroup.Group
// The operating system interface to use for system calls. Defaults to SystemOS.
OS OS
Exit func(int)
// Client used to connect to other LiteFS instances.
Client Client
// Leaser manages the lease that controls leader election.
Leaser Leaser
// BackupClient is the client to connect to an external backup service.
BackupClient BackupClient
// If true, LTX files are compressed using LZ4.
Compress bool
// Time to wait after disconnecting from the primary to reconnect.
ReconnectDelay time.Duration
// Time to wait after manually demoting trying to become primary again.
DemoteDelay time.Duration
// Length of time to retain LTX files.
Retention time.Duration
RetentionMonitorInterval time.Duration
// Max time to hold HALT lock and interval between expiration checks.
HaltLockTTL time.Duration
HaltLockMonitorInterval time.Duration
// Time to wait to acquire the HALT lock.
HaltAcquireTimeout time.Duration
// Time after a change is made before it is sent to the backup service.
// This allows multiple changes in quick succession to be batched together.
BackupDelay time.Duration
// Interval between checks to re-fetch the position map. This ensures that
// restores on the backup server are detected by the LiteFS primary.
BackupFullSyncInterval time.Duration
// Callback to notify kernel of file changes.
Invalidator Invalidator
// Interface to interact with the host environment.
Environment Environment
// Specifies a subset of databases to replicate from the primary.
DatabaseFilter []string
// If true, computes and verifies the checksum of the entire database
// after every transaction. Should only be used during testing.
StrictVerify bool
}
// NewStore returns a new instance of Store.
func NewStore(path string, candidate bool) *Store {
primaryCh := make(chan struct{})
close(primaryCh)
// Generate random node ID to prevent connecting to itself.
b := make([]byte, 16)
if _, err := io.ReadFull(crand.Reader, b); err != nil {
panic(fmt.Errorf("cannot generate node id: %w", err))
}
s := &Store{
id: binary.BigEndian.Uint64(b),
path: path,
dbs: make(map[string]*DB),
changeSetSubscribers: make(map[*ChangeSetSubscriber]struct{}),
eventSubscribers: make(map[*EventSubscriber]struct{}),
candidate: candidate,
primaryCh: primaryCh,
readyCh: make(chan struct{}),
demoteCh: make(chan struct{}),
OS: &internal.SystemOS{},
Exit: os.Exit,
ReconnectDelay: DefaultReconnectDelay,
DemoteDelay: DefaultDemoteDelay,
Retention: DefaultRetention,
RetentionMonitorInterval: DefaultRetentionMonitorInterval,
HaltAcquireTimeout: DefaultHaltAcquireTimeout,
HaltLockTTL: DefaultHaltLockTTL,
HaltLockMonitorInterval: DefaultHaltLockMonitorInterval,
BackupDelay: DefaultBackupDelay,
BackupFullSyncInterval: DefaultBackupFullSyncInterval,
Environment: &nopEnvironment{},
}
s.ctx, s.cancel = context.WithCancelCause(context.Background())
s.clusterID.Store("")
s.primaryTimestamp.Store(-1)
return s
}
// Path returns underlying data directory.
func (s *Store) Path() string { return s.path }
// DBDir returns the folder that stores all databases.
func (s *Store) DBDir() string {
return filepath.Join(s.path, "dbs")
}
// DBPath returns the folder that stores a single database.
func (s *Store) DBPath(name string) string {
return filepath.Join(s.path, "dbs", name)
}
// ClusterIDPath returns the filename where the cluster ID is stored.
func (s *Store) ClusterIDPath() string {
return filepath.Join(s.path, "clusterid")
}
// ID returns the unique identifier for this instance. Available after Open().
// Persistent across restarts if underlying storage is persistent.
func (s *Store) ID() uint64 {
return s.id
}
// ClusterID returns the cluster ID.
func (s *Store) ClusterID() string {
return s.clusterID.Load().(string)
}
// setClusterID saves the cluster ID to disk.
func (s *Store) setClusterID(id string) error {
if s.ClusterID() == id {
return nil // no-op
}
if err := ValidateClusterID(id); err != nil {
return err
}
filename := s.ClusterIDPath()
tempFilename := filename + ".tmp"
defer func() { _ = s.OS.Remove("SETCLUSTERID", tempFilename) }()
if err := s.OS.MkdirAll("SETCLUSTERID", filepath.Dir(filename), 0o777); err != nil {
return err
}
f, err := s.OS.Create("SETCLUSTERID", tempFilename)
if err != nil {
return err
}
defer func() { _ = f.Close() }()
if _, err := io.WriteString(f, id+"\n"); err != nil {
return err
}
if err := f.Sync(); err != nil {
return err
} else if err := f.Close(); err != nil {
return err
}
if err := s.OS.Rename("SETCLUSTERID", tempFilename, filename); err != nil {
return err
} else if err := internal.Sync(filepath.Dir(filename)); err != nil {
return err
}
s.clusterID.Store(id)
return nil
}
// Open initializes the store based on files in the data directory.
func (s *Store) Open() error {
if s.Leaser == nil {
return fmt.Errorf("leaser required")
}
if err := s.OS.MkdirAll("OPEN", s.path, 0o777); err != nil {
return err
}
// Attempt to remove persisted node ID from disk.
// See: https://github.com/superfly/litefs/issues/361
_ = s.OS.Remove("OPEN:ID", filepath.Join(s.path, "id"))
// Load cluster ID from disk, if available locally.
if err := s.readClusterID(); err != nil {
return fmt.Errorf("load cluster id: %w", err)
}
if err := s.openDatabases(); err != nil {
return fmt.Errorf("open databases: %w", err)
}
// Begin background replication monitor.
s.g.Go(func() error { return s.monitorLease(s.ctx) })
// Begin lock monitor.
s.g.Go(func() error { return s.monitorHaltLock(s.ctx) })
// Begin retention monitor.
if s.RetentionMonitorInterval > 0 {
s.g.Go(func() error { return s.monitorRetention(s.ctx) })
}
return nil
}
// readClusterID reads the cluster ID from the "clusterid" file.
// Skipped if no cluster id file exists.
func (s *Store) readClusterID() error {
b, err := s.OS.ReadFile("READCLUSTERID", s.ClusterIDPath())
if os.IsNotExist(err) {
return nil
} else if err != nil {
return err
}
clusterID := strings.TrimSpace(string(b))
if err := ValidateClusterID(clusterID); err != nil {
return err
}
s.clusterID.Store(clusterID)
return nil
}
func (s *Store) openDatabases() error {
if err := s.OS.MkdirAll("OPENDATABASES", s.DBDir(), 0o777); err != nil {
return err
}
fis, err := s.OS.ReadDir("OPENDATABASES", s.DBDir())
if err != nil {
return fmt.Errorf("readdir: %w", err)
}
for _, fi := range fis {
if err := s.openDatabase(fi.Name()); err != nil {
return fmt.Errorf("open database(%q): %w", fi.Name(), err)
}
}
// Update metrics.
storeDBCountMetric.Set(float64(len(s.dbs)))
return nil
}
func (s *Store) openDatabase(name string) error {
// Instantiate and open database.
db := NewDB(s, name, s.DBPath(name))
if err := db.Open(); err != nil {
return err
}
// Add to internal lookups.
s.dbs[db.Name()] = db
return nil
}
// Close signals for the store to shut down.
func (s *Store) Close() (retErr error) {
s.cancel(ErrStoreClosed)
retErr = s.g.Wait()
// Release outstanding HALT locks.
for _, db := range s.DBs() {
haltLock := db.RemoteHaltLock()
if haltLock == nil {
continue
}
log.Printf("releasing halt lock on %q", db.Name())
if err := db.ReleaseRemoteHaltLock(context.Background(), haltLock.ID); err != nil {
log.Printf("cannot release halt lock on %q on shutdown", db.Name())
}
}
return retErr
}
// ReadyCh returns a channel that is closed once the store has become primary
// or once it has connected to the primary.
func (s *Store) ReadyCh() chan struct{} {
return s.readyCh
}
func (s *Store) isReady() bool {
select {
case <-s.readyCh:
return true
default:
return false
}
}
// markReady closes the ready channel if it hasn't already been closed.
func (s *Store) markReady() {
select {
case <-s.readyCh:
return
default:
close(s.readyCh)
}
}
// Demote instructs store to destroy its primary lease, if any.
// Store will wait momentarily before attempting to become primary again.
func (s *Store) Demote() {
s.mu.Lock()
defer s.mu.Unlock()
close(s.demoteCh)
s.demoteCh = make(chan struct{})
}
// Handoff instructs store to send its lease to a connected replica.
func (s *Store) Handoff(ctx context.Context, nodeID uint64) error {
var lease Lease
if err := func() error {
s.mu.Lock()
defer s.mu.Unlock()
// Ensure this node is currently the primary and has a lease.
lease = s.lease
if lease == nil {
return fmt.Errorf("node is not currently primary")
}
// Find connected subscriber by node ID.
sub := s.changeSetSubscriberByNodeID(nodeID)
if sub == nil {
return fmt.Errorf("target node is not currently connected")
}
return nil
}(); err != nil {
return err
}
// Attempt to handoff the lease.
// Not all lease systems support handoff so this may return an error.
return lease.Handoff(ctx, nodeID)
}
// IsPrimary returns true if store has a lease to be the primary.
func (s *Store) IsPrimary() bool {
s.mu.Lock()
defer s.mu.Unlock()
return s.isPrimary()
}
func (s *Store) isPrimary() bool { return s.lease != nil }
func (s *Store) setLease(lease Lease) {
// Create a new channel to notify about primary loss when becoming primary.
// Or close existing channel if we are losing our primary status.
if (s.lease != nil) != (lease != nil) {
if lease != nil {
s.primaryCh = make(chan struct{})
s.setPrimaryTimestamp(0)
} else {
close(s.primaryCh)
s.setPrimaryTimestamp(-1)
}
}
// Store current lease
s.lease = lease
// Update metrics.
if s.isPrimary() {
storeIsPrimaryMetric.Set(1)
} else {
storeIsPrimaryMetric.Set(0)
}
s.notifyPrimaryChange()
}
// PrimaryCtx wraps ctx with another context that will cancel when no longer primary.
func (s *Store) PrimaryCtx(ctx context.Context) context.Context {
s.mu.Lock()
defer s.mu.Unlock()
return s.primaryCtx(ctx)
}
func (s *Store) primaryCtx(ctx context.Context) context.Context {
return newPrimaryCtx(ctx, s.primaryCh)
}
// PrimaryInfo returns info about the current primary.
func (s *Store) PrimaryInfo() (isPrimary bool, info *PrimaryInfo) {
s.mu.Lock()
defer s.mu.Unlock()
return s.isPrimary(), s.primaryInfo.Clone()
}
// PrimaryInfoWithContext continually attempts to fetch the primary info until available.
// Returns when isPrimary is true, info is non-nil, or when ctx is done.
func (s *Store) PrimaryInfoWithContext(ctx context.Context) (isPrimary bool, info *PrimaryInfo) {
if isPrimary, info = s.PrimaryInfo(); isPrimary || info != nil {
return isPrimary, info
}
ticker := time.NewTicker(100 * time.Microsecond)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return isPrimary, info
case <-ticker.C:
if isPrimary, info = s.PrimaryInfo(); isPrimary || info != nil {
return isPrimary, info
}
}
}
}
func (s *Store) setPrimaryInfo(info *PrimaryInfo) {
s.primaryInfo = info
s.notifyPrimaryChange()
}
// Candidate returns true if store is eligible to be the primary.
func (s *Store) Candidate() bool {
return s.candidate
}
// DBByName returns a database by name.
// Returns nil if the database does not exist.
func (s *Store) DB(name string) *DB {
s.mu.Lock()
defer s.mu.Unlock()
return s.dbs[name]
}
// DBs returns a list of databases.
func (s *Store) DBs() []*DB {
s.mu.Lock()
defer s.mu.Unlock()
a := make([]*DB, 0, len(s.dbs))
for _, db := range s.dbs {
a = append(a, db)
}
return a
}
// CreateDB creates a new database with the given name. The returned file handle
// must be closed by the caller. Returns an error if a database with the same
// name already exists.
func (s *Store) CreateDB(name string) (db *DB, f *os.File, err error) {
defer func() {
TraceLog.Printf("[CreateDatabase(%s)]: %s", name, errorKeyValue(err))
}()
s.mu.Lock()
defer s.mu.Unlock()
// Check if the database already exists. We could have a reference to a
// zero-length database which means it was previously deleted.
requireNewDB := true
if db = s.dbs[name]; db != nil {
if db.PageN() > 0 {
return nil, nil, ErrDatabaseExists
}
requireNewDB = false
}
// Generate database directory with name file & empty database file.
dbPath := s.DBPath(name)
if err := s.OS.MkdirAll("CREATDEDB", dbPath, 0o777); err != nil {
return nil, nil, err
}
f, err = s.OS.OpenFile("CREATDEDB", filepath.Join(dbPath, "database"), os.O_RDWR|os.O_CREATE|os.O_EXCL|os.O_TRUNC, 0o666)
if err != nil {
return nil, nil, err
}
// Create new database instance and add to maps.
if requireNewDB {
db = NewDB(s, name, dbPath)
if err := db.Open(); err != nil {
_ = f.Close()
return nil, nil, err
}
s.dbs[name] = db
}
// Notify listeners of change.
s.markDirty(name)
// Update metrics
storeDBCountMetric.Set(float64(len(s.dbs)))
return db, f, nil
}
// CreateDBIfNotExists creates an empty database with the given name.
func (s *Store) CreateDBIfNotExists(name string) (*DB, error) {
s.mu.Lock()
defer s.mu.Unlock()
// Exit if database with same name already exists.
if db := s.dbs[name]; db != nil {
return db, nil
}
// Generate database directory with name file & empty database file.
dbPath := s.DBPath(name)
if err := s.OS.MkdirAll("CREATDEDBIFNOTEXISTS", dbPath, 0o777); err != nil {
return nil, err
}
if err := s.OS.WriteFile("CREATDEDBIFNOTEXISTS", filepath.Join(dbPath, "database"), nil, 0o666); err != nil {
return nil, err
}
// Create new database instance and add to maps.
db := NewDB(s, name, dbPath)
if err := db.Open(); err != nil {
return nil, err
}
s.dbs[name] = db
// Notify listeners of change.
s.markDirty(name)
// Update metrics
storeDBCountMetric.Set(float64(len(s.dbs)))
return db, nil
}
// PosMap returns a map of databases and their transactional position.
func (s *Store) PosMap() map[string]ltx.Pos {
s.mu.Lock()
defer s.mu.Unlock()
m := make(map[string]ltx.Pos, len(s.dbs))
for _, db := range s.dbs {
m[db.Name()] = db.Pos()
}
return m
}
// SubscribeChangeSet creates a new subscriber for store changes.
func (s *Store) SubscribeChangeSet(nodeID uint64) *ChangeSetSubscriber {
s.mu.Lock()
defer s.mu.Unlock()
sub := newChangeSetSubscriber(s, nodeID)
s.changeSetSubscribers[sub] = struct{}{}
storeSubscriberCountMetric.Set(float64(len(s.changeSetSubscribers)))
return sub
}
// UnsubscribeChangeSet removes a subscriber from the store.
func (s *Store) UnsubscribeChangeSet(sub *ChangeSetSubscriber) {
s.mu.Lock()
defer s.mu.Unlock()
delete(s.changeSetSubscribers, sub)
storeSubscriberCountMetric.Set(float64(len(s.changeSetSubscribers)))
}
// SubscriberByNodeID returns a subscriber by node ID.
// Returns nil if the node is not currently subscribed to the store.
func (s *Store) SubscriberByNodeID(nodeID uint64) *ChangeSetSubscriber {
s.mu.Lock()
defer s.mu.Unlock()
return s.changeSetSubscriberByNodeID(nodeID)
}
func (s *Store) changeSetSubscriberByNodeID(nodeID uint64) *ChangeSetSubscriber {
for sub := range s.changeSetSubscribers {
if sub.NodeID() == nodeID {
return sub
}
}
return nil
}
// MarkDirty marks a database dirty on all subscribers.
func (s *Store) MarkDirty(name string) {
s.mu.Lock()
defer s.mu.Unlock()
s.markDirty(name)
}
func (s *Store) markDirty(name string) {
for sub := range s.changeSetSubscribers {
sub.MarkDirty(name)
}
}
// SubscribeEvents creates a new subscriber for store events.
func (s *Store) SubscribeEvents() *EventSubscriber {
s.mu.Lock()
defer s.mu.Unlock()
var hostname string
if s.primaryInfo != nil {
hostname = s.primaryInfo.Hostname
}
sub := newEventSubscriber(s)
sub.ch <- Event{
Type: EventTypeInit,
Data: InitEventData{
IsPrimary: s.isPrimary(),
Hostname: hostname,
},
}
s.eventSubscribers[sub] = struct{}{}
return sub
}
// UnsubscribeEvents removes an event subscriber from the store.
func (s *Store) UnsubscribeEvents(sub *EventSubscriber) {
s.mu.Lock()
defer s.mu.Unlock()
s.unsubscribeEvents(sub)
}
func (s *Store) unsubscribeEvents(sub *EventSubscriber) {
if _, ok := s.eventSubscribers[sub]; ok {
delete(s.eventSubscribers, sub)
close(sub.ch)
}
}
// NotifyEvent sends event to all event subscribers.
// If a subscriber has no additional buffer space available then it is closed.
func (s *Store) NotifyEvent(event Event) {
s.mu.Lock()
defer s.mu.Unlock()
s.notifyEvent(event)
}
func (s *Store) notifyEvent(event Event) {
for sub := range s.eventSubscribers {
select {
case sub.ch <- event:
default:
s.unsubscribeEvents(sub)
}
}
}
func (s *Store) notifyPrimaryChange() {
var hostname string
if s.primaryInfo != nil {
hostname = s.primaryInfo.Hostname
}
s.notifyEvent(Event{
Type: EventTypePrimaryChange,
Data: PrimaryChangeEventData{
IsPrimary: s.isPrimary(),
Hostname: hostname,
},
})
}
// monitorLease continuously handles either the leader lease or replicates from the primary.
func (s *Store) monitorLease(ctx context.Context) (err error) {
// Initialize environment to indicate this node is not a primary.
s.Environment.SetPrimaryStatus(ctx, false)
var handoffLeaseID string
for {
// Exit if store is closed.
if err := ctx.Err(); err != nil {
return nil
}
// If a cluster ID exists on the server, ensure it matches what we have.
var info PrimaryInfo
if leaserClusterID, err := s.Leaser.ClusterID(ctx); err != nil {
log.Printf("cannot fetch cluster ID from %q lease, retrying: %s", s.Leaser.Type(), err)
sleepWithContext(ctx, s.ReconnectDelay)
continue
} else if leaserClusterID != "" && s.ClusterID() != "" && leaserClusterID != s.ClusterID() {
log.Printf("cannot connect, %q lease already initialized with different ID: %s", s.Leaser.Type(), leaserClusterID)
sleepWithContext(ctx, s.ReconnectDelay)
continue
} else if leaserClusterID != "" && s.ClusterID() == "" {
log.Printf("cannot become primary, local node has no cluster ID and %q lease already initialized with cluster ID %s", s.Leaser.Type(), leaserClusterID)
if info, err = s.Leaser.PrimaryInfo(ctx); err != nil {
log.Printf("cannot find primary, retrying: %s", err)
sleepWithContext(ctx, s.ReconnectDelay)
continue
}
} else {
// At this point, either the leaser has a cluster ID and ours matches,
// or the leaser has no cluster ID. We'll update the leaser once we
// become primary.
// If we have been handed a lease ID from the current primary, use that
// and act like we're the new primary.
var lease Lease
if handoffLeaseID != "" {
// Move lease to a local variable so we can clear the outer scope.
leaseID := handoffLeaseID
handoffLeaseID = ""
// We'll only try to acquire the lease once. If it fails, then it
// reverts back to the regular primary/replica flow.
log.Printf("%s: acquiring existing lease from handoff", FormatNodeID(s.id))
if lease, err = s.Leaser.AcquireExisting(ctx, leaseID); err != nil {
log.Printf("%s: cannot acquire existing lease from handoff, retrying: %s", FormatNodeID(s.id), err)
sleepWithContext(ctx, s.ReconnectDelay)
continue
}
} else {
// Otherwise, attempt to either obtain a primary lock or read the current primary.
lease, info, err = s.acquireLeaseOrPrimaryInfo(ctx)
if err == ErrNoPrimary && !s.candidate {
log.Printf("%s: cannot find primary & ineligible to become primary, retrying: %s", FormatNodeID(s.id), err)
sleepWithContext(ctx, s.ReconnectDelay)
continue
} else if err != nil {
log.Printf("%s: cannot acquire lease or find primary, retrying: %s", FormatNodeID(s.id), err)
sleepWithContext(ctx, s.ReconnectDelay)
continue
}
}
// Monitor as primary if we have obtained a lease.
if lease != nil {
log.Printf("%s: primary lease acquired, advertising as %s", FormatNodeID(s.id), s.Leaser.AdvertiseURL())
if err := s.monitorLeaseAsPrimary(ctx, lease); err != nil {
log.Printf("%s: primary lease lost, retrying: %s", FormatNodeID(s.id), err)
}
if err := s.Recover(ctx); err != nil {
log.Printf("%s: state change recovery error (primary): %s", FormatNodeID(s.id), err)
}
continue
}
}
// Monitor as replica if another primary already exists.
log.Printf("%s: existing primary found (%s), connecting as replica to %q", FormatNodeID(s.id), info.Hostname, info.AdvertiseURL)
if handoffLeaseID, err = s.monitorLeaseAsReplica(ctx, info); err == nil {
log.Printf("%s: disconnected from primary, retrying", FormatNodeID(s.id))
} else {
log.Printf("%s: disconnected from primary with error, retrying: %s", FormatNodeID(s.id), err)
}
if err := s.Recover(ctx); err != nil {
log.Printf("%s: state change recovery error (replica): %s", FormatNodeID(s.id), err)
}
// Ignore the sleep if we are receiving a handed off lease.
if handoffLeaseID == "" {
sleepWithContext(ctx, s.ReconnectDelay)
}
}
}
func (s *Store) acquireLeaseOrPrimaryInfo(ctx context.Context) (Lease, PrimaryInfo, error) {
// Attempt to find an existing primary first.
info, err := s.Leaser.PrimaryInfo(ctx)
if err == ErrNoPrimary && !s.candidate {
return nil, info, err // no primary, not eligible to become primary
} else if err != nil && err != ErrNoPrimary {
return nil, info, fmt.Errorf("fetch primary url: %w", err)
} else if err == nil {
return nil, info, nil
}
// If no primary, attempt to become primary.
lease, err := s.Leaser.Acquire(ctx)
if err == ErrPrimaryExists {
// passthrough and retry primary info fetch
} else if err != nil {
return nil, info, fmt.Errorf("acquire lease: %w", err)
} else if lease != nil {
return lease, info, nil
}
// If we raced to become primary and another node beat us, retry the fetch.
info, err = s.Leaser.PrimaryInfo(ctx)
if err != nil {
return nil, info, err
}
return nil, info, nil
}
// monitorLeaseAsPrimary monitors & renews the current lease.
// NOTE: This code is borrowed from the consul/api's RenewPeriodic() implementation.
func (s *Store) monitorLeaseAsPrimary(ctx context.Context, lease Lease) error {
const timeout = 1 * time.Second
// Attempt to destroy lease when we exit this function.
var demoted bool
closeLeaseOnExit := true
defer func() {
if closeLeaseOnExit {
log.Printf("%s: exiting primary, destroying lease", FormatNodeID(s.id))
if err := lease.Close(); err != nil {
log.Printf("%s: cannot remove lease: %s", FormatNodeID(s.id), err)
}
} else {
log.Printf("%s: exiting primary, preserving lease for handoff", FormatNodeID(s.id))
}
// Pause momentarily if this was a manual demotion.
if demoted {
log.Printf("%s: waiting for %s after demotion", FormatNodeID(s.id), s.DemoteDelay)
sleepWithContext(ctx, s.DemoteDelay)
}
}()
// If the leaser doesn't have a cluster ID yet, generate one or set it to ours.
if v, err := s.Leaser.ClusterID(ctx); err != nil {
return fmt.Errorf("set cluster id: %w", err)
} else if v == "" {
// Use existing ID or generate a new one.
clusterID := s.ClusterID()
if clusterID == "" {
clusterID = GenerateClusterID()
}
// Update the cluster ID on the leaser.
if err := s.Leaser.SetClusterID(ctx, clusterID); err != nil {
return fmt.Errorf("set leaser cluster id: %w", err)
}
// Save the cluster ID to disk, in case we generated a new one above.
if err := s.setClusterID(clusterID); err != nil {
return fmt.Errorf("set local cluster id: %w", err)
}
log.Printf("set cluster id on %q lease %q", s.Leaser.Type(), clusterID)
}
// Mark as the primary node while we're in this function.
s.mu.Lock()
s.setLease(lease)
primaryCtx := s.primaryCtx(context.Background())
demoteCh := s.demoteCh
s.mu.Unlock()
// Mark store as ready if we've obtained primary status.
s.markReady()
// Run background goroutine to push data to long-term storage while we are primary.
// This context is canceled when the lease is cleared on exit of the function.
var g sync.WaitGroup
defer g.Wait()
if s.BackupClient != nil && s.BackupDelay > 0 {
g.Add(1)
go func() { defer g.Done(); s.monitorPrimaryBackup(primaryCtx) }()
}
// Ensure that we are no longer marked as primary once we exit this function.
defer func() {
s.mu.Lock()
defer s.mu.Unlock()
s.setLease(nil)
}()
// Notify host environment that we are primary.
s.Environment.SetPrimaryStatus(ctx, true)
defer func() { s.Environment.SetPrimaryStatus(ctx, false) }()
waitDur := lease.TTL() / 2
for {
select {
case <-time.After(waitDur):
// Attempt to renew the lease. If the lease is gone then we need to
// just exit and we can start over or connect to the new primary.
//
// If we just have a connection error then we'll try to more
// aggressively retry the renewal until we exceed TTL.
if err := lease.Renew(ctx); err == ErrLeaseExpired {
return err
} else if err != nil {
// If our next renewal will exceed TTL, exit now.
if time.Since(lease.RenewedAt())+timeout > lease.TTL() {
time.Sleep(timeout)
return ErrLeaseExpired
}
// Otherwise log error and try again after a shorter period.
log.Printf("%s: lease renewal error, retrying: %s", FormatNodeID(s.id), err)
waitDur = time.Second
continue
}
// Renewal was successful, restart with low frequency.
waitDur = lease.TTL() / 2
case <-demoteCh:
demoted = true
log.Printf("%s: node manually demoted", FormatNodeID(s.id))
return nil