-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
handler.go
1535 lines (1336 loc) · 44.9 KB
/
handler.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 receive
import (
"bytes"
"context"
"crypto/tls"
"fmt"
"io"
stdlog "log"
"math"
"net"
"net/http"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/go-kit/log"
"github.com/go-kit/log/level"
"github.com/gogo/protobuf/proto"
"github.com/jpillora/backoff"
"github.com/klauspost/compress/s2"
"github.com/mwitkow/go-conntrack"
"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/route"
"github.com/prometheus/prometheus/model/labels"
"github.com/prometheus/prometheus/model/relabel"
"github.com/prometheus/prometheus/storage"
"github.com/prometheus/prometheus/tsdb"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/trace"
"golang.org/x/exp/slices"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"github.com/thanos-io/thanos/pkg/api"
statusapi "github.com/thanos-io/thanos/pkg/api/status"
"github.com/thanos-io/thanos/pkg/logging"
"github.com/thanos-io/thanos/pkg/receive/writecapnp"
extpromhttp "github.com/thanos-io/thanos/pkg/extprom/http"
"github.com/thanos-io/thanos/pkg/pool"
"github.com/thanos-io/thanos/pkg/runutil"
"github.com/thanos-io/thanos/pkg/server/http/middleware"
"github.com/thanos-io/thanos/pkg/store/labelpb"
"github.com/thanos-io/thanos/pkg/store/storepb"
"github.com/thanos-io/thanos/pkg/store/storepb/prompb"
"github.com/thanos-io/thanos/pkg/tenancy"
"github.com/thanos-io/thanos/pkg/tracing"
)
const (
// DefaultStatsLimit is the default value used for limiting tenant stats.
DefaultStatsLimit = 10
// DefaultReplicaHeader is the default header used to designate the replica count of a write request.
DefaultReplicaHeader = "THANOS-REPLICA"
// AllTenantsQueryParam is the query parameter for getting TSDB stats for all tenants.
AllTenantsQueryParam = "all_tenants"
// LimitStatsQueryParam is the query parameter for limiting the amount of returned TSDB stats.
LimitStatsQueryParam = "limit"
// Labels for metrics.
labelSuccess = "success"
labelError = "error"
)
type ReplicationProtocol string
const (
ProtobufReplication ReplicationProtocol = "protobuf"
CapNProtoReplication ReplicationProtocol = "capnproto"
)
var (
// errConflict is returned whenever an operation fails due to any conflict-type error.
errConflict = errors.New("conflict")
errBadReplica = errors.New("request replica exceeds receiver replication factor")
errNotReady = errors.New("target not ready")
errUnavailable = errors.New("target not available")
errInternal = errors.New("internal error")
)
type WriteableStoreAsyncClient interface {
storepb.WriteableStoreClient
RemoteWriteAsync(context.Context, *storepb.WriteRequest, endpointReplica, []int, chan writeResponse, func(error))
}
// Options for the web Handler.
type Options struct {
Writer *Writer
ListenAddress string
Registry *prometheus.Registry
TenantHeader string
TenantField string
DefaultTenantID string
ReplicaHeader string
Endpoint string
ReplicationFactor uint64
SplitTenantLabelName string
ReceiverMode ReceiverMode
Tracer opentracing.Tracer
TLSConfig *tls.Config
DialOpts []grpc.DialOption
ForwardTimeout time.Duration
MaxBackoff time.Duration
RelabelConfigs []*relabel.Config
TSDBStats TSDBStats
Limiter *Limiter
AsyncForwardWorkerCount uint
ReplicationProtocol ReplicationProtocol
}
// Handler serves a Prometheus remote write receiving HTTP endpoint.
type Handler struct {
logger log.Logger
writer *Writer
router *route.Router
options *Options
splitTenantLabelName string
httpSrv *http.Server
mtx sync.RWMutex
hashring Hashring
peers peersContainer
receiverMode ReceiverMode
forwardRequests *prometheus.CounterVec
replications *prometheus.CounterVec
replicationFactor prometheus.Gauge
writeSamplesTotal *prometheus.HistogramVec
writeTimeseriesTotal *prometheus.HistogramVec
Limiter *Limiter
}
func NewHandler(logger log.Logger, o *Options) *Handler {
if logger == nil {
logger = log.NewNopLogger()
}
var registerer prometheus.Registerer = nil
if o.Registry != nil {
registerer = o.Registry
}
workers := o.AsyncForwardWorkerCount
if workers == 0 {
workers = 1
}
level.Info(logger).Log("msg", "Starting receive handler with async forward workers", "workers", workers)
h := &Handler{
logger: logger,
writer: o.Writer,
router: route.New(),
options: o,
splitTenantLabelName: o.SplitTenantLabelName,
peers: newPeerGroup(
logger,
backoff.Backoff{
Factor: 2,
Min: 100 * time.Millisecond,
Max: o.MaxBackoff,
Jitter: true,
},
promauto.With(registerer).NewHistogram(
prometheus.HistogramOpts{
Name: "thanos_receive_forward_delay_seconds",
Help: "The delay between the time the request was received and the time it was forwarded to a worker. ",
Buckets: prometheus.ExponentialBuckets(0.001, 2, 16),
},
),
workers,
o.ReplicationProtocol,
o.DialOpts...),
receiverMode: o.ReceiverMode,
Limiter: o.Limiter,
forwardRequests: promauto.With(registerer).NewCounterVec(
prometheus.CounterOpts{
Name: "thanos_receive_forward_requests_total",
Help: "The number of forward requests.",
}, []string{"result"},
),
replications: promauto.With(registerer).NewCounterVec(
prometheus.CounterOpts{
Name: "thanos_receive_replications_total",
Help: "The number of replication operations done by the receiver. The success of replication is fulfilled when a quorum is met.",
}, []string{"result"},
),
replicationFactor: promauto.With(registerer).NewGauge(
prometheus.GaugeOpts{
Name: "thanos_receive_replication_factor",
Help: "The number of times to replicate incoming write requests.",
},
),
writeTimeseriesTotal: promauto.With(registerer).NewHistogramVec(
prometheus.HistogramOpts{
Namespace: "thanos",
Subsystem: "receive",
Name: "write_timeseries",
Help: "The number of timeseries received in the incoming write requests.",
Buckets: []float64{10, 50, 100, 500, 1000, 5000, 10000},
}, []string{"code", "tenant"},
),
writeSamplesTotal: promauto.With(registerer).NewHistogramVec(
prometheus.HistogramOpts{
Namespace: "thanos",
Subsystem: "receive",
Name: "write_samples",
Help: "The number of sampled received in the incoming write requests.",
Buckets: []float64{10, 50, 100, 500, 1000, 5000, 10000},
}, []string{"code", "tenant"},
),
}
h.forwardRequests.WithLabelValues(labelSuccess)
h.forwardRequests.WithLabelValues(labelError)
h.replications.WithLabelValues(labelSuccess)
h.replications.WithLabelValues(labelError)
if o.ReplicationFactor > 1 {
h.replicationFactor.Set(float64(o.ReplicationFactor))
} else {
h.replicationFactor.Set(1)
}
ins := extpromhttp.NewNopInstrumentationMiddleware()
if o.Registry != nil {
var buckets = []float64{0.001, 0.005, 0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09, 0.1, 0.25, 0.5, 0.75, 1, 2, 3, 4, 5}
const bucketIncrement = 2.0
for curMax := 5.0 + bucketIncrement; curMax < o.ForwardTimeout.Seconds(); curMax += bucketIncrement {
buckets = append(buckets, curMax)
}
if buckets[len(buckets)-1] < o.ForwardTimeout.Seconds() {
buckets = append(buckets, o.ForwardTimeout.Seconds())
}
ins = extpromhttp.NewTenantInstrumentationMiddleware(
o.TenantHeader,
o.DefaultTenantID,
o.Registry,
buckets,
)
}
readyf := h.testReady
instrf := func(name string, next func(w http.ResponseWriter, r *http.Request)) http.HandlerFunc {
next = ins.NewHandler(name, http.HandlerFunc(next))
if o.Tracer != nil {
next = tracing.HTTPMiddleware(o.Tracer, name, logger, http.HandlerFunc(next))
}
return next
}
h.router.Post(
"/api/v1/receive",
instrf(
"receive",
readyf(
middleware.RequestID(
http.HandlerFunc(h.receiveHTTP),
),
),
),
)
statusAPI := statusapi.New(statusapi.Options{
GetStats: h.getStats,
Registry: h.options.Registry,
})
statusAPI.Register(h.router, o.Tracer, logger, ins, logging.NewHTTPServerMiddleware(logger))
errlog := stdlog.New(log.NewStdlibAdapter(level.Error(h.logger)), "", 0)
h.httpSrv = &http.Server{
Handler: h.router,
ErrorLog: errlog,
TLSConfig: h.options.TLSConfig,
}
return h
}
// Hashring sets the hashring for the handler and marks the hashring as ready.
// The hashring must be set to a non-nil value in order for the
// handler to be ready and usable.
// If the hashring is nil, then the handler is marked as not ready.
func (h *Handler) Hashring(hashring Hashring) {
h.mtx.Lock()
defer h.mtx.Unlock()
if h.hashring != nil {
previousNodes := h.hashring.Nodes()
newNodes := hashring.Nodes()
disappearedNodes := getSortedStringSliceDiff(previousNodes, newNodes)
for _, node := range disappearedNodes {
if err := h.peers.close(node); err != nil {
level.Error(h.logger).Log("msg", "closing gRPC connection failed, we might have leaked a file descriptor", "addr", node, "err", err.Error())
}
}
}
h.hashring = hashring
h.peers.reset()
}
// getSortedStringSliceDiff returns items which are in slice1 but not in slice2.
// The returned slice also only contains unique items i.e. it is a set.
func getSortedStringSliceDiff(slice1, slice2 []Endpoint) []Endpoint {
slice1Items := make(map[Endpoint]struct{}, len(slice1))
slice2Items := make(map[Endpoint]struct{}, len(slice2))
for _, s1 := range slice1 {
slice1Items[s1] = struct{}{}
}
for _, s2 := range slice2 {
slice2Items[s2] = struct{}{}
}
var difference = make([]Endpoint, 0)
for s1 := range slice1Items {
_, s2Contains := slice2Items[s1]
if s2Contains {
continue
}
difference = append(difference, s1)
}
slices.SortFunc(difference, func(a, b Endpoint) int {
return strings.Compare(a.String(), b.String())
})
return difference
}
// Verifies whether the server is ready or not.
func (h *Handler) isReady() bool {
h.mtx.RLock()
hr := h.hashring != nil
sr := h.writer != nil
h.mtx.RUnlock()
return sr && hr
}
// Checks if server is ready, calls f if it is, returns 503 if it is not.
func (h *Handler) testReady(f http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if h.isReady() {
f(w, r)
return
}
w.WriteHeader(http.StatusServiceUnavailable)
_, err := fmt.Fprintf(w, "Service Unavailable")
if err != nil {
h.logger.Log("msg", "failed to write to response body", "err", err)
}
}
}
func getStatsLimitParameter(r *http.Request) (int, error) {
statsLimitStr := r.URL.Query().Get(LimitStatsQueryParam)
if statsLimitStr == "" {
return DefaultStatsLimit, nil
}
statsLimit, err := strconv.ParseInt(statsLimitStr, 10, 0)
if err != nil {
return 0, fmt.Errorf("unable to parse '%s' parameter: %w", LimitStatsQueryParam, err)
}
if statsLimit > math.MaxInt {
return 0, fmt.Errorf("'%s' parameter is larger than %d", LimitStatsQueryParam, math.MaxInt)
}
return int(statsLimit), nil
}
func (h *Handler) getStats(r *http.Request, statsByLabelName string) ([]statusapi.TenantStats, *api.ApiError) {
if !h.isReady() {
return nil, &api.ApiError{Typ: api.ErrorInternal, Err: fmt.Errorf("service unavailable")}
}
tenantID := r.Header.Get(h.options.TenantHeader)
getAllTenantStats := r.FormValue(AllTenantsQueryParam) == "true"
if getAllTenantStats && tenantID != "" {
err := fmt.Errorf("using both the %s parameter and the %s header is not supported", AllTenantsQueryParam, h.options.TenantHeader)
return nil, &api.ApiError{Typ: api.ErrorBadData, Err: err}
}
statsLimit, err := getStatsLimitParameter(r)
if err != nil {
return nil, &api.ApiError{Typ: api.ErrorBadData, Err: err}
}
if getAllTenantStats {
return h.options.TSDBStats.TenantStats(statsLimit, statsByLabelName), nil
}
if tenantID == "" {
tenantID = h.options.DefaultTenantID
}
return h.options.TSDBStats.TenantStats(statsLimit, statsByLabelName, tenantID), nil
}
// Close stops the Handler.
func (h *Handler) Close() {
_ = h.peers.Close()
runutil.CloseWithLogOnErr(h.logger, h.httpSrv, "receive HTTP server")
}
// Run serves the HTTP endpoints.
func (h *Handler) Run() error {
level.Info(h.logger).Log("msg", "Start listening for connections", "address", h.options.ListenAddress)
listener, err := net.Listen("tcp", h.options.ListenAddress)
if err != nil {
return err
}
// Monitor incoming connections with conntrack.
listener = conntrack.NewListener(listener,
conntrack.TrackWithName("http"),
conntrack.TrackWithTracing())
if h.options.TLSConfig != nil {
level.Info(h.logger).Log("msg", "Serving HTTPS", "address", h.options.ListenAddress)
// Cert & Key are already being passed in via TLSConfig.
return h.httpSrv.ServeTLS(listener, "", "")
}
level.Info(h.logger).Log("msg", "Serving plain HTTP", "address", h.options.ListenAddress)
return h.httpSrv.Serve(listener)
}
// replica encapsulates the replica number of a request and if the request is
// already replicated.
type replica struct {
n uint64
replicated bool
}
// endpointReplica is a pair of a receive endpoint and a write request replica.
type endpointReplica struct {
endpoint Endpoint
replica uint64
}
type trackedSeries struct {
seriesIDs []int
timeSeries []prompb.TimeSeries
}
type writeResponse struct {
seriesIDs []int
err error
er endpointReplica
}
func newWriteResponse(seriesIDs []int, err error, er endpointReplica) writeResponse {
return writeResponse{
seriesIDs: seriesIDs,
err: err,
er: er,
}
}
func (h *Handler) receiveHTTP(w http.ResponseWriter, r *http.Request) {
var err error
span, ctx := tracing.StartSpan(r.Context(), "receive_http")
span.SetTag("receiver.mode", string(h.receiverMode))
defer span.Finish()
tenantHTTP, err := tenancy.GetTenantFromHTTP(r, h.options.TenantHeader, h.options.DefaultTenantID, h.options.TenantField)
if err != nil {
level.Error(h.logger).Log("msg", "error getting tenant from HTTP", "err", err)
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
tLogger := log.With(h.logger, "tenant", tenantHTTP)
span.SetTag("tenant", tenantHTTP)
writeGate := h.Limiter.WriteGate()
tracing.DoInSpan(r.Context(), "receive_write_gate_ismyturn", func(ctx context.Context) {
err = writeGate.Start(r.Context())
})
defer writeGate.Done()
if err != nil {
level.Error(tLogger).Log("err", err, "msg", "internal server error")
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
under, err := h.Limiter.HeadSeriesLimiter().isUnderLimit(tenantHTTP)
if err != nil {
level.Error(tLogger).Log("msg", "error while limiting", "err", err.Error())
}
// Fail request fully if tenant has exceeded set limit.
if !under {
http.Error(w, "tenant is above active series limit", http.StatusTooManyRequests)
return
}
requestLimiter := h.Limiter.RequestLimiter()
// io.ReadAll dynamically adjust the byte slice for read data, starting from 512B.
// Since this is receive hot path, grow upfront saving allocations and CPU time.
compressed := bytes.Buffer{}
if r.ContentLength >= 0 {
if !requestLimiter.AllowSizeBytes(tenantHTTP, r.ContentLength) {
http.Error(w, "write request too large", http.StatusRequestEntityTooLarge)
return
}
compressed.Grow(int(r.ContentLength))
} else {
compressed.Grow(512)
}
_, err = io.Copy(&compressed, r.Body)
if err != nil {
http.Error(w, errors.Wrap(err, "read compressed request body").Error(), http.StatusInternalServerError)
return
}
reqBuf, err := s2.Decode(nil, compressed.Bytes())
if err != nil {
level.Error(tLogger).Log("msg", "snappy decode error", "err", err)
http.Error(w, errors.Wrap(err, "snappy decode error").Error(), http.StatusBadRequest)
return
}
if !requestLimiter.AllowSizeBytes(tenantHTTP, int64(len(reqBuf))) {
http.Error(w, "write request too large", http.StatusRequestEntityTooLarge)
return
}
// NOTE: Due to zero copy ZLabels, Labels used from WriteRequests keeps memory
// from the whole request. Ensure that we always copy those when we want to
// store them for longer time.
var wreq prompb.WriteRequest
if err := proto.Unmarshal(reqBuf, &wreq); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
rep := uint64(0)
// If the header is empty, we assume the request is not yet replicated.
if replicaRaw := r.Header.Get(h.options.ReplicaHeader); replicaRaw != "" {
if rep, err = strconv.ParseUint(replicaRaw, 10, 64); err != nil {
http.Error(w, "could not parse replica header", http.StatusBadRequest)
return
}
}
// Exit early if the request contained no data. We don't support metadata yet. We also cannot fail here, because
// this would mean lack of forward compatibility for remote write proto.
if len(wreq.Timeseries) == 0 {
// TODO(yeya24): Handle remote write metadata.
if len(wreq.Metadata) > 0 {
// TODO(bwplotka): Do we need this error message?
level.Debug(tLogger).Log("msg", "only metadata from client; metadata ingestion not supported; skipping")
return
}
level.Debug(tLogger).Log("msg", "empty remote write request; client bug or newer remote write protocol used?; skipping")
return
}
if !requestLimiter.AllowSeries(tenantHTTP, int64(len(wreq.Timeseries))) {
http.Error(w, "too many timeseries", http.StatusRequestEntityTooLarge)
return
}
totalSamples := 0
for _, timeseries := range wreq.Timeseries {
totalSamples += len(timeseries.Samples)
}
if !requestLimiter.AllowSamples(tenantHTTP, int64(totalSamples)) {
http.Error(w, "too many samples", http.StatusRequestEntityTooLarge)
return
}
// Apply relabeling configs.
h.relabel(&wreq)
if len(wreq.Timeseries) == 0 {
level.Debug(tLogger).Log("msg", "remote write request dropped due to relabeling.")
return
}
responseStatusCode := http.StatusOK
tenantStats, err := h.handleRequest(ctx, rep, tenantHTTP, &wreq)
if err != nil {
level.Debug(tLogger).Log("msg", "failed to handle request", "err", err.Error())
switch errors.Cause(err) {
case errNotReady:
responseStatusCode = http.StatusServiceUnavailable
case errUnavailable:
responseStatusCode = http.StatusServiceUnavailable
case errConflict:
responseStatusCode = http.StatusConflict
case errBadReplica:
responseStatusCode = http.StatusBadRequest
default:
level.Error(tLogger).Log("err", err, "msg", "internal server error")
responseStatusCode = http.StatusInternalServerError
}
http.Error(w, err.Error(), responseStatusCode)
}
for tenant, stats := range tenantStats {
h.writeTimeseriesTotal.WithLabelValues(strconv.Itoa(responseStatusCode), tenant).Observe(float64(stats.timeseries))
h.writeSamplesTotal.WithLabelValues(strconv.Itoa(responseStatusCode), tenant).Observe(float64(stats.totalSamples))
}
}
type requestStats struct {
timeseries int
totalSamples int
}
type tenantRequestStats map[string]requestStats
func (h *Handler) handleRequest(ctx context.Context, rep uint64, tenantHTTP string, wreq *prompb.WriteRequest) (tenantRequestStats, error) {
tLogger := log.With(h.logger, "tenantHTTP", tenantHTTP)
// This replica value is used to detect cycles in cyclic topologies.
// A non-zero value indicates that the request has already been replicated by a previous receive instance.
// For almost all users, this is only used in fully connected topologies of IngestorRouter instances.
// For acyclic topologies that use RouterOnly and IngestorOnly instances, this causes issues when replicating data.
// See discussion in: https://github.com/thanos-io/thanos/issues/4359.
if h.receiverMode == RouterOnly || h.receiverMode == IngestorOnly {
rep = 0
}
// The replica value in the header is one-indexed, thus we need >.
if rep > h.options.ReplicationFactor {
level.Error(tLogger).Log("err", errBadReplica, "msg", "write request rejected",
"request_replica", rep, "replication_factor", h.options.ReplicationFactor)
return tenantRequestStats{}, errBadReplica
}
r := replica{n: rep, replicated: rep != 0}
// On the wire, format is 1-indexed and in-code is 0-indexed, so we decrement the value if it was already replicated.
if r.replicated {
r.n--
}
// Forward any time series as necessary. All time series
// destined for the local node will be written to the receiver.
// Time series will be replicated as necessary.
return h.forward(ctx, tenantHTTP, r, wreq)
}
// forward accepts a write request, batches its time series by
// corresponding endpoint, and forwards them in parallel to the
// correct endpoint. Requests destined for the local node are written
// the local receiver. For a given write request, at most one outgoing
// write request will be made to every other node in the hashring,
// unless the request needs to be replicated.
// The function only returns when all requests have finished
// or the context is canceled.
func (h *Handler) forward(ctx context.Context, tenantHTTP string, r replica, wreq *prompb.WriteRequest) (tenantRequestStats, error) {
span, ctx := tracing.StartSpan(ctx, "receive_fanout_forward")
defer span.Finish()
var replicas []uint64
if r.replicated {
replicas = []uint64{r.n}
} else {
for rn := uint64(0); rn < h.options.ReplicationFactor; rn++ {
replicas = append(replicas, rn)
}
}
params := remoteWriteParams{
tenant: tenantHTTP,
writeRequest: wreq,
replicas: replicas,
alreadyReplicated: r.replicated,
}
return h.fanoutForward(ctx, params)
}
type remoteWriteParams struct {
tenant string
writeRequest *prompb.WriteRequest
replicas []uint64
alreadyReplicated bool
}
func (h *Handler) gatherWriteStats(rf int, writes ...map[endpointReplica]map[string]trackedSeries) tenantRequestStats {
var stats tenantRequestStats = make(tenantRequestStats)
for _, write := range writes {
for er := range write {
for tenant, series := range write[er] {
samples := 0
for _, ts := range series.timeSeries {
samples += len(ts.Samples)
}
if st, ok := stats[tenant]; ok {
st.timeseries += len(series.timeSeries)
st.totalSamples += samples
stats[tenant] = st
} else {
stats[tenant] = requestStats{
timeseries: len(series.timeSeries),
totalSamples: samples,
}
}
}
}
}
// adjust counters by the replication factor
for tenant, st := range stats {
st.timeseries /= rf
st.totalSamples /= rf
stats[tenant] = st
}
return stats
}
func (h *Handler) fanoutForward(ctx context.Context, params remoteWriteParams) (tenantRequestStats, error) {
ctx, cancel := context.WithTimeout(tracing.CopyTraceContext(context.Background(), ctx), h.options.ForwardTimeout)
var writeErrors writeErrors
var stats tenantRequestStats = make(tenantRequestStats)
defer func() {
if writeErrors.ErrOrNil() != nil {
// NOTICE: The cancel function is not used on all paths intentionally,
// if there is no error when quorum is reached,
// let forward requests to optimistically run until timeout.
cancel()
}
}()
logTags := []interface{}{"tenant", params.tenant}
if id, ok := middleware.RequestIDFromContext(ctx); ok {
logTags = append(logTags, "request-id", id)
}
requestLogger := log.With(h.logger, logTags...)
localWrites, remoteWrites, err := h.distributeTimeseriesToReplicas(params.tenant, params.replicas, params.writeRequest.Timeseries)
if err != nil {
level.Error(requestLogger).Log("msg", "failed to distribute timeseries to replicas", "err", err)
return stats, err
}
stats = h.gatherWriteStats(len(params.replicas), localWrites, remoteWrites)
// Prepare a buffered channel to receive the responses from the local and remote writes. Remote writes will all go
// asynchronously and with this capacity we will never block on writing to the channel.
maxBufferedResponses := len(localWrites)
for er := range remoteWrites {
maxBufferedResponses += len(remoteWrites[er])
}
responses := make(chan writeResponse, maxBufferedResponses)
wg := sync.WaitGroup{}
h.sendWrites(ctx, &wg, params, localWrites, remoteWrites, responses)
go func() {
wg.Wait()
close(responses)
}()
// At the end, make sure to exhaust the channel, letting remaining unnecessary requests finish asynchronously.
// This is needed if context is canceled or if we reached success of fail quorum faster.
defer func() {
go func() {
for resp := range responses {
if resp.err != nil {
level.Debug(requestLogger).Log("msg", "request failed, but not needed to achieve quorum", "err", resp.err)
}
}
}()
}()
quorum := h.writeQuorum()
if params.alreadyReplicated {
quorum = 1
}
successes := make([]int, len(params.writeRequest.Timeseries))
seriesErrs := newReplicationErrors(quorum, len(params.writeRequest.Timeseries))
for {
select {
case <-ctx.Done():
return stats, ctx.Err()
case resp, hasMore := <-responses:
if !hasMore {
for _, seriesErr := range seriesErrs {
writeErrors.Add(seriesErr)
}
return stats, writeErrors.ErrOrNil()
}
if resp.err != nil {
// Track errors and successes on a per-series basis.
for _, seriesID := range resp.seriesIDs {
seriesErrs[seriesID].Add(resp.err)
}
continue
}
// At the end, aggregate all errors if there are any and return them.
for _, seriesID := range resp.seriesIDs {
successes[seriesID]++
}
if quorumReached(successes, quorum) {
return stats, nil
}
}
}
}
// distributeTimeseriesToReplicas distributes the given timeseries from the tenant to different endpoints in a manner
// that achieves the replication factor indicated by replicas.
// The first return value are the series that should be written to the local node. The second return value are the
// series that should be written to remote nodes.
func (h *Handler) distributeTimeseriesToReplicas(
tenantHTTP string,
replicas []uint64,
timeseries []prompb.TimeSeries,
) (map[endpointReplica]map[string]trackedSeries, map[endpointReplica]map[string]trackedSeries, error) {
h.mtx.RLock()
defer h.mtx.RUnlock()
remoteWrites := make(map[endpointReplica]map[string]trackedSeries)
localWrites := make(map[endpointReplica]map[string]trackedSeries)
for tsIndex, ts := range timeseries {
var tenant = tenantHTTP
if h.splitTenantLabelName != "" {
lbls := labelpb.ZLabelsToPromLabels(ts.Labels)
tenantLabel := lbls.Get(h.splitTenantLabelName)
if tenantLabel != "" {
tenant = tenantLabel
newLabels := labels.NewBuilder(lbls)
newLabels.Del(h.splitTenantLabelName)
ts.Labels = labelpb.ZLabelsFromPromLabels(
newLabels.Labels(),
)
}
}
for _, rn := range replicas {
endpoint, err := h.hashring.GetN(tenant, &ts, rn)
if err != nil {
return nil, nil, err
}
endpointReplica := endpointReplica{endpoint: endpoint, replica: rn}
var writeDestination = remoteWrites
if endpoint.HasAddress(h.options.Endpoint) {
writeDestination = localWrites
}
writeableSeries, ok := writeDestination[endpointReplica]
if !ok {
writeDestination[endpointReplica] = map[string]trackedSeries{
tenant: {
seriesIDs: make([]int, 0),
timeSeries: make([]prompb.TimeSeries, 0),
},
}
}
tenantSeries := writeableSeries[tenant]
tenantSeries.timeSeries = append(tenantSeries.timeSeries, ts)
tenantSeries.seriesIDs = append(tenantSeries.seriesIDs, tsIndex)
writeDestination[endpointReplica][tenant] = tenantSeries
}
}
return localWrites, remoteWrites, nil
}
// sendWrites sends the local and remote writes to execute concurrently, controlling them through the provided sync.WaitGroup.
// The responses from the writes are sent to the responses channel.
func (h *Handler) sendWrites(
ctx context.Context,
wg *sync.WaitGroup,
params remoteWriteParams,
localWrites map[endpointReplica]map[string]trackedSeries,
remoteWrites map[endpointReplica]map[string]trackedSeries,
responses chan writeResponse,
) {
// Do the writes to the local node first. This should be easy and fast.
for writeDestination := range localWrites {
func(writeDestination endpointReplica) {
for tenant, trackedSeries := range localWrites[writeDestination] {
h.sendLocalWrite(ctx, writeDestination, tenant, trackedSeries, responses)
}
}(writeDestination)
}
// Do the writes to remote nodes. Run them all in parallel.
for writeDestination := range remoteWrites {
for tenant, trackedSeries := range remoteWrites[writeDestination] {
wg.Add(1)
h.sendRemoteWrite(ctx, tenant, writeDestination, trackedSeries, params.alreadyReplicated, responses, wg)
}
}
}
// sendLocalWrite sends a write request to the local node.
// The responses are sent to the responses channel.
func (h *Handler) sendLocalWrite(
ctx context.Context,
writeDestination endpointReplica,
tenantHTTP string,
trackedSeries trackedSeries,
responses chan<- writeResponse,
) {
span, tracingCtx := tracing.StartSpan(ctx, "receive_local_tsdb_write")
defer span.Finish()
span.SetTag("endpoint", writeDestination.endpoint)
span.SetTag("replica", writeDestination.replica)
tenantSeriesMapping := map[string][]prompb.TimeSeries{}
for _, ts := range trackedSeries.timeSeries {
var tenant = tenantHTTP
if h.splitTenantLabelName != "" {
lbls := labelpb.ZLabelsToPromLabels(ts.Labels)
if tnt := lbls.Get(h.splitTenantLabelName); tnt != "" {
tenant = tnt
}
}
tenantSeriesMapping[tenant] = append(tenantSeriesMapping[tenant], ts)
}
for tenant, series := range tenantSeriesMapping {
err := h.writer.Write(tracingCtx, tenant, series)
if err != nil {
span.SetTag("error", true)
span.SetTag("error.msg", err.Error())
responses <- newWriteResponse(trackedSeries.seriesIDs, err, writeDestination)
return
}
}
responses <- newWriteResponse(trackedSeries.seriesIDs, nil, writeDestination)
}
// sendRemoteWrite sends a write request to the remote node. It takes care of checking whether the endpoint is up or not
// in the peerGroup, correctly marking them as up or down when appropriate.
// The responses are sent to the responses channel.
func (h *Handler) sendRemoteWrite(
ctx context.Context,
tenant string,
endpointReplica endpointReplica,
trackedSeries trackedSeries,
alreadyReplicated bool,
responses chan writeResponse,
wg *sync.WaitGroup,
) {
endpoint := endpointReplica.endpoint
cl, err := h.peers.getConnection(ctx, endpoint)
if err != nil {
if errors.Is(err, errUnavailable) {
err = errors.Wrapf(errUnavailable, "backing off forward request for endpoint %v", endpointReplica)
}
responses <- newWriteResponse(trackedSeries.seriesIDs, err, endpointReplica)
wg.Done()
return
}
// This is called "real" because it's 1-indexed.
realReplicationIndex := int64(endpointReplica.replica + 1)
// Actually make the request against the endpoint we determined should handle these time series.
cl.RemoteWriteAsync(ctx, &storepb.WriteRequest{
Timeseries: trackedSeries.timeSeries,
Tenant: tenant,
// Increment replica since on-the-wire format is 1-indexed and 0 indicates un-replicated.
Replica: realReplicationIndex,
}, endpointReplica, trackedSeries.seriesIDs, responses, func(err error) {
if err == nil {
h.forwardRequests.WithLabelValues(labelSuccess).Inc()
if !alreadyReplicated {
h.replications.WithLabelValues(labelSuccess).Inc()
}
h.peers.markPeerAvailable(endpoint)
} else {