-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.go
More file actions
2478 lines (2369 loc) · 69.9 KB
/
server.go
File metadata and controls
2478 lines (2369 loc) · 69.9 KB
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 lockd
import (
"bytes"
"context"
"crypto/tls"
"crypto/x509"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"net/http"
"net/url"
"os"
"path/filepath"
"strings"
"sync"
"sync/atomic"
"time"
"golang.org/x/net/http2"
"pkt.systems/kryptograf/keymgmt"
"pkt.systems/lockd/api"
"pkt.systems/lockd/internal/clock"
"pkt.systems/lockd/internal/connguard"
"pkt.systems/lockd/internal/core"
"pkt.systems/lockd/internal/cryptoutil"
"pkt.systems/lockd/internal/httpapi"
"pkt.systems/lockd/internal/lsf"
"pkt.systems/lockd/internal/qrf"
"pkt.systems/lockd/internal/search"
indexer "pkt.systems/lockd/internal/search/index"
"pkt.systems/lockd/internal/search/scan"
"pkt.systems/lockd/internal/storage"
loggingbackend "pkt.systems/lockd/internal/storage/logging"
"pkt.systems/lockd/internal/storage/retry"
"pkt.systems/lockd/internal/svcfields"
"pkt.systems/lockd/internal/tcclient"
"pkt.systems/lockd/internal/tccluster"
"pkt.systems/lockd/internal/tcleader"
"pkt.systems/lockd/internal/txncoord"
"pkt.systems/lockd/namespaces"
"pkt.systems/lockd/tlsutil"
"pkt.systems/pslog"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/metric"
)
// Server wraps the HTTP server, storage backend, and supporting components.
type Server struct {
cfg Config
baseLogger pslog.Logger
logger pslog.Logger
backend storage.Backend
backendHash string
serverBundle *tlsutil.Bundle
indexManager *indexer.Manager
handler *httpapi.Handler
httpSrv *http.Server
httpShutdown func(context.Context) error
listener net.Listener
socketPath string
clock clock.Clock
telemetry *telemetryBundle
lastServeErr error
mu sync.Mutex
tcLeader *tcleader.Manager
tcLeaderCancel context.CancelFunc
tcCAPool *x509.CertPool
defaultCAPool *x509.CertPool
tcAuthEnabled bool
tcAllowDefaultCA bool
tcCluster *tccluster.Store
tcTrustPEM [][]byte
tcClusterMu sync.Mutex
tcClusterClient *http.Client
tcClusterNoLeave atomic.Bool
tcClusterLeft atomic.Bool
rmRegisterCancel context.CancelFunc
rmRegisterDone sync.WaitGroup
tcClusterCancel context.CancelFunc
tcClusterDone sync.WaitGroup
tcClusterID string
shutdown bool
sweeperStop chan struct{}
sweeperDone sync.WaitGroup
readyOnce sync.Once
readyCh chan struct{}
qrfController *qrf.Controller
lsfObserver *lsf.Observer
lsfCancel context.CancelFunc
lastActivity atomic.Int64
idleSweepRunning atomic.Bool
draining atomic.Bool
drainDeadline atomic.Int64
drainMetrics struct {
once sync.Once
active metric.Int64Histogram
remaining metric.Int64Histogram
duration metric.Float64Histogram
err error
}
drainNotifyClients atomic.Bool
defaultCloseOpts closeOptions
drainFn func(context.Context, DrainLeasesPolicy) drainSummary
}
type leaseSnapshot struct {
Namespace string
Key string
Owner string
LeaseID string
ExpiresAt int64
}
type drainSummary struct {
ActiveAtStart int
Remaining int
Elapsed time.Duration
}
// Option configures server instances.
type Option func(*options)
type options struct {
Logger pslog.Logger
Backend storage.Backend
Clock clock.Clock
OTLPEndpoint string
MetricsListen string
MetricsSet bool
PprofListen string
PprofSet bool
ProfilingMetrics bool
ProfilingMetricsSet bool
configHooks []func(*Config)
closeDefaults []CloseOption
tcLeaseTTL time.Duration
tcFanoutGate txncoord.FanoutGate
}
// WithLogger supplies a custom logger.
// Passing nil falls back to pslog.NoopLogger().
func WithLogger(l pslog.Logger) Option {
return func(o *options) {
if l == nil {
o.Logger = pslog.NoopLogger()
return
}
o.Logger = l
}
}
// WithBackend injects a pre-built backend (useful for tests).
func WithBackend(b storage.Backend) Option {
return func(o *options) {
o.Backend = b
}
}
// WithClock injects a custom clock implementation.
func WithClock(c clock.Clock) Option {
return func(o *options) {
o.Clock = c
}
}
// WithTCLeaderLeaseTTL overrides the lease TTL used for TC leader election.
func WithTCLeaderLeaseTTL(ttl time.Duration) Option {
return func(o *options) {
o.tcLeaseTTL = ttl
}
}
// WithTCFanoutGate injects a hook between local apply and remote fan-out (test-only).
func WithTCFanoutGate(gate txncoord.FanoutGate) Option {
return func(o *options) {
o.tcFanoutGate = gate
}
}
// WithOTLPEndpoint overrides the OTLP collector endpoint used for telemetry.
func WithOTLPEndpoint(endpoint string) Option {
return func(o *options) {
o.OTLPEndpoint = endpoint
}
}
// WithMetricsListen overrides the metrics listener address (empty disables metrics).
func WithMetricsListen(addr string) Option {
return func(o *options) {
o.MetricsListen = addr
o.MetricsSet = true
}
}
// WithPprofListen overrides the pprof listener address (empty disables).
func WithPprofListen(addr string) Option {
return func(o *options) {
o.PprofListen = addr
o.PprofSet = true
}
}
// WithProfilingMetrics toggles Go runtime profiling metrics on the metrics endpoint.
func WithProfilingMetrics(enabled bool) Option {
return func(o *options) {
o.ProfilingMetrics = enabled
o.ProfilingMetricsSet = true
}
}
// WithLSFLogInterval overrides the cadence for lockd.lsf.sample telemetry logs; use 0 to disable logging.
func WithLSFLogInterval(interval time.Duration) Option {
return func(o *options) {
o.configHooks = append(o.configHooks, func(cfg *Config) {
cfg.LSFLogInterval = interval
cfg.LSFLogIntervalSet = true
})
}
}
// WithDefaultCloseOptions sets the server-wide defaults applied to Close/Shutdown calls.
func WithDefaultCloseOptions(opts ...CloseOption) Option {
return func(o *options) {
o.closeDefaults = append(o.closeDefaults, opts...)
}
}
// CloseOption customises server shutdown semantics.
type CloseOption func(*closeOptions)
type closeOptions struct {
drain DrainLeasesPolicy
drainSet bool
shutdownTimeout time.Duration
shutdownTimeoutSet bool
}
const drainShutdownSplit = 0.8
const (
rmRegistrationInterval = 30 * time.Second
rmRegistrationPollInterval = 1 * time.Second
rmRegistrationTimeout = 5 * time.Second
)
const (
tcLeaveFanoutHeader = "X-Lockd-TC-Leave-Fanout"
tcLeaveFanoutMaxConcurrent = 16
)
// DrainLeasesPolicy describes how the server should attempt to let existing lease
// holders finish work before the HTTP server stops accepting new connections.
type DrainLeasesPolicy struct {
// GracePeriod defines how long the server should keep serving requests
// (while denying new leases) before beginning the HTTP shutdown. Zero skips
// the grace window.
GracePeriod time.Duration
// ForceRelease toggles metadata rewrites that explicitly clear outstanding
// leases when the grace period elapses. This is experimental and disabled by
// default.
ForceRelease bool
// NotifyClients controls whether the server surfaces Shutdown-Imminent
// headers while draining so clients can release proactively.
NotifyClients bool
}
// WithDrainLeases configures the shutdown grace period used to let existing
// lease holders flush state. Passing a negative duration disables draining.
func WithDrainLeases(grace time.Duration) CloseOption {
return WithDrainLeasesPolicy(DrainLeasesPolicy{
GracePeriod: grace,
NotifyClients: true,
})
}
// WithDrainLeasesPolicy applies a full drain policy to shutdown calls.
func WithDrainLeasesPolicy(policy DrainLeasesPolicy) CloseOption {
return func(opts *closeOptions) {
opts.drain = policy.normalized()
opts.drainSet = true
}
}
// WithShutdownTimeout caps the total time allowed for drain plus HTTP shutdown.
// Zero disables the explicit cap and relies solely on the provided context.
func WithShutdownTimeout(d time.Duration) CloseOption {
return func(opts *closeOptions) {
if d <= 0 {
opts.shutdownTimeout = 0
opts.shutdownTimeoutSet = true
return
}
opts.shutdownTimeout = d
opts.shutdownTimeoutSet = true
}
}
func defaultCloseOptions() closeOptions {
return closeOptions{
drain: DrainLeasesPolicy{
GracePeriod: 10 * time.Second,
NotifyClients: true,
},
drainSet: true,
shutdownTimeout: 10 * time.Second,
shutdownTimeoutSet: true,
}
}
func resolveCloseOptions(base closeOptions, input []CloseOption) closeOptions {
opts := base
for _, apply := range input {
if apply == nil {
continue
}
apply(&opts)
}
if !opts.drainSet {
def := defaultCloseOptions().drain
opts.drain = def
opts.drainSet = true
}
opts.drain = opts.drain.normalized()
return opts
}
func (p DrainLeasesPolicy) normalized() DrainLeasesPolicy {
if p.GracePeriod < 0 {
p.GracePeriod = 0
}
return p
}
// NewServer constructs a lockd server according to cfg.
// Example:
//
// cfg := lockd.Config{Store: "mem://", Listen: ":9341", ListenProto: "tcp"}
// srv, err := lockd.NewServer(cfg)
// if err != nil {
// log.Fatal(err)
// }
// go srv.Start()
func NewServer(cfg Config, opts ...Option) (*Server, error) {
cfgCopy := cfg
var o options
for _, opt := range opts {
opt(&o)
}
for _, hook := range o.configHooks {
hook(&cfgCopy)
}
if err := cfgCopy.Validate(); err != nil {
return nil, err
}
cfg = cfgCopy
var err error
var bundle *tlsutil.Bundle
if cfg.MTLSEnabled() || cfg.StorageEncryptionEnabled() {
bundleSource := cfg.BundlePath
if len(cfg.BundlePEM) > 0 {
bundle, err = tlsutil.LoadBundleFromBytes(cfg.BundlePEM)
bundleSource = "<inline>"
} else {
bundle, err = tlsutil.LoadBundle(cfg.BundlePath, cfg.DenylistPath)
}
if err != nil {
return nil, err
}
if cfg.StorageEncryptionEnabled() {
if bundle.MetadataRootKey == (keymgmt.RootKey{}) {
return nil, fmt.Errorf("config: server bundle %s missing kryptograf root key (reissue with 'lockd auth new server')", bundleSource)
}
if bundle.MetadataDescriptor == (keymgmt.Descriptor{}) {
return nil, fmt.Errorf("config: server bundle %s missing metadata descriptor (reissue with 'lockd auth new server')", bundleSource)
}
caID, err := cryptoutil.CACertificateID(bundle.CACertPEM)
if err != nil {
return nil, fmt.Errorf("config: derive ca id: %w", err)
}
cfg.MetadataRootKey = bundle.MetadataRootKey
cfg.MetadataDescriptor = bundle.MetadataDescriptor
cfg.MetadataContext = caID
}
}
var crypto *storage.Crypto
if cfg.StorageEncryptionEnabled() {
crypto, err = storage.NewCrypto(storage.CryptoConfig{
Enabled: true,
RootKey: cfg.MetadataRootKey,
MetadataDescriptor: cfg.MetadataDescriptor,
MetadataContext: []byte(cfg.MetadataContext),
Snappy: cfg.StorageEncryptionSnappy,
DisableBufferPool: cfg.DisableKryptoPool,
})
if err != nil {
return nil, err
}
}
logger := o.Logger
if logger == nil {
logger = pslog.NoopLogger()
}
if parsed, err := url.Parse(cfg.Store); err == nil {
scheme := strings.ToLower(strings.TrimSpace(parsed.Scheme))
if scheme == "disk" && strings.EqualFold(cfg.HAMode, "concurrent") {
logger.Warn("ha.mode.override",
"requested", "concurrent",
"effective", "failover",
"store", cfg.Store,
"reason", "disk/nfs backends require a single serialized writer for performance and correctness; concurrent mode is supported for object stores",
)
cfg.HAMode = "failover"
}
}
serverClock := o.Clock
if serverClock == nil {
serverClock = clock.Real{}
}
if cfg.StorageEncryptionEnabled() {
cryptoLogger := svcfields.WithSubsystem(logger, "storage.crypto.envelope")
cryptoLogger.Info("storage.crypto.envelope enabled", "enabled", true)
poolLogger := svcfields.WithSubsystem(logger, "storage.crypto.buffer_pool")
poolLogger.Info("storage.crypto.buffer_pool enabled", "enabled", !cfg.DisableKryptoPool)
snappyLogger := svcfields.WithSubsystem(logger, "storage.pipeline.snappy.pre_encrypt")
if cfg.StorageEncryptionSnappy {
snappyLogger.Info("storage.pipeline.snappy pre-encrypt enabled", "enabled", true)
} else {
snappyLogger.Info("storage.pipeline.snappy pre-encrypt disabled", "enabled", false)
}
} else {
cryptoLogger := svcfields.WithSubsystem(logger, "storage.crypto.envelope")
cryptoLogger.Warn("storage.crypto.envelope disabled; falling back to plaintext at rest", "impact", "data at rest will be stored in plaintext", "enabled", false)
snappyLogger := svcfields.WithSubsystem(logger, "storage.pipeline.snappy.pre_encrypt")
snappyLogger.Info("storage.pipeline.snappy pre-encrypt disabled", "enabled", false, "reason", "requires storage.crypto.envelope")
}
var (
tcTrustPool *x509.CertPool
tcTrustPEMBlobs [][]byte
tcClientTrustPEM [][]byte
clientTrustPool *x509.CertPool
)
if bundle != nil {
clientTrustPool = bundle.CAPool
if cfg.TCTrustDir != "" {
tcPool, blobs, err := loadTCTrustPool(cfg.TCTrustDir, svcfields.WithSubsystem(logger, "server.tctrust"))
if err != nil {
return nil, err
}
tcTrustPool = tcPool
tcTrustPEMBlobs = blobs
if tcPool != nil && len(tcTrustPEMBlobs) > 0 {
clientTrustPool = bundle.CAPool.Clone()
for _, pemData := range tcTrustPEMBlobs {
clientTrustPool.AppendCertsFromPEM(pemData)
}
}
}
}
if len(tcTrustPEMBlobs) > 0 {
tcClientTrustPEM = append(tcClientTrustPEM, tcTrustPEMBlobs...)
}
if bundle != nil && len(bundle.CACertPEM) > 0 {
tcClientTrustPEM = append(tcClientTrustPEM, bundle.CACertPEM)
}
tcClusterIdentity := ""
if cfg.MTLSEnabled() && bundle != nil {
if bundle.ServerCert != nil {
tcClusterIdentity = tccluster.IdentityFromCertificate(bundle.ServerCert)
}
if tcClusterIdentity == "" && len(bundle.ServerCertificate.Certificate) > 0 {
if cert, err := x509.ParseCertificate(bundle.ServerCertificate.Certificate[0]); err == nil {
tcClusterIdentity = tccluster.IdentityFromCertificate(cert)
}
}
} else {
tcClusterIdentity = tccluster.IdentityFromEndpoint(cfg.SelfEndpoint)
}
joinHasNonSelf := false
selfEndpoint := strings.TrimSpace(cfg.SelfEndpoint)
normalizedSelf := selfEndpoint
if normalizedSelf != "" {
normalized := tccluster.NormalizeEndpoints([]string{normalizedSelf})
if len(normalized) > 0 {
normalizedSelf = normalized[0]
}
}
joinEndpoints := tccluster.NormalizeEndpoints(append([]string(nil), cfg.TCJoinEndpoints...))
if len(joinEndpoints) > 0 && normalizedSelf != "" {
for _, endpoint := range joinEndpoints {
if endpoint != normalizedSelf {
joinHasNonSelf = true
break
}
}
}
if joinHasNonSelf && !cfg.MTLSEnabled() {
return nil, fmt.Errorf("tc join requires mTLS for multi-node membership")
}
if cfg.MTLSEnabled() && joinHasNonSelf && tcClusterIdentity == "" {
return nil, fmt.Errorf("tc join requires a server certificate with spiffe://lockd/server/<node-id>")
}
leaderSelfID := ""
if cfg.MTLSEnabled() && tcClusterIdentity != "" {
leaderSelfID = tcClusterIdentity
}
var handler *httpapi.Handler
var tcLeader *tcleader.Manager
if strings.TrimSpace(cfg.SelfEndpoint) != "" {
tcLeader, err = tcleader.NewManager(tcleader.Config{
SelfID: leaderSelfID,
SelfEndpoint: cfg.SelfEndpoint,
Logger: svcfields.WithSubsystem(logger, "tc.leader"),
DisableMTLS: cfg.DisableMTLS,
ClientBundle: cfg.TCClientBundlePath,
TrustPEM: tcClientTrustPEM,
LeaseTTL: o.tcLeaseTTL,
Clock: serverClock,
Eligible: func() bool {
if handler == nil {
return true
}
return handler.NodeActive()
},
})
if err != nil {
return nil, err
}
}
var telemetry *telemetryBundle
otlpEndpoint := cfg.OTLPEndpoint
if o.OTLPEndpoint != "" {
otlpEndpoint = o.OTLPEndpoint
}
if strings.TrimSpace(otlpEndpoint) == "" {
cfg.DisableHTTPTracing = true
cfg.DisableStorageTracing = true
}
metricsListen := cfg.MetricsListen
if o.MetricsSet {
metricsListen = o.MetricsListen
}
pprofListen := cfg.PprofListen
if o.PprofSet {
pprofListen = o.PprofListen
}
profilingMetrics := cfg.EnableProfilingMetrics
if o.ProfilingMetricsSet {
profilingMetrics = o.ProfilingMetrics
}
if profilingMetrics && strings.TrimSpace(metricsListen) == "" {
return nil, fmt.Errorf("profiling metrics require metrics listen address")
}
if otlpEndpoint != "" || metricsListen != "" || pprofListen != "" || profilingMetrics {
telemetry, err = setupTelemetry(context.Background(), otlpEndpoint, metricsListen, pprofListen, profilingMetrics, svcfields.WithSubsystem(logger, "observability.telemetry.exporter"))
if err != nil {
return nil, err
}
}
backend := o.Backend
ownedBackend := false
if backend == nil {
backend, err = openBackend(cfg, crypto, logger)
if err != nil {
if telemetry != nil {
shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
_ = telemetry.Shutdown(shutdownCtx)
cancel()
}
return nil, err
}
ownedBackend = true
}
clusterLogger := svcfields.WithSubsystem(logger, "tc.cluster")
var tcClusterStore *tccluster.Store
if backend != nil {
tcClusterStore = tccluster.NewStore(backend, clusterLogger, serverClock)
}
backendHash := ""
if backend != nil {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
hash, err := backend.BackendHash(ctx)
cancel()
if err != nil {
logger.Warn("storage.backend_hash.error", "error", err)
}
backendHash = strings.TrimSpace(hash)
if backendHash == "" {
logger.Warn("storage.backend_hash.empty")
}
}
retryCfg := retry.Config{
MaxAttempts: cfg.StorageRetryMaxAttempts,
BaseDelay: cfg.StorageRetryBaseDelay,
MaxDelay: cfg.StorageRetryMaxDelay,
Multiplier: cfg.StorageRetryMultiplier,
}
storageLogger := svcfields.WithSubsystem(logger, "storage.backend.core")
if !cfg.DisableStorageTracing {
backend = loggingbackend.Wrap(backend, storageLogger.With("layer", "backend"), "storage.backend.core")
}
backend = retry.Wrap(backend, storageLogger.With("layer", "retry"), serverClock, retryCfg)
if strings.EqualFold(cfg.HAMode, "concurrent") {
storageLogger.Info("storage.single_writer.disabled", "mode", "concurrent")
}
jsonUtil, err := selectJSONUtil(cfg.JSONUtil)
if err != nil {
if ownedBackend {
_ = backend.Close()
}
if telemetry != nil {
shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
_ = telemetry.Shutdown(shutdownCtx)
cancel()
}
return nil, err
}
qrfCtrl := qrf.NewController(qrf.Config{
Enabled: !cfg.QRFDisabled,
QueueSoftLimit: cfg.QRFQueueSoftLimit,
QueueHardLimit: cfg.QRFQueueHardLimit,
QueueConsumerSoftLimit: cfg.QRFQueueConsumerSoftLimit,
QueueConsumerHardLimit: cfg.QRFQueueConsumerHardLimit,
LockSoftLimit: cfg.QRFLockSoftLimit,
LockHardLimit: cfg.QRFLockHardLimit,
QuerySoftLimit: cfg.QRFQuerySoftLimit,
QueryHardLimit: cfg.QRFQueryHardLimit,
MemorySoftLimitBytes: cfg.QRFMemorySoftLimitBytes,
MemoryHardLimitBytes: cfg.QRFMemoryHardLimitBytes,
MemorySoftLimitPercent: cfg.QRFMemorySoftLimitPercent,
MemoryHardLimitPercent: cfg.QRFMemoryHardLimitPercent,
MemoryStrictHeadroomPercent: cfg.QRFMemoryStrictHeadroomPercent,
SwapSoftLimitBytes: cfg.QRFSwapSoftLimitBytes,
SwapHardLimitBytes: cfg.QRFSwapHardLimitBytes,
SwapSoftLimitPercent: cfg.QRFSwapSoftLimitPercent,
SwapHardLimitPercent: cfg.QRFSwapHardLimitPercent,
CPUPercentSoftLimit: cfg.QRFCPUPercentSoftLimit,
CPUPercentHardLimit: cfg.QRFCPUPercentHardLimit,
LoadSoftLimitMultiplier: cfg.QRFLoadSoftLimitMultiplier,
LoadHardLimitMultiplier: cfg.QRFLoadHardLimitMultiplier,
RecoverySamples: cfg.QRFRecoverySamples,
SoftDelay: cfg.QRFSoftDelay,
EngagedDelay: cfg.QRFEngagedDelay,
RecoveryDelay: cfg.QRFRecoveryDelay,
MaxWait: cfg.QRFMaxWait,
Logger: logger,
})
var lsfObserver *lsf.Observer
if !cfg.QRFDisabled {
lsfObserver = lsf.NewObserver(lsf.Config{
Enabled: true,
SampleInterval: cfg.LSFSampleInterval,
LogInterval: cfg.LSFLogInterval,
}, qrfCtrl, logger)
}
defaultNamespaceCfg := namespaces.DefaultConfig()
if provider, ok := backend.(namespaces.ConfigProvider); ok && provider != nil {
defaultNamespaceCfg = provider.DefaultNamespaceConfig()
}
var scanAdapter search.Adapter
if backend != nil {
adapter, err := scan.New(scan.Config{
Backend: backend,
Logger: svcfields.WithSubsystem(logger, "search.scan"),
MaxDocumentBytes: cfg.JSONMaxBytes,
})
if err != nil {
return nil, err
}
scanAdapter = adapter
}
var namespaceConfigs *namespaces.ConfigStore
if backend != nil {
namespaceConfigs = namespaces.NewConfigStore(backend, crypto, svcfields.WithSubsystem(logger, "namespace.config"), defaultNamespaceCfg)
}
var indexManager *indexer.Manager
var indexAdapter search.Adapter
var indexStore *indexer.Store
if backend != nil {
indexStore = indexer.NewStore(backend, crypto)
if indexStore != nil {
indexLogger := svcfields.WithSubsystem(logger, "search.index")
flushDocs := cfg.IndexerFlushDocs
flushInterval := cfg.IndexerFlushInterval
if defaults, ok := backend.(storage.IndexerDefaultsProvider); ok && defaults != nil {
defDocs, defInterval := defaults.IndexerFlushDefaults()
if !cfg.IndexerFlushDocsSet && defDocs > 0 {
flushDocs = defDocs
}
if !cfg.IndexerFlushIntervalSet && defInterval > 0 {
flushInterval = defInterval
}
}
indexManager = indexer.NewManager(indexStore, indexer.WriterOptions{
FlushDocs: flushDocs,
FlushInterval: flushInterval,
NoSync: strings.EqualFold(cfg.HAMode, "failover") ||
strings.EqualFold(cfg.HAMode, "single"),
Logger: indexLogger,
})
adapter, err := indexer.NewAdapter(indexer.AdapterConfig{
Store: indexStore,
Logger: indexLogger,
})
if err != nil {
return nil, err
}
indexAdapter = adapter
indexLogger.Info("indexer.config",
"flush_docs", flushDocs,
"flush_interval", flushInterval,
"docs_override", cfg.IndexerFlushDocsSet,
"interval_override", cfg.IndexerFlushIntervalSet)
}
}
var searchAdapter search.Adapter
switch {
case scanAdapter != nil && indexAdapter != nil:
searchAdapter = search.NewDispatcher(search.DispatcherConfig{
Index: indexAdapter,
Scan: scanAdapter,
})
case indexAdapter != nil:
searchAdapter = indexAdapter
default:
searchAdapter = scanAdapter
}
var srvRef *Server
handler = httpapi.New(httpapi.Config{
Store: backend,
Crypto: crypto,
Logger: logger,
Clock: serverClock,
HAMode: cfg.HAMode,
HALeaseTTL: cfg.HALeaseTTL,
HASinglePresenceTTL: cfg.HASinglePresenceTTL,
SearchAdapter: searchAdapter,
NamespaceConfigs: namespaceConfigs,
DefaultNamespaceConfig: defaultNamespaceCfg,
IndexManager: indexManager,
DefaultNamespace: cfg.DefaultNamespace,
JSONMaxBytes: cfg.JSONMaxBytes,
AttachmentMaxBytes: cfg.AttachmentMaxBytes,
CompactWriter: jsonUtil.compactWriter,
DefaultTTL: cfg.DefaultTTL,
MaxTTL: cfg.MaxTTL,
AcquireBlock: cfg.AcquireBlock,
SpoolMemoryThreshold: cfg.SpoolMemoryThreshold,
TxnDecisionRetention: cfg.TCDecisionRetention,
TxnReplayInterval: cfg.TxnReplayInterval,
QueueDecisionCacheTTL: cfg.QueueDecisionCacheTTL,
QueueDecisionMaxApply: cfg.QueueDecisionMaxApply,
QueueDecisionApplyTimeout: cfg.QueueDecisionApplyTimeout,
StateCacheBytes: cfg.StateCacheBytes,
QueryDocPrefetch: cfg.QueryDocPrefetch,
EnforceClientIdentity: cfg.MTLSEnabled(),
MetaWarmupAttempts: -1,
StateWarmupAttempts: -1,
QueueMaxConsumers: cfg.QueueMaxConsumers,
QueuePollInterval: cfg.QueuePollInterval,
QueuePollJitter: cfg.QueuePollJitter,
QueueResilientPollInterval: cfg.QueueResilientPollInterval,
QueueListPageSize: cfg.QueueListPageSize,
LSFObserver: lsfObserver,
QRFController: qrfCtrl,
TCAuthEnabled: cfg.MTLSEnabled() && !cfg.TCDisableAuth,
TCTrustPool: tcTrustPool,
DefaultCAPool: bundleCAPool(bundle),
TCAllowDefaultCA: cfg.TCAllowDefaultCA,
TCLeader: tcLeader,
SelfEndpoint: cfg.SelfEndpoint,
TCClusterIdentity: tcClusterIdentity,
TCJoinEndpoints: cfg.TCJoinEndpoints,
TCFanoutTimeout: cfg.TCFanoutTimeout,
TCFanoutMaxAttempts: cfg.TCFanoutMaxAttempts,
TCFanoutBaseDelay: cfg.TCFanoutBaseDelay,
TCFanoutMaxDelay: cfg.TCFanoutMaxDelay,
TCFanoutMultiplier: cfg.TCFanoutMultiplier,
TCFanoutGate: o.tcFanoutGate,
TCFanoutTrustPEM: tcClientTrustPEM,
TCLeaveFanout: func(ctx context.Context) error {
if srvRef == nil {
return nil
}
return srvRef.tcClusterLeaveFanout(ctx)
},
TCClusterLeaveSelf: func() {
if srvRef == nil {
return
}
srvRef.markTCClusterLeft()
},
TCClusterJoinSelf: func() {
if srvRef == nil {
return
}
srvRef.markTCClusterJoined()
},
TCClientBundlePath: cfg.TCClientBundlePath,
TCServerBundle: bundle,
DisableMTLS: cfg.DisableMTLS,
ShutdownState: func() httpapi.ShutdownState {
if srvRef == nil {
return httpapi.ShutdownState{}
}
draining, remaining, notify := srvRef.shutdownState()
return httpapi.ShutdownState{Draining: draining, Remaining: remaining, Notify: notify}
},
DisableHTTPTracing: cfg.DisableHTTPTracing,
ActivityHook: func() {
if srvRef == nil {
return
}
srvRef.markActivity()
},
})
logger.Info("json compaction configured", "impl", jsonUtil.name)
mux := http.NewServeMux()
handler.Register(mux)
var lsfCancel context.CancelFunc
if lsfObserver != nil {
lsfCtx, cancel := context.WithCancel(context.Background())
lsfCancel = cancel
lsfObserver.Start(lsfCtx)
}
httpSrv := &http.Server{
Addr: cfg.Listen,
Handler: mux,
BaseContext: func(net.Listener) context.Context {
return context.Background()
},
}
httpSrv.ErrorLog = pslog.LogLoggerWithLevel(svcfields.WithSubsystem(logger, "api.http.server"), pslog.ErrorLevel)
if cfg.MTLSEnabled() {
httpSrv.TLSConfig = buildServerTLS(bundle, clientTrustPool)
if err := http2.ConfigureServer(httpSrv, &http2.Server{MaxConcurrentStreams: uint32(cfg.HTTP2MaxConcurrentStreams)}); err != nil {
return nil, err
}
}
srv := &Server{
cfg: cfg,
baseLogger: logger,
logger: svcfields.WithSubsystem(logger, "server.lifecycle.core"),
backend: backend,
backendHash: backendHash,
serverBundle: bundle,
indexManager: indexManager,
handler: handler,
httpSrv: httpSrv,
httpShutdown: httpSrv.Shutdown,
clock: serverClock,
telemetry: telemetry,
readyCh: make(chan struct{}),
qrfController: qrfCtrl,
lsfObserver: lsfObserver,
lsfCancel: lsfCancel,
defaultCloseOpts: defaultCloseOptions(),
tcLeader: tcLeader,
tcCluster: tcClusterStore,
tcTrustPEM: tcTrustPEMBlobs,
tcCAPool: tcTrustPool,
defaultCAPool: bundleCAPool(bundle),
tcAuthEnabled: cfg.MTLSEnabled() && !cfg.TCDisableAuth,
tcAllowDefaultCA: cfg.TCAllowDefaultCA,
}
configClose := make([]CloseOption, 0, 2)
if cfg.DrainGraceSet || cfg.DrainGrace > 0 {
configClose = append(configClose, WithDrainLeases(cfg.DrainGrace))
}
if cfg.ShutdownTimeoutSet || cfg.ShutdownTimeout > 0 {
configClose = append(configClose, WithShutdownTimeout(cfg.ShutdownTimeout))
}
if len(configClose) > 0 {
srv.defaultCloseOpts = resolveCloseOptions(srv.defaultCloseOpts, configClose)
}
srv.drainFn = srv.performDrain
if len(o.closeDefaults) > 0 {
srv.defaultCloseOpts = resolveCloseOptions(srv.defaultCloseOpts, o.closeDefaults)
}
srvRef = srv
srv.markActivity()
return srv, nil
}
// Handler returns the underlying HTTP handler so lockd can be mounted inside an
// existing mux when embedding the server into another program.
func (s *Server) Handler() http.Handler {
return s.httpSrv.Handler
}
// Start begins serving requests and blocks until the server stops.
func (s *Server) Start() error {
if s.cfg.ListenProto == "unix" {
if err := os.Remove(s.cfg.Listen); err != nil && !errors.Is(err, os.ErrNotExist) {
return fmt.Errorf("remove stale unix socket: %w", err)
}
}
ln, err := net.Listen(s.cfg.ListenProto, s.cfg.Listen)
if err != nil {
return fmt.Errorf("listen (%s %s): %w", s.cfg.ListenProto, s.cfg.Listen, err)
}
s.listener = ln
if s.cfg.ListenProto == "unix" {
s.socketPath = s.cfg.Listen
}
if err := s.tcJoinPreflight(); err != nil {
_ = ln.Close()
s.listener = nil
return err
}
s.signalReady()
s.logger.Info("listening", "network", s.cfg.ListenProto, "address", ln.Addr().String(), "mtls", s.cfg.MTLSEnabled())
if s.tcLeader != nil {
self := strings.TrimSpace(s.cfg.SelfEndpoint)
seedEndpoints := tccluster.NormalizeEndpoints(append([]string(nil), s.cfg.TCJoinEndpoints...))
if self != "" && !tccluster.ContainsEndpoint(seedEndpoints, self) {
seedEndpoints = tccluster.NormalizeEndpoints(append(seedEndpoints, self))
}
if err := s.tcLeader.SetEndpoints(seedEndpoints); err != nil {
s.logger.Warn("tc.cluster.leader.seed_failed", "error", err)
}
}
if s.tcLeader != nil && s.tcLeaderCancel == nil {
tcCtx, cancel := context.WithCancel(context.Background())
s.tcLeaderCancel = cancel
s.tcLeader.Start(tcCtx)
}
s.startTCClusterMembership()
s.startRMRegistration()
if s.tcLeaderCancel != nil {
cancel := s.tcLeaderCancel
defer func() {
cancel()
s.tcLeaderCancel = nil
}()
}
defer s.stopTCClusterMembership()
defer s.stopRMRegistration()
s.startSweeper()
defer s.stopSweeper()
var serveErr error
serveListener := ln
if s.httpSrv.TLSConfig != nil || s.cfg.ConnguardEnabled {
cfg := connguard.ConnectionGuardConfig{
Enabled: s.cfg.ConnguardEnabled,
FailureThreshold: s.cfg.ConnguardFailureThreshold,
FailureWindow: s.cfg.ConnguardFailureWindow,
BlockDuration: s.cfg.ConnguardBlockDuration,
ProbeTimeout: s.cfg.ConnguardProbeTimeout,
}
guard := connguard.NewConnectionGuard(cfg, s.logger)
serveListener = guard.WrapListener(ln, s.httpSrv.TLSConfig)
}
if s.httpSrv.TLSConfig != nil && !s.cfg.ConnguardEnabled {
serveListener = tls.NewListener(serveListener, s.httpSrv.TLSConfig)
}
serveErr = s.httpSrv.Serve(serveListener)
s.recordServeErr(serveErr)
if errors.Is(serveErr, http.ErrServerClosed) {
return nil
}
if serveErr != nil {
return fmt.Errorf("http serve: %w", serveErr)
}
return nil
}
func (s *Server) startRMRegistration() {
if s == nil || s.rmRegisterCancel != nil {
return
}
self := strings.TrimSpace(s.cfg.SelfEndpoint)
if self == "" || s.backendHash == "" || s.tcCluster == nil {
return
}
ctx, cancel := context.WithCancel(context.Background())
s.rmRegisterCancel = cancel
s.rmRegisterDone.Add(1)
go func() {
defer s.rmRegisterDone.Done()
s.rmRegisterLoop(ctx)
}()
}
func (s *Server) startTCClusterMembership() {