-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
Copy pathreceive.go
1098 lines (936 loc) · 43.3 KB
/
receive.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 (c) The Thanos Authors.
// Licensed under the Apache License 2.0.
package main
import (
"context"
"fmt"
"net"
"os"
"path"
"strings"
"time"
"github.com/alecthomas/units"
extflag "github.com/efficientgo/tools/extkingpin"
"github.com/go-kit/log"
"github.com/go-kit/log/level"
grpc_logging "github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/logging"
"github.com/oklog/run"
"github.com/opentracing/opentracing-go"
"github.com/pkg/errors"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"github.com/prometheus/common/model"
"github.com/prometheus/prometheus/model/labels"
"github.com/prometheus/prometheus/model/relabel"
"github.com/prometheus/prometheus/tsdb"
"github.com/prometheus/prometheus/tsdb/wlog"
"github.com/thanos-io/objstore"
"github.com/thanos-io/objstore/client"
objstoretracing "github.com/thanos-io/objstore/tracing/opentracing"
"google.golang.org/grpc"
"gopkg.in/yaml.v2"
"github.com/thanos-io/thanos/pkg/block/metadata"
"github.com/thanos-io/thanos/pkg/component"
"github.com/thanos-io/thanos/pkg/exemplars"
"github.com/thanos-io/thanos/pkg/extgrpc"
"github.com/thanos-io/thanos/pkg/extgrpc/snappy"
"github.com/thanos-io/thanos/pkg/extkingpin"
"github.com/thanos-io/thanos/pkg/extprom"
"github.com/thanos-io/thanos/pkg/info"
"github.com/thanos-io/thanos/pkg/info/infopb"
"github.com/thanos-io/thanos/pkg/logging"
"github.com/thanos-io/thanos/pkg/prober"
"github.com/thanos-io/thanos/pkg/receive"
"github.com/thanos-io/thanos/pkg/runutil"
grpcserver "github.com/thanos-io/thanos/pkg/server/grpc"
httpserver "github.com/thanos-io/thanos/pkg/server/http"
"github.com/thanos-io/thanos/pkg/store"
storecache "github.com/thanos-io/thanos/pkg/store/cache"
"github.com/thanos-io/thanos/pkg/store/labelpb"
"github.com/thanos-io/thanos/pkg/tenancy"
"github.com/thanos-io/thanos/pkg/tls"
)
const (
compressionNone = "none"
metricNamesFilter = "metric-names-filter"
)
func registerReceive(app *extkingpin.App) {
cmd := app.Command(component.Receive.String(), "Accept Prometheus remote write API requests and write to local tsdb.")
conf := &receiveConfig{}
conf.registerFlag(cmd)
cmd.Setup(func(g *run.Group, logger log.Logger, reg *prometheus.Registry, tracer opentracing.Tracer, _ <-chan struct{}, debugLogging bool) error {
lset, err := parseFlagLabels(conf.labelStrs)
if err != nil {
return errors.Wrap(err, "parse labels")
}
if !model.LabelName.IsValid(model.LabelName(conf.tenantLabelName)) {
return errors.Errorf("unsupported format for tenant label name, got %s", conf.tenantLabelName)
}
if lset.Len() == 0 {
return errors.New("no external labels configured for receive, uniquely identifying external labels must be configured (ideally with `receive_` prefix); see https://thanos.io/tip/thanos/storage.md#external-labels for details.")
}
grpcLogOpts, logFilterMethods, err := logging.ParsegRPCOptions(conf.reqLogConfig)
if err != nil {
return errors.Wrap(err, "error while parsing config for request logging")
}
tsdbOpts := &tsdb.Options{
MinBlockDuration: int64(time.Duration(*conf.tsdbMinBlockDuration) / time.Millisecond),
MaxBlockDuration: int64(time.Duration(*conf.tsdbMaxBlockDuration) / time.Millisecond),
RetentionDuration: int64(time.Duration(*conf.retention) / time.Millisecond),
OutOfOrderTimeWindow: int64(time.Duration(*conf.tsdbOutOfOrderTimeWindow) / time.Millisecond),
MaxBytes: int64(conf.tsdbMaxBytes),
OutOfOrderCapMax: conf.tsdbOutOfOrderCapMax,
NoLockfile: conf.noLockFile,
WALCompression: wlog.ParseCompressionType(conf.walCompression, string(wlog.CompressionSnappy)),
MaxExemplars: conf.tsdbMaxExemplars,
EnableExemplarStorage: conf.tsdbMaxExemplars > 0,
HeadChunksWriteQueueSize: int(conf.tsdbWriteQueueSize),
EnableMemorySnapshotOnShutdown: conf.tsdbMemorySnapshotOnShutdown,
EnableNativeHistograms: conf.tsdbEnableNativeHistograms,
}
// Are we running in IngestorOnly, RouterOnly or RouterIngestor mode?
receiveMode := conf.determineMode()
return runReceive(
g,
logger,
debugLogging,
reg,
tracer,
grpcLogOpts,
logFilterMethods,
tsdbOpts,
lset,
component.Receive,
metadata.HashFunc(conf.hashFunc),
receiveMode,
conf,
)
})
}
func runReceive(
g *run.Group,
logger log.Logger,
debugLogging bool,
reg *prometheus.Registry,
tracer opentracing.Tracer,
grpcLogOpts []grpc_logging.Option,
logFilterMethods []string,
tsdbOpts *tsdb.Options,
lset labels.Labels,
comp component.SourceStoreAPI,
hashFunc metadata.HashFunc,
receiveMode receive.ReceiverMode,
conf *receiveConfig,
) error {
logger = log.With(logger, "component", "receive")
level.Info(logger).Log("mode", receiveMode, "msg", "running receive")
multiTSDBOptions := []receive.MultiTSDBOption{
receive.WithHeadExpandedPostingsCacheSize(conf.headExpandedPostingsCacheSize),
receive.WithBlockExpandedPostingsCacheSize(conf.compactedBlocksExpandedPostingsCacheSize),
}
for _, feature := range *conf.featureList {
if feature == metricNamesFilter {
multiTSDBOptions = append(multiTSDBOptions, receive.WithMetricNameFilterEnabled())
level.Info(logger).Log("msg", "metric name filter feature enabled")
}
}
rwTLSConfig, err := tls.NewServerConfig(log.With(logger, "protocol", "HTTP"), conf.rwServerCert, conf.rwServerKey, conf.rwServerClientCA, conf.rwServerTlsMinVersion)
if err != nil {
return err
}
dialOpts, err := extgrpc.StoreClientGRPCOpts(
logger,
reg,
tracer,
conf.rwClientSecure,
conf.rwClientSkipVerify,
conf.rwClientCert,
conf.rwClientKey,
conf.rwClientServerCA,
conf.rwClientServerName,
)
if err != nil {
return err
}
if conf.compression != compressionNone {
dialOpts = append(dialOpts, grpc.WithDefaultCallOptions(grpc.UseCompressor(conf.compression)))
}
if conf.grpcServiceConfig != "" {
dialOpts = append(dialOpts, grpc.WithDefaultServiceConfig(conf.grpcServiceConfig))
}
var bkt objstore.Bucket
confContentYaml, err := conf.objStoreConfig.Content()
if err != nil {
return err
}
// Has this thanos receive instance been configured to ingest metrics into a local TSDB?
enableIngestion := receiveMode == receive.IngestorOnly || receiveMode == receive.RouterIngestor
upload := len(confContentYaml) > 0
if enableIngestion {
if upload {
if tsdbOpts.MinBlockDuration != tsdbOpts.MaxBlockDuration {
if !conf.ignoreBlockSize {
return errors.Errorf("found that TSDB Max time is %d and Min time is %d. "+
"Compaction needs to be disabled (tsdb.min-block-duration = tsdb.max-block-duration)", tsdbOpts.MaxBlockDuration, tsdbOpts.MinBlockDuration)
}
level.Warn(logger).Log("msg", "flag to ignore min/max block duration flags differing is being used. If the upload of a 2h block fails and a tsdb compaction happens that block may be missing from your Thanos bucket storage.")
}
// The background shipper continuously scans the data directory and uploads
// new blocks to object storage service.
bkt, err = client.NewBucket(logger, confContentYaml, comp.String(), nil)
if err != nil {
return err
}
bkt = objstoretracing.WrapWithTraces(objstore.WrapWithMetrics(bkt, extprom.WrapRegistererWithPrefix("thanos_", reg), bkt.Name()))
} else {
level.Info(logger).Log("msg", "no supported bucket was configured, uploads will be disabled")
}
}
// TODO(brancz): remove after a couple of versions
// Migrate non-multi-tsdb capable storage to multi-tsdb disk layout.
if err := migrateLegacyStorage(logger, conf.dataDir, conf.defaultTenantID); err != nil {
return errors.Wrapf(err, "migrate legacy storage in %v to default tenant %v", conf.dataDir, conf.defaultTenantID)
}
relabelContentYaml, err := conf.relabelConfigPath.Content()
if err != nil {
return errors.Wrap(err, "get content of relabel configuration")
}
var relabelConfig []*relabel.Config
if err := yaml.Unmarshal(relabelContentYaml, &relabelConfig); err != nil {
return errors.Wrap(err, "parse relabel configuration")
}
var cache = storecache.NoopMatchersCache
if conf.matcherCacheSize > 0 {
cache, err = storecache.NewMatchersCache(storecache.WithSize(conf.matcherCacheSize), storecache.WithPromRegistry(reg))
if err != nil {
return errors.Wrap(err, "failed to create matchers cache")
}
multiTSDBOptions = append(multiTSDBOptions, receive.WithMatchersCache(cache))
}
dbs := receive.NewMultiTSDB(
conf.dataDir,
logger,
reg,
tsdbOpts,
lset,
conf.tenantLabelName,
bkt,
conf.allowOutOfOrderUpload,
hashFunc,
multiTSDBOptions...,
)
writer := receive.NewWriter(log.With(logger, "component", "receive-writer"), dbs, &receive.WriterOptions{
Intern: conf.writerInterning,
TooFarInFutureTimeWindow: int64(time.Duration(*conf.tsdbTooFarInFutureTimeWindow)),
})
var limitsConfig *receive.RootLimitsConfig
if conf.writeLimitsConfig != nil {
limitsContentYaml, err := conf.writeLimitsConfig.Content()
if err != nil {
return errors.Wrap(err, "get content of limit configuration")
}
limitsConfig, err = receive.ParseRootLimitConfig(limitsContentYaml)
if err != nil {
return errors.Wrap(err, "parse limit configuration")
}
}
limiter, err := receive.NewLimiter(conf.writeLimitsConfig, reg, receiveMode, log.With(logger, "component", "receive-limiter"), conf.limitsConfigReloadTimer)
if err != nil {
return errors.Wrap(err, "creating limiter")
}
webHandler := receive.NewHandler(log.With(logger, "component", "receive-handler"), &receive.Options{
Writer: writer,
ListenAddress: conf.rwAddress,
Registry: reg,
Endpoint: conf.endpoint,
TenantHeader: conf.tenantHeader,
TenantField: conf.tenantField,
DefaultTenantID: conf.defaultTenantID,
ReplicaHeader: conf.replicaHeader,
ReplicationFactor: conf.replicationFactor,
RelabelConfigs: relabelConfig,
ReceiverMode: receiveMode,
Tracer: tracer,
TLSConfig: rwTLSConfig,
SplitTenantLabelName: conf.splitTenantLabelName,
DialOpts: dialOpts,
ForwardTimeout: time.Duration(*conf.forwardTimeout),
MaxBackoff: time.Duration(*conf.maxBackoff),
TSDBStats: dbs,
Limiter: limiter,
AsyncForwardWorkerCount: conf.asyncForwardWorkerCount,
ReplicationProtocol: receive.ReplicationProtocol(conf.replicationProtocol),
OtlpEnableTargetInfo: conf.otlpEnableTargetInfo,
OtlpResourceAttributes: conf.otlpResourceAttributes,
})
grpcProbe := prober.NewGRPC()
httpProbe := prober.NewHTTP()
statusProber := prober.Combine(
httpProbe,
grpcProbe,
prober.NewInstrumentation(comp, logger, extprom.WrapRegistererWithPrefix("thanos_", reg)),
)
// Start all components while we wait for TSDB to open but only load
// initial config and mark ourselves as ready after it completes.
// hashringChangedChan signals when TSDB needs to be flushed and updated due to hashring config change.
hashringChangedChan := make(chan struct{}, 1)
if enableIngestion {
// uploadC signals when new blocks should be uploaded.
uploadC := make(chan struct{}, 1)
// uploadDone signals when uploading has finished.
uploadDone := make(chan struct{}, 1)
level.Debug(logger).Log("msg", "setting up TSDB")
{
if err := startTSDBAndUpload(g, logger, reg, dbs, uploadC, hashringChangedChan, upload, uploadDone, statusProber, bkt, receive.HashringAlgorithm(conf.hashringsAlgorithm)); err != nil {
return err
}
}
}
level.Debug(logger).Log("msg", "setting up hashring")
{
if err := setupHashring(g, logger, reg, conf, hashringChangedChan, webHandler, statusProber, enableIngestion, dbs); err != nil {
return err
}
}
level.Debug(logger).Log("msg", "setting up HTTP server")
{
srv := httpserver.New(logger, reg, comp, httpProbe,
httpserver.WithListen(*conf.httpBindAddr),
httpserver.WithGracePeriod(time.Duration(*conf.httpGracePeriod)),
httpserver.WithTLSConfig(*conf.httpTLSConfig),
)
g.Add(func() error {
statusProber.Healthy()
return srv.ListenAndServe()
}, func(err error) {
statusProber.NotReady(err)
defer statusProber.NotHealthy(err)
srv.Shutdown(err)
})
}
level.Debug(logger).Log("msg", "setting up gRPC server")
{
tlsCfg, err := tls.NewServerConfig(log.With(logger, "protocol", "gRPC"), conf.grpcConfig.tlsSrvCert, conf.grpcConfig.tlsSrvKey, conf.grpcConfig.tlsSrvClientCA, conf.grpcConfig.tlsMinVersion)
if err != nil {
return errors.Wrap(err, "setup gRPC server")
}
options := []store.ProxyStoreOption{
store.WithProxyStoreDebugLogging(debugLogging),
store.WithMatcherCache(cache),
store.WithoutDedup(),
}
proxy := store.NewProxyStore(
logger,
reg,
dbs.TSDBLocalClients,
comp,
labels.Labels{},
0,
store.LazyRetrieval,
options...,
)
mts := store.NewLimitedStoreServer(store.NewInstrumentedStoreServer(reg, proxy), reg, conf.storeRateLimits)
rw := store.ReadWriteTSDBStore{
StoreServer: mts,
WriteableStoreServer: webHandler,
}
infoSrv := info.NewInfoServer(
component.Receive.String(),
info.WithLabelSetFunc(func() []labelpb.ZLabelSet { return proxy.LabelSet() }),
info.WithStoreInfoFunc(func() (*infopb.StoreInfo, error) {
if httpProbe.IsReady() {
minTime, maxTime := proxy.TimeRange()
return &infopb.StoreInfo{
MinTime: minTime,
MaxTime: maxTime,
SupportsSharding: true,
SupportsWithoutReplicaLabels: true,
TsdbInfos: proxy.TSDBInfos(),
}, nil
}
return nil, errors.New("Not ready")
}),
info.WithExemplarsInfoFunc(),
)
srv := grpcserver.New(logger, receive.NewUnRegisterer(reg), tracer, grpcLogOpts, logFilterMethods, comp, grpcProbe,
grpcserver.WithServer(store.RegisterStoreServer(rw, logger)),
grpcserver.WithServer(store.RegisterWritableStoreServer(rw)),
grpcserver.WithServer(exemplars.RegisterExemplarsServer(exemplars.NewMultiTSDB(dbs.TSDBExemplars))),
grpcserver.WithServer(info.RegisterInfoServer(infoSrv)),
grpcserver.WithListen(conf.grpcConfig.bindAddress),
grpcserver.WithGracePeriod(conf.grpcConfig.gracePeriod),
grpcserver.WithMaxConnAge(conf.grpcConfig.maxConnectionAge),
grpcserver.WithTLSConfig(tlsCfg),
)
g.Add(
func() error {
level.Info(logger).Log("msg", "listening for StoreAPI and WritableStoreAPI gRPC", "address", conf.grpcConfig.bindAddress)
statusProber.Healthy()
return srv.ListenAndServe()
},
func(err error) {
statusProber.NotReady(err)
defer statusProber.NotHealthy(err)
srv.Shutdown(err)
},
)
}
level.Debug(logger).Log("msg", "setting up receive HTTP handler")
{
g.Add(
func() error {
return errors.Wrap(webHandler.Run(), "error starting web server")
},
func(err error) {
webHandler.Close()
},
)
}
if limitsConfig.AreHeadSeriesLimitsConfigured() {
level.Info(logger).Log("msg", "setting up periodic (every 15s) meta-monitoring query for limiting cache")
{
ctx, cancel := context.WithCancel(context.Background())
g.Add(func() error {
return runutil.Repeat(15*time.Second, ctx.Done(), func() error {
if err := limiter.HeadSeriesLimiter().QueryMetaMonitoring(ctx); err != nil {
level.Error(logger).Log("msg", "failed to query meta-monitoring", "err", err.Error())
}
return nil
})
}, func(err error) {
cancel()
})
}
}
level.Debug(logger).Log("msg", "setting up periodic tenant pruning")
{
ctx, cancel := context.WithCancel(context.Background())
g.Add(func() error {
pruneInterval := 2 * time.Duration(tsdbOpts.MaxBlockDuration) * time.Millisecond
return runutil.Repeat(time.Minute, ctx.Done(), func() error {
currentTime := time.Now()
currentTotalMinutes := currentTime.Hour()*60 + currentTime.Minute()
if currentTotalMinutes%int(pruneInterval.Minutes()) != 0 {
return nil
}
if err := dbs.Prune(ctx); err != nil {
level.Error(logger).Log("err", err)
}
return nil
})
}, func(err error) {
cancel()
})
}
{
if limiter.CanReload() {
ctx, cancel := context.WithCancel(context.Background())
g.Add(func() error {
level.Debug(logger).Log("msg", "limits config initialized with file watcher.")
if err := limiter.StartConfigReloader(ctx); err != nil {
return err
}
<-ctx.Done()
return nil
}, func(err error) {
cancel()
})
}
}
{
capNProtoWriter := receive.NewCapNProtoWriter(logger, dbs, &receive.CapNProtoWriterOptions{
TooFarInFutureTimeWindow: int64(time.Duration(*conf.tsdbTooFarInFutureTimeWindow)),
})
handler := receive.NewCapNProtoHandler(logger, capNProtoWriter)
listener, err := net.Listen("tcp", conf.replicationAddr)
if err != nil {
return err
}
server := receive.NewCapNProtoServer(listener, handler, logger)
g.Add(func() error {
return server.ListenAndServe()
}, func(err error) {
server.Shutdown()
if err := listener.Close(); err != nil {
level.Warn(logger).Log("msg", "Cap'n Proto server did not shut down gracefully", "err", err.Error())
}
})
}
level.Info(logger).Log("msg", "starting receiver")
return nil
}
// setupHashring sets up the hashring configuration provided.
// If no hashring is provided, we setup a single node hashring with local endpoint.
func setupHashring(g *run.Group,
logger log.Logger,
reg *prometheus.Registry,
conf *receiveConfig,
hashringChangedChan chan struct{},
webHandler *receive.Handler,
statusProber prober.Probe,
enableIngestion bool,
dbs *receive.MultiTSDB,
) error {
// Note: the hashring configuration watcher
// is the sender and thus closes the chan.
// In the single-node case, which has no configuration
// watcher, we close the chan ourselves.
updates := make(chan []receive.HashringConfig, 1)
algorithm := receive.HashringAlgorithm(conf.hashringsAlgorithm)
// The Hashrings config file path is given initializing config watcher.
if conf.hashringsFilePath != "" {
cw, err := receive.NewConfigWatcher(log.With(logger, "component", "config-watcher"), reg, conf.hashringsFilePath, *conf.refreshInterval)
if err != nil {
return errors.Wrap(err, "failed to initialize config watcher")
}
// Check the hashring configuration on before running the watcher.
if err := cw.ValidateConfig(); err != nil {
cw.Stop()
close(updates)
return errors.Wrap(err, "failed to validate hashring configuration file")
}
ctx, cancel := context.WithCancel(context.Background())
g.Add(func() error {
return receive.ConfigFromWatcher(ctx, updates, cw)
}, func(error) {
cancel()
})
} else {
var (
cf []receive.HashringConfig
err error
)
// The Hashrings config file content given initialize configuration from content.
if len(conf.hashringsFileContent) > 0 {
cf, err = receive.ParseConfig([]byte(conf.hashringsFileContent))
if err != nil {
close(updates)
return errors.Wrap(err, "failed to validate hashring configuration content")
}
}
cancel := make(chan struct{})
g.Add(func() error {
defer close(updates)
updates <- cf
<-cancel
return nil
}, func(error) {
close(cancel)
})
}
cancel := make(chan struct{})
g.Add(func() error {
if enableIngestion {
defer close(hashringChangedChan)
}
for {
select {
case c, ok := <-updates:
if !ok {
return nil
}
if c == nil {
webHandler.Hashring(receive.SingleNodeHashring(conf.endpoint))
level.Info(logger).Log("msg", "Empty hashring config. Set up single node hashring.")
} else {
h, err := receive.NewMultiHashring(algorithm, conf.replicationFactor, c)
if err != nil {
return errors.Wrap(err, "unable to create new hashring from config")
}
webHandler.Hashring(h)
level.Info(logger).Log("msg", "Set up hashring for the given hashring config.")
}
if err := dbs.SetHashringConfig(c); err != nil {
return errors.Wrap(err, "failed to set hashring config in MultiTSDB")
}
// If ingestion is enabled, send a signal to TSDB to flush.
if enableIngestion {
hashringChangedChan <- struct{}{}
} else {
// If not, just signal we are ready (this is important during first hashring load)
statusProber.Ready()
}
case <-cancel:
return nil
}
}
}, func(err error) {
close(cancel)
},
)
return nil
}
// startTSDBAndUpload starts the multi-TSDB and sets up the rungroup to flush the TSDB and reload on hashring change.
// It also upload blocks to object store, if upload is enabled.
func startTSDBAndUpload(g *run.Group,
logger log.Logger,
reg *prometheus.Registry,
dbs *receive.MultiTSDB,
uploadC chan struct{},
hashringChangedChan chan struct{},
upload bool,
uploadDone chan struct{},
statusProber prober.Probe,
bkt objstore.Bucket,
hashringAlgorithm receive.HashringAlgorithm,
) error {
log.With(logger, "component", "storage")
dbUpdatesStarted := promauto.With(reg).NewCounter(prometheus.CounterOpts{
Name: "thanos_receive_multi_db_updates_attempted_total",
Help: "Number of Multi DB attempted reloads with flush and potential upload due to hashring changes",
})
dbUpdatesCompleted := promauto.With(reg).NewCounter(prometheus.CounterOpts{
Name: "thanos_receive_multi_db_updates_completed_total",
Help: "Number of Multi DB completed reloads with flush and potential upload due to hashring changes",
})
level.Debug(logger).Log("msg", "removing storage lock files if any")
if err := dbs.RemoveLockFilesIfAny(); err != nil {
return errors.Wrap(err, "remove storage lock files")
}
// TSDBs reload logic, listening on hashring changes.
cancel := make(chan struct{})
g.Add(func() error {
defer close(uploadC)
// Before quitting, ensure the WAL is flushed and the DBs are closed.
defer func() {
level.Info(logger).Log("msg", "shutting down storage")
if err := dbs.Flush(); err != nil {
level.Error(logger).Log("err", err, "msg", "failed to flush storage")
} else {
level.Info(logger).Log("msg", "storage is flushed successfully")
}
if err := dbs.Close(); err != nil {
level.Error(logger).Log("err", err, "msg", "failed to close storage")
return
}
level.Info(logger).Log("msg", "storage is closed")
}()
var initialized bool
for {
select {
case <-cancel:
return nil
case _, ok := <-hashringChangedChan:
if !ok {
return nil
}
// When using Ketama as the hashring algorithm, there is no need to flush the TSDB head.
// If new receivers were added to the hashring, existing receivers will not need to
// ingest additional series.
// If receivers are removed from the hashring, existing receivers will only need
// to ingest a subset of the series that were assigned to the removed receivers.
// As a result, changing the hashring produces no churn, hence no need to force
// head compaction and upload.
flushHead := !initialized || hashringAlgorithm != receive.AlgorithmKetama
if flushHead {
msg := "hashring has changed; server is not ready to receive requests"
statusProber.NotReady(errors.New(msg))
level.Info(logger).Log("msg", msg)
level.Info(logger).Log("msg", "updating storage")
dbUpdatesStarted.Inc()
if err := dbs.Flush(); err != nil {
return errors.Wrap(err, "flushing storage")
}
if err := dbs.Open(); err != nil {
return errors.Wrap(err, "opening storage")
}
if upload {
uploadC <- struct{}{}
<-uploadDone
}
dbUpdatesCompleted.Inc()
statusProber.Ready()
level.Info(logger).Log("msg", "storage started, and server is ready to receive requests")
dbUpdatesCompleted.Inc()
}
initialized = true
}
}
}, func(err error) {
close(cancel)
})
if upload {
logger := log.With(logger, "component", "uploader")
upload := func(ctx context.Context) error {
level.Debug(logger).Log("msg", "upload phase starting")
start := time.Now()
uploaded, err := dbs.Sync(ctx)
if err != nil {
level.Warn(logger).Log("msg", "upload failed", "elapsed", time.Since(start), "err", err)
return err
}
level.Debug(logger).Log("msg", "upload phase done", "uploaded", uploaded, "elapsed", time.Since(start))
return nil
}
{
level.Info(logger).Log("msg", "upload enabled, starting initial sync")
if err := upload(context.Background()); err != nil {
return errors.Wrap(err, "initial upload failed")
}
level.Info(logger).Log("msg", "initial sync done")
}
{
ctx, cancel := context.WithCancel(context.Background())
g.Add(func() error {
// Ensure we clean up everything properly.
defer func() {
runutil.CloseWithLogOnErr(logger, bkt, "bucket client")
}()
// Before quitting, ensure all blocks are uploaded.
defer func() {
<-uploadC // Closed by storage routine when it's done.
level.Info(logger).Log("msg", "uploading the final cut block before exiting")
ctx, cancel := context.WithCancel(context.Background())
uploaded, err := dbs.Sync(ctx)
if err != nil {
cancel()
level.Error(logger).Log("msg", "the final upload failed", "err", err)
return
}
cancel()
level.Info(logger).Log("msg", "the final cut block was uploaded", "uploaded", uploaded)
}()
defer close(uploadDone)
// Run the uploader in a loop.
tick := time.NewTicker(30 * time.Second)
defer tick.Stop()
for {
select {
case <-ctx.Done():
return nil
case <-uploadC:
// Upload on demand.
if err := upload(ctx); err != nil {
level.Error(logger).Log("msg", "on demand upload failed", "err", err)
}
uploadDone <- struct{}{}
case <-tick.C:
if err := upload(ctx); err != nil {
level.Error(logger).Log("msg", "recurring upload failed", "err", err)
}
}
}
}, func(error) {
cancel()
})
}
}
return nil
}
func migrateLegacyStorage(logger log.Logger, dataDir, defaultTenantID string) error {
defaultTenantDataDir := path.Join(dataDir, defaultTenantID)
if _, err := os.Stat(defaultTenantDataDir); !os.IsNotExist(err) {
level.Info(logger).Log("msg", "default tenant data dir already present, not attempting to migrate storage")
return nil
}
if _, err := os.Stat(dataDir); os.IsNotExist(err) {
level.Info(logger).Log("msg", "no existing storage found, no data migration attempted")
return nil
}
level.Info(logger).Log("msg", "found legacy storage, migrating to multi-tsdb layout with default tenant", "defaultTenantID", defaultTenantID)
files, err := os.ReadDir(dataDir)
if err != nil {
return errors.Wrapf(err, "read legacy data dir: %v", dataDir)
}
if err := os.MkdirAll(defaultTenantDataDir, 0750); err != nil {
return errors.Wrapf(err, "create default tenant data dir: %v", defaultTenantDataDir)
}
for _, f := range files {
from := path.Join(dataDir, f.Name())
to := path.Join(defaultTenantDataDir, f.Name())
if err := os.Rename(from, to); err != nil {
return errors.Wrapf(err, "migrate file from %v to %v", from, to)
}
}
return nil
}
type receiveConfig struct {
httpBindAddr *string
httpGracePeriod *model.Duration
httpTLSConfig *string
grpcConfig grpcConfig
replicationAddr string
rwAddress string
rwServerCert string
rwServerKey string
rwServerClientCA string
rwClientCert string
rwClientKey string
rwClientSecure bool
rwClientServerCA string
rwClientServerName string
rwClientSkipVerify bool
rwServerTlsMinVersion string
dataDir string
labelStrs []string
objStoreConfig *extflag.PathOrContent
retention *model.Duration
hashringsFilePath string
hashringsFileContent string
hashringsAlgorithm string
refreshInterval *model.Duration
endpoint string
tenantHeader string
tenantField string
tenantLabelName string
defaultTenantID string
replicaHeader string
replicationFactor uint64
forwardTimeout *model.Duration
maxBackoff *model.Duration
compression string
replicationProtocol string
grpcServiceConfig string
tsdbMinBlockDuration *model.Duration
tsdbMaxBlockDuration *model.Duration
tsdbTooFarInFutureTimeWindow *model.Duration
tsdbOutOfOrderTimeWindow *model.Duration
tsdbOutOfOrderCapMax int64
tsdbAllowOverlappingBlocks bool
tsdbMaxExemplars int64
tsdbMaxBytes units.Base2Bytes
tsdbWriteQueueSize int64
tsdbMemorySnapshotOnShutdown bool
tsdbEnableNativeHistograms bool
walCompression bool
noLockFile bool
writerInterning bool
splitTenantLabelName string
hashFunc string
ignoreBlockSize bool
allowOutOfOrderUpload bool
reqLogConfig *extflag.PathOrContent
relabelConfigPath *extflag.PathOrContent
writeLimitsConfig *extflag.PathOrContent
storeRateLimits store.SeriesSelectLimits
limitsConfigReloadTimer time.Duration
asyncForwardWorkerCount uint
matcherCacheSize int
featureList *[]string
headExpandedPostingsCacheSize uint64
compactedBlocksExpandedPostingsCacheSize uint64
otlpEnableTargetInfo bool
otlpResourceAttributes []string
}
func (rc *receiveConfig) registerFlag(cmd extkingpin.FlagClause) {
rc.httpBindAddr, rc.httpGracePeriod, rc.httpTLSConfig = extkingpin.RegisterHTTPFlags(cmd)
rc.grpcConfig.registerFlag(cmd)
rc.storeRateLimits.RegisterFlags(cmd)
cmd.Flag("remote-write.address", "Address to listen on for remote write requests.").
Default("0.0.0.0:19291").StringVar(&rc.rwAddress)
cmd.Flag("remote-write.server-tls-cert", "TLS Certificate for HTTP server, leave blank to disable TLS.").Default("").StringVar(&rc.rwServerCert)
cmd.Flag("remote-write.server-tls-key", "TLS Key for the HTTP server, leave blank to disable TLS.").Default("").StringVar(&rc.rwServerKey)
cmd.Flag("remote-write.server-tls-client-ca", "TLS CA to verify clients against. If no client CA is specified, there is no client verification on server side. (tls.NoClientCert)").Default("").StringVar(&rc.rwServerClientCA)
cmd.Flag("remote-write.server-tls-min-version", "TLS version for the gRPC server, leave blank to default to TLS 1.3, allow values: [\"1.0\", \"1.1\", \"1.2\", \"1.3\"]").Default("1.3").StringVar(&rc.rwServerTlsMinVersion)
cmd.Flag("remote-write.client-tls-cert", "TLS Certificates to use to identify this client to the server.").Default("").StringVar(&rc.rwClientCert)
cmd.Flag("remote-write.client-tls-key", "TLS Key for the client's certificate.").Default("").StringVar(&rc.rwClientKey)
cmd.Flag("remote-write.client-tls-secure", "Use TLS when talking to the other receivers.").Default("false").BoolVar(&rc.rwClientSecure)
cmd.Flag("remote-write.client-tls-skip-verify", "Disable TLS certificate verification when talking to the other receivers i.e self signed, signed by fake CA.").Default("false").BoolVar(&rc.rwClientSkipVerify)
cmd.Flag("remote-write.client-tls-ca", "TLS CA Certificates to use to verify servers.").Default("").StringVar(&rc.rwClientServerCA)
cmd.Flag("remote-write.client-server-name", "Server name to verify the hostname on the returned TLS certificates. See https://tools.ietf.org/html/rfc4366#section-3.1").Default("").StringVar(&rc.rwClientServerName)
cmd.Flag("tsdb.path", "Data directory of TSDB.").
Default("./data").StringVar(&rc.dataDir)
cmd.Flag("label", "External labels to announce. This flag will be removed in the future when handling multiple tsdb instances is added.").PlaceHolder("key=\"value\"").StringsVar(&rc.labelStrs)
rc.objStoreConfig = extkingpin.RegisterCommonObjStoreFlags(cmd, "", false)
rc.retention = extkingpin.ModelDuration(cmd.Flag("tsdb.retention", "How long to retain raw samples on local storage. 0d - disables the retention policy (i.e. infinite retention). For more details on how retention is enforced for individual tenants, please refer to the Tenant lifecycle management section in the Receive documentation: https://thanos.io/tip/components/receive.md/#tenant-lifecycle-management").Default("15d"))
cmd.Flag("receive.hashrings-file", "Path to file that contains the hashring configuration. A watcher is initialized to watch changes and update the hashring dynamically.").PlaceHolder("<path>").StringVar(&rc.hashringsFilePath)
cmd.Flag("receive.hashrings", "Alternative to 'receive.hashrings-file' flag (lower priority). Content of file that contains the hashring configuration.").PlaceHolder("<content>").StringVar(&rc.hashringsFileContent)
hashringAlgorithmsHelptext := strings.Join([]string{string(receive.AlgorithmHashmod), string(receive.AlgorithmKetama)}, ", ")
cmd.Flag("receive.hashrings-algorithm", "The algorithm used when distributing series in the hashrings. Must be one of "+hashringAlgorithmsHelptext+". Will be overwritten by the tenant-specific algorithm in the hashring config.").
Default(string(receive.AlgorithmHashmod)).
EnumVar(&rc.hashringsAlgorithm, string(receive.AlgorithmHashmod), string(receive.AlgorithmKetama))
rc.refreshInterval = extkingpin.ModelDuration(cmd.Flag("receive.hashrings-file-refresh-interval", "Refresh interval to re-read the hashring configuration file. (used as a fallback)").
Default("5m"))
cmd.Flag("receive.local-endpoint", "Endpoint of local receive node. Used to identify the local node in the hashring configuration. If it's empty AND hashring configuration was provided, it means that receive will run in RoutingOnly mode.").StringVar(&rc.endpoint)
cmd.Flag("receive.tenant-header", "HTTP header to determine tenant for write requests.").Default(tenancy.DefaultTenantHeader).StringVar(&rc.tenantHeader)
cmd.Flag("receive.tenant-certificate-field", "Use TLS client's certificate field to determine tenant for write requests. Must be one of "+tenancy.CertificateFieldOrganization+", "+tenancy.CertificateFieldOrganizationalUnit+" or "+tenancy.CertificateFieldCommonName+". This setting will cause the receive.tenant-header flag value to be ignored.").Default("").EnumVar(&rc.tenantField, "", tenancy.CertificateFieldOrganization, tenancy.CertificateFieldOrganizationalUnit, tenancy.CertificateFieldCommonName)
cmd.Flag("receive.default-tenant-id", "Default tenant ID to use when none is provided via a header.").Default(tenancy.DefaultTenant).StringVar(&rc.defaultTenantID)
cmd.Flag("receive.split-tenant-label-name", "Label name through which the request will be split into multiple tenants. This takes precedence over the HTTP header.").Default("").StringVar(&rc.splitTenantLabelName)
cmd.Flag("receive.tenant-label-name", "Label name through which the tenant will be announced.").Default(tenancy.DefaultTenantLabel).StringVar(&rc.tenantLabelName)
cmd.Flag("receive.replica-header", "HTTP header specifying the replica number of a write request.").Default(receive.DefaultReplicaHeader).StringVar(&rc.replicaHeader)
cmd.Flag("receive.forward.async-workers", "Number of concurrent workers processing forwarding of remote-write requests.").Default("5").UintVar(&rc.asyncForwardWorkerCount)
compressionOptions := strings.Join([]string{snappy.Name, compressionNone}, ", ")
cmd.Flag("receive.grpc-compression", "Compression algorithm to use for gRPC requests to other receivers. Must be one of: "+compressionOptions).Default(snappy.Name).EnumVar(&rc.compression, snappy.Name, compressionNone)
cmd.Flag("receive.replication-factor", "How many times to replicate incoming write requests.").Default("1").Uint64Var(&rc.replicationFactor)
replicationProtocols := []string{string(receive.ProtobufReplication), string(receive.CapNProtoReplication)}
cmd.Flag("receive.replication-protocol", "The protocol to use for replicating remote-write requests. One of "+strings.Join(replicationProtocols, ", ")).
Default(string(receive.ProtobufReplication)).
EnumVar(&rc.replicationProtocol, replicationProtocols...)
cmd.Flag("receive.capnproto-address", "Address for the Cap'n Proto server.").Default(fmt.Sprintf("0.0.0.0:%s", receive.DefaultCapNProtoPort)).StringVar(&rc.replicationAddr)
cmd.Flag("receive.grpc-service-config", "gRPC service configuration file or content in JSON format. See https://github.com/grpc/grpc/blob/master/doc/service_config.md").PlaceHolder("<content>").Default("").StringVar(&rc.grpcServiceConfig)
rc.forwardTimeout = extkingpin.ModelDuration(cmd.Flag("receive-forward-timeout", "Timeout for each forward request.").Default("5s").Hidden())
rc.maxBackoff = extkingpin.ModelDuration(cmd.Flag("receive-forward-max-backoff", "Maximum backoff for each forward fan-out request").Default("5s").Hidden())
rc.relabelConfigPath = extflag.RegisterPathOrContent(cmd, "receive.relabel-config", "YAML file that contains relabeling configuration.", extflag.WithEnvSubstitution())