Debian Codegraph @

exp/api/remote/remote_api.go

raw
1 // Copyright 2024 The Prometheus Authors
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 // Package remote implements bindings for Prometheus Remote APIs.
15 package remote
16
17 import (
18 "bytes"
19 "context"
20 "errors"
21 "fmt"
22 "io"
23 "log/slog"
24 "net/http"
25 "net/url"
26 "path"
27 "strconv"
28 "strings"
29 "sync"
30 "time"
31
32 "github.com/klauspost/compress/snappy"
33 "google.golang.org/protobuf/proto"
34
35 "github.com/prometheus/client_golang/exp/internal/github.com/efficientgo/core/backoff"
36 )
37
38 // API is a client for Prometheus Remote Protocols.
39 // NOTE(bwplotka): Only https://prometheus.io/docs/specs/remote_write_spec_2_0/ is currently implemented,
40 // read protocols to be implemented if there will be a demand.
41 type API struct {
42 baseURL *url.URL
43
44 opts apiOpts
45 bufPool sync.Pool
46 }
47
48 // APIOption represents a remote API option.
49 type APIOption func(o *apiOpts) error
50
51 // TODO(bwplotka): Add "too old sample" handling one day.
52 type apiOpts struct {
53 logger *slog.Logger
54 client *http.Client
55 backoff backoff.Config
56 compression Compression
57 path string
58 retryOnRateLimit bool
59 }
60
61 var defaultAPIOpts = &apiOpts{
62 backoff: backoff.Config{
63 Min: 1 * time.Second,
64 Max: 10 * time.Second,
65 MaxRetries: 10,
66 },
67 client: http.DefaultClient,
68 // Hardcoded for now.
69 retryOnRateLimit: true,
70 compression: SnappyBlockCompression,
71 path: "api/v1/write",
72 }
73
74 // WithAPILogger returns APIOption that allows providing slog logger.
75 // By default, nothing is logged.
76 func WithAPILogger(logger *slog.Logger) APIOption {
77 return func(o *apiOpts) error {
78 o.logger = logger
79 return nil
80 }
81 }
82
83 // WithAPIHTTPClient returns APIOption that allows providing http client.
84 func WithAPIHTTPClient(client *http.Client) APIOption {
85 return func(o *apiOpts) error {
86 o.client = client
87 return nil
88 }
89 }
90
91 // WithAPIPath returns APIOption that allows providing path to send remote write requests to.
92 func WithAPIPath(path string) APIOption {
93 return func(o *apiOpts) error {
94 o.path = path
95 return nil
96 }
97 }
98
99 // WithAPIRetryOnRateLimit returns APIOption that disables retrying on rate limit status code.
100 func WithAPINoRetryOnRateLimit() APIOption {
101 return func(o *apiOpts) error {
102 o.retryOnRateLimit = false
103 return nil
104 }
105 }
106
107 // WithAPIBackoff returns APIOption that allows overriding backoff configuration.
108 func WithAPIBackoff(backoff backoff.Config) APIOption {
109 return func(o *apiOpts) error {
110 o.backoff = backoff
111 return nil
112 }
113 }
114
115 type nopSlogHandler struct{}
116
117 func (n nopSlogHandler) Enabled(context.Context, slog.Level) bool { return false }
118 func (n nopSlogHandler) Handle(context.Context, slog.Record) error { return nil }
119 func (n nopSlogHandler) WithAttrs([]slog.Attr) slog.Handler { return n }
120 func (n nopSlogHandler) WithGroup(string) slog.Handler { return n }
121
122 // NewAPI returns a new API for the clients of Remote Write Protocol.
123 func NewAPI(baseURL string, opts ...APIOption) (*API, error) {
124 parsedURL, err := url.Parse(baseURL)
125 if err != nil {
126 return nil, fmt.Errorf("invalid base URL: %w", err)
127 }
128
129 o := *defaultAPIOpts
130 for _, opt := range opts {
131 if err := opt(&o); err != nil {
132 return nil, err
133 }
134 }
135
136 if o.logger == nil {
137 o.logger = slog.New(nopSlogHandler{})
138 }
139
140 parsedURL.Path = path.Join(parsedURL.Path, o.path)
141
142 api := &API{
143 opts: o,
144 baseURL: parsedURL,
145 bufPool: sync.Pool{
146 New: func() any {
147 b := make([]byte, 0, 1024*16) // Initial capacity of 16KB.
148 return &b
149 },
150 },
151 }
152 return api, nil
153 }
154
155 type retryableError struct {
156 error
157 retryAfter time.Duration
158 }
159
160 func (r retryableError) RetryAfter() time.Duration {
161 return r.retryAfter
162 }
163
164 type vtProtoEnabled interface {
165 SizeVT() int
166 MarshalToSizedBufferVT(dAtA []byte) (int, error)
167 }
168
169 type gogoProtoEnabled interface {
170 Size() (n int)
171 MarshalToSizedBuffer(dAtA []byte) (n int, err error)
172 }
173
174 // Write writes given, non-empty, protobuf message to a remote storage.
175 //
176 // Depending on serialization methods,
177 // - https://github.com/planetscale/vtprotobuf methods will be used if your msg
178 // supports those (e.g. SizeVT() and MarshalToSizedBufferVT(...)), for efficiency
179 // - Otherwise https://github.com/gogo/protobuf methods (e.g. Size() and MarshalToSizedBuffer(...))
180 // will be used
181 // - If neither is supported, it will marshaled using generic google.golang.org/protobuf methods and
182 // error out on unknown scheme.
183 func (r *API) Write(ctx context.Context, msgType WriteMessageType, msg any) (_ WriteResponseStats, err error) {
184 buf := r.bufPool.Get().(*[]byte)
185
186 if err := msgType.Validate(); err != nil {
187 return WriteResponseStats{}, err
188 }
189
190 // Encode the payload.
191 switch m := msg.(type) {
192 case vtProtoEnabled:
193 // Use optimized vtprotobuf if supported.
194 size := m.SizeVT()
195 if cap(*buf) < size {
196 *buf = make([]byte, size)
197 } else {
198 *buf = (*buf)[:size]
199 }
200
201 if _, err := m.MarshalToSizedBufferVT(*buf); err != nil {
202 return WriteResponseStats{}, fmt.Errorf("encoding request %w", err)
203 }
204 case gogoProtoEnabled:
205 // Gogo proto if supported.
206 size := m.Size()
207 if cap(*buf) < size {
208 *buf = make([]byte, size)
209 } else {
210 *buf = (*buf)[:size]
211 }
212
213 if _, err := m.MarshalToSizedBuffer(*buf); err != nil {
214 return WriteResponseStats{}, fmt.Errorf("encoding request %w", err)
215 }
216 case proto.Message:
217 // Generic proto.
218 *buf, err = (proto.MarshalOptions{}).MarshalAppend(*buf, m)
219 if err != nil {
220 return WriteResponseStats{}, fmt.Errorf("encoding request %w", err)
221 }
222 default:
223 return WriteResponseStats{}, fmt.Errorf("unknown message type %T", m)
224 }
225
226 comprBuf := r.bufPool.Get().(*[]byte)
227 payload, err := compressPayload(comprBuf, r.opts.compression, *buf)
228 if err != nil {
229 return WriteResponseStats{}, fmt.Errorf("compressing %w", err)
230 }
231 r.bufPool.Put(buf)
232 r.bufPool.Put(comprBuf)
233
234 // Since we retry writes we need to track the total amount of accepted data
235 // across the various attempts.
236 accumulatedStats := WriteResponseStats{}
237
238 b := backoff.New(ctx, r.opts.backoff)
239 for {
240 rs, err := r.attemptWrite(ctx, r.opts.compression, msgType, payload, b.NumRetries())
241 accumulatedStats.Add(rs)
242 if err == nil {
243 // Check the case mentioned in PRW 2.0.
244 // https://prometheus.io/docs/specs/remote_write_spec_2_0/#required-written-response-headers.
245 if msgType == WriteV2MessageType && !accumulatedStats.confirmed && accumulatedStats.NoDataWritten() {
246 // TODO(bwplotka): Allow users to disable this check or provide their stats for us to know if it's empty.
247 return accumulatedStats, fmt.Errorf("sent v2 request; "+
248 "got 2xx, but PRW 2.0 response header statistics indicate %v samples, %v histograms "+
249 "and %v exemplars were accepted; assumining failure e.g. the target only supports "+
250 "PRW 1.0 prometheus.WriteRequest, but does not check the Content-Type header correctly",
251 accumulatedStats.Samples, accumulatedStats.Histograms, accumulatedStats.Exemplars,
252 )
253 }
254 // Success!
255 // TODO(bwplotka): Debug log with retry summary?
256 return accumulatedStats, nil
257 }
258
259 var retryableErr retryableError
260 if !errors.As(err, &retryableErr) {
261 // TODO(bwplotka): More context in the error e.g. about retries.
262 return accumulatedStats, err
263 }
264
265 if !b.Ongoing() {
266 // TODO(bwplotka): More context in the error e.g. about retries.
267 return accumulatedStats, err
268 }
269
270 backoffDelay := b.NextDelay() + retryableErr.RetryAfter()
271 r.opts.logger.Error("failed to send remote write request; retrying after backoff", "err", err, "backoff", backoffDelay)
272 select {
273 case <-ctx.Done():
274 // TODO(bwplotka): More context in the error e.g. about retries.
275 return WriteResponseStats{}, ctx.Err()
276 case <-time.After(backoffDelay):
277 // Retry.
278 }
279 }
280 }
281
282 func compressPayload(tmpbuf *[]byte, enc Compression, inp []byte) (compressed []byte, _ error) {
283 switch enc {
284 case SnappyBlockCompression:
285 if cap(*tmpbuf) < snappy.MaxEncodedLen(len(inp)) {
286 *tmpbuf = make([]byte, snappy.MaxEncodedLen(len(inp)))
287 } else {
288 *tmpbuf = (*tmpbuf)[:snappy.MaxEncodedLen(len(inp))]
289 }
290
291 compressed = snappy.Encode(*tmpbuf, inp)
292 return compressed, nil
293 default:
294 return compressed, fmt.Errorf("unknown compression scheme [%v]", enc)
295 }
296 }
297
298 func (r *API) attemptWrite(ctx context.Context, compr Compression, msgType WriteMessageType, payload []byte, attempt int) (WriteResponseStats, error) {
299 req, err := http.NewRequest(http.MethodPost, r.baseURL.String(), bytes.NewReader(payload))
300 if err != nil {
301 // Errors from NewRequest are from unparsable URLs, so are not
302 // recoverable.
303 return WriteResponseStats{}, err
304 }
305
306 req.Header.Add("Content-Encoding", string(compr))
307 req.Header.Set("Content-Type", contentTypeHeader(msgType))
308 if msgType == WriteV1MessageType {
309 // Compatibility mode for 1.0.
310 req.Header.Set(versionHeader, version1HeaderValue)
311 } else {
312 req.Header.Set(versionHeader, version20HeaderValue)
313 }
314
315 if attempt > 0 {
316 req.Header.Set("Retry-Attempt", strconv.Itoa(attempt))
317 }
318
319 resp, err := r.opts.client.Do(req.WithContext(ctx))
320 if err != nil {
321 // Errors from Client.Do are likely network errors, so recoverable.
322 return WriteResponseStats{}, retryableError{err, 0}
323 }
324 defer resp.Body.Close()
325
326 body, err := io.ReadAll(resp.Body)
327 if err != nil {
328 return WriteResponseStats{}, fmt.Errorf("reading response body: %w", err)
329 }
330
331 rs := WriteResponseStats{}
332 if msgType == WriteV2MessageType {
333 rs, err = parseWriteResponseStats(resp)
334 if err != nil {
335 r.opts.logger.Warn("parsing rw write statistics failed; partial or no stats", "err", err)
336 }
337 }
338
339 if resp.StatusCode/100 == 2 {
340 return rs, nil
341 }
342
343 err = fmt.Errorf("server returned HTTP status %s: %s", resp.Status, body)
344 if resp.StatusCode/100 == 5 ||
345 (r.opts.retryOnRateLimit && resp.StatusCode == http.StatusTooManyRequests) {
346 return rs, retryableError{err, retryAfterDuration(resp.Header.Get("Retry-After"))}
347 }
348 return rs, err
349 }
350
351 // retryAfterDuration returns the duration for the Retry-After header. In case of any errors, it
352 // returns 0 as if the header was never supplied.
353 func retryAfterDuration(t string) time.Duration {
354 parsedDuration, err := time.Parse(http.TimeFormat, t)
355 if err == nil {
356 return time.Until(parsedDuration)
357 }
358 // The duration can be in seconds.
359 d, err := strconv.Atoi(t)
360 if err != nil {
361 return 0
362 }
363 return time.Duration(d) * time.Second
364 }
365
366 // writeStorage represents the storage for RemoteWriteHandler.
367 // This interface is intentionally private due its experimental state.
368 type writeStorage interface {
369 // Store stores remote write metrics encoded in the given WriteContentType.
370 // Provided http.Request contains the encoded bytes in the req.Body with all the HTTP information,
371 // except "Content-Type" header which is provided in a separate, validated ctype.
372 //
373 // Other headers might be trimmed, depending on the configured middlewares
374 // e.g. a default SnappyMiddleware trims "Content-Encoding" and ensures that
375 // encoded body bytes are already decompressed.
376 Store(ctx context.Context, msgType WriteMessageType, req *http.Request) (_ *WriteResponse, _ error)
377 }
378
379 type handler struct {
380 store writeStorage
381 acceptedMessageTypes MessageTypes
382 opts handlerOpts
383 }
384
385 type handlerOpts struct {
386 logger *slog.Logger
387 middlewares []func(http.Handler) http.Handler
388 }
389
390 // HandlerOption represents an option for the handler.
391 type HandlerOption func(o *handlerOpts)
392
393 // WithHandlerLogger returns HandlerOption that allows providing slog logger.
394 // By default, nothing is logged.
395 func WithHandlerLogger(logger *slog.Logger) HandlerOption {
396 return func(o *handlerOpts) {
397 o.logger = logger
398 }
399 }
400
401 // WithHandlerMiddleware returns HandlerOption that allows providing middlewares.
402 // Multiple middlewares can be provided and will be applied in the order they are passed.
403 // When using this option, SnappyDecompressorMiddleware is not applied by default so
404 // it (or any other decompression middleware) needs to be added explicitly.
405 func WithHandlerMiddlewares(middlewares ...func(http.Handler) http.Handler) HandlerOption {
406 return func(o *handlerOpts) {
407 o.middlewares = middlewares
408 }
409 }
410
411 // SnappyDecompressorMiddleware returns a middleware that checks if the request body is snappy-encoded and decompresses it.
412 // If the request body is not snappy-encoded, it returns an error.
413 // Used by default in NewRemoteWriteHandler.
414 func SnappyDecompressorMiddleware(logger *slog.Logger) func(http.Handler) http.Handler {
415 bufPool := sync.Pool{
416 New: func() any {
417 return bytes.NewBuffer(nil)
418 },
419 }
420
421 return func(next http.Handler) http.Handler {
422 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
423 enc := r.Header.Get("Content-Encoding")
424 if enc != "" && enc != string(SnappyBlockCompression) {
425 err := fmt.Errorf("%v encoding (compression) is not accepted by this server; only %v is acceptable", enc, SnappyBlockCompression)
426 logger.Error("Error decoding remote write request", "err", err)
427 http.Error(w, err.Error(), http.StatusUnsupportedMediaType)
428 return
429 }
430
431 buf := bufPool.Get().(*bytes.Buffer)
432 buf.Reset()
433 defer bufPool.Put(buf)
434
435 bodyBytes, err := io.ReadAll(io.TeeReader(r.Body, buf))
436 if err != nil {
437 logger.Error("Error reading request body", "err", err)
438 http.Error(w, err.Error(), http.StatusBadRequest)
439 return
440 }
441
442 decompressed, err := snappy.Decode(nil, bodyBytes)
443 if err != nil {
444 // TODO(bwplotka): Add more context to responded error?
445 logger.Error("Error snappy decoding remote write request", "err", err)
446 http.Error(w, err.Error(), http.StatusBadRequest)
447 return
448 }
449
450 // Replace the body with decompressed data and remove Content-Encoding header.
451 r.Body = io.NopCloser(bytes.NewReader(decompressed))
452 r.Header.Del("Content-Encoding")
453 next.ServeHTTP(w, r)
454 })
455 }
456 }
457
458 // NewHandler returns HTTP handler that receives Remote Write 2.0
459 // protocol https://prometheus.io/docs/specs/remote_write_spec_2_0/.
460 func NewHandler(store writeStorage, acceptedMessageTypes MessageTypes, opts ...HandlerOption) http.Handler {
461 o := handlerOpts{
462 logger: slog.New(nopSlogHandler{}),
463 middlewares: []func(http.Handler) http.Handler{SnappyDecompressorMiddleware(slog.New(nopSlogHandler{}))},
464 }
465 for _, opt := range opts {
466 opt(&o)
467 }
468
469 h := &handler{
470 opts: o,
471 store: store,
472 acceptedMessageTypes: acceptedMessageTypes,
473 }
474
475 // Apply all middlewares in order
476 var handler http.Handler = h
477 for i := len(o.middlewares) - 1; i >= 0; i-- {
478 handler = o.middlewares[i](handler)
479 }
480 return handler
481 }
482
483 // ParseProtoMsg parses the content-type header and returns the proto message type.
484 //
485 // The expected content-type will be of the form,
486 // - `application/x-protobuf;proto=io.prometheus.write.v2.Request` which will be treated as RW2.0 request,
487 // - `application/x-protobuf;proto=prometheus.WriteRequest` which will be treated as RW1.0 request,
488 // - `application/x-protobuf` which will be treated as RW1.0 request.
489 //
490 // If the content-type is not of the above forms, it will return an error.
491 func ParseProtoMsg(contentType string) (WriteMessageType, error) {
492 contentType = strings.TrimSpace(contentType)
493
494 parts := strings.Split(contentType, ";")
495 if parts[0] != appProtoContentType {
496 return "", fmt.Errorf("expected %v as the first (media) part, got %v content-type", appProtoContentType, contentType)
497 }
498 // Parse potential https://www.rfc-editor.org/rfc/rfc9110#parameter
499 for _, p := range parts[1:] {
500 pair := strings.Split(p, "=")
501 if len(pair) != 2 {
502 return "", fmt.Errorf("as per https://www.rfc-editor.org/rfc/rfc9110#parameter expected parameters to be key-values, got %v in %v content-type", p, contentType)
503 }
504 if pair[0] == "proto" {
505 ret := WriteMessageType(pair[1])
506 if err := ret.Validate(); err != nil {
507 return "", fmt.Errorf("got %v content type; %w", contentType, err)
508 }
509 return ret, nil
510 }
511 }
512 // No "proto=" parameter, assuming v1.
513 return WriteV1MessageType, nil
514 }
515
516 func (h *handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
517 if r.Method != http.MethodPost {
518 http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
519 return
520 }
521
522 contentType := r.Header.Get("Content-Type")
523 if contentType == "" {
524 contentType = appProtoContentType
525 }
526
527 msgType, err := ParseProtoMsg(contentType)
528 if err != nil {
529 h.opts.logger.Error("Error decoding remote write request", "err", err)
530 http.Error(w, err.Error(), http.StatusUnsupportedMediaType)
531 return
532 }
533
534 if !h.acceptedMessageTypes.Contains(msgType) {
535 err := fmt.Errorf("%v protobuf message is not accepted by this server; only accepts %v", msgType, h.acceptedMessageTypes.String())
536 h.opts.logger.Error("Unaccepted message type", "msgType", msgType, "err", err)
537 http.Error(w, err.Error(), http.StatusUnsupportedMediaType)
538 return
539 }
540
541 writeResponse, storeErr := h.store.Store(r.Context(), msgType, r)
542
543 // Set required X-Prometheus-Remote-Write-Written-* response headers, in all cases, alongwith any user-defined headers.
544 writeResponse.SetHeaders(w)
545
546 if storeErr != nil {
547 if writeResponse.StatusCode() == 0 {
548 writeResponse.SetStatusCode(http.StatusInternalServerError)
549 }
550 if writeResponse.StatusCode()/100 == 5 { // 5xx
551 h.opts.logger.Error("Error while storing the remote write request", "err", storeErr.Error())
552 }
553 http.Error(w, storeErr.Error(), writeResponse.StatusCode())
554 return
555 }
556 w.WriteHeader(writeResponse.StatusCode())
557 }