-
Notifications
You must be signed in to change notification settings - Fork 1.2k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Move remote write API to client_golang/exp #1711
base: prwclient-em
Are you sure you want to change the base?
Changes from all commits
d32e301
9392687
3858538
a7eceb3
e7dbd12
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -22,23 +22,26 @@ import ( | |
"io" | ||
"log/slog" | ||
"net/http" | ||
"net/url" | ||
"path" | ||
"strconv" | ||
"strings" | ||
"time" | ||
|
||
"github.com/klauspost/compress/snappy" | ||
"google.golang.org/protobuf/proto" | ||
|
||
"github.com/prometheus/client_golang/api" | ||
"github.com/prometheus/client_golang/internal/github.com/efficientgo/core/backoff" | ||
"github.com/prometheus/client_golang/exp/internal/github.com/efficientgo/core/backoff" | ||
) | ||
|
||
// API is a client for Prometheus Remote Protocols. | ||
// NOTE(bwplotka): Only https://prometheus.io/docs/specs/remote_write_spec_2_0/ is currently implemented, | ||
// read protocols to be implemented if there will be a demand. | ||
type API struct { | ||
client api.Client | ||
opts apiOpts | ||
baseURL *url.URL | ||
client *http.Client | ||
|
||
opts apiOpts | ||
|
||
reqBuf, comprBuf []byte | ||
} | ||
|
@@ -103,7 +106,12 @@ func (n nopSlogHandler) WithGroup(string) slog.Handler { return n } | |
// | ||
// It is not safe to use the returned API from multiple goroutines, create a | ||
// separate *API for each goroutine. | ||
func NewAPI(c api.Client, opts ...APIOption) (*API, error) { | ||
func NewAPI(client *http.Client, baseURL string, opts ...APIOption) (*API, error) { | ||
parsedURL, err := url.Parse(baseURL) | ||
if err != nil { | ||
return nil, fmt.Errorf("invalid base URL: %w", err) | ||
} | ||
|
||
o := *defaultAPIOpts | ||
for _, opt := range opts { | ||
if err := opt(&o); err != nil { | ||
|
@@ -115,9 +123,16 @@ func NewAPI(c api.Client, opts ...APIOption) (*API, error) { | |
o.logger = slog.New(nopSlogHandler{}) | ||
} | ||
|
||
if client == nil { | ||
client = http.DefaultClient | ||
} | ||
|
||
parsedURL.Path = path.Join(parsedURL.Path, o.path) | ||
|
||
return &API{ | ||
client: c, | ||
opts: o, | ||
opts: o, | ||
client: client, | ||
baseURL: parsedURL, | ||
}, nil | ||
} | ||
|
||
|
@@ -157,6 +172,9 @@ type v2Request interface { | |
// - If neither is supported, it will marshaled using generic google.golang.org/protobuf methods and | ||
// error out on unknown scheme. | ||
func (r *API) Write(ctx context.Context, msg any) (_ WriteResponseStats, err error) { | ||
// Reset the buffer. | ||
r.reqBuf = r.reqBuf[:0] | ||
|
||
// Detect content-type. | ||
cType := WriteProtoFullNameV1 | ||
if _, ok := msg.(v2Request); ok { | ||
|
@@ -189,7 +207,6 @@ func (r *API) Write(ctx context.Context, msg any) (_ WriteResponseStats, err err | |
} | ||
case proto.Message: | ||
// Generic proto. | ||
r.reqBuf = r.reqBuf[:0] | ||
r.reqBuf, err = (proto.MarshalOptions{}).MarshalAppend(r.reqBuf, m) | ||
if err != nil { | ||
return WriteResponseStats{}, fmt.Errorf("encoding request %w", err) | ||
|
@@ -266,8 +283,7 @@ func compressPayload(tmpbuf *[]byte, enc Compression, inp []byte) (compressed [] | |
} | ||
|
||
func (r *API) attemptWrite(ctx context.Context, compr Compression, proto WriteProtoFullName, payload []byte, attempt int) (WriteResponseStats, error) { | ||
u := r.client.URL(r.opts.path, nil) | ||
req, err := http.NewRequest(http.MethodPost, u.String(), bytes.NewReader(payload)) | ||
req, err := http.NewRequest(http.MethodPost, r.baseURL.String(), bytes.NewReader(payload)) | ||
if err != nil { | ||
// Errors from NewRequest are from unparsable URLs, so are not | ||
// recoverable. | ||
|
@@ -287,11 +303,17 @@ func (r *API) attemptWrite(ctx context.Context, compr Compression, proto WritePr | |
req.Header.Set("Retry-Attempt", strconv.Itoa(attempt)) | ||
} | ||
|
||
resp, body, err := r.client.Do(ctx, req) | ||
resp, err := r.client.Do(req.WithContext(ctx)) | ||
if err != nil { | ||
// Errors from Client.Do are likely network errors, so recoverable. | ||
return WriteResponseStats{}, retryableError{err, 0} | ||
} | ||
defer resp.Body.Close() | ||
|
||
body, err := io.ReadAll(resp.Body) | ||
if err != nil { | ||
return WriteResponseStats{}, fmt.Errorf("reading response body: %w", err) | ||
} | ||
|
||
rs := WriteResponseStats{} | ||
if proto == WriteProtoFullNameV2 { | ||
|
@@ -334,19 +356,14 @@ type writeStorage interface { | |
Store(ctx context.Context, proto WriteProtoFullName, serializedRequest []byte) (_ WriteResponseStats, code int, _ error) | ||
} | ||
|
||
// remoteWriteDecompressor is an interface that allows decompressing the body of the request. | ||
type remoteWriteDecompressor interface { | ||
Decompress(ctx context.Context, body io.ReadCloser) (decompressed []byte, _ error) | ||
} | ||
|
||
type handler struct { | ||
store writeStorage | ||
opts handlerOpts | ||
} | ||
|
||
type handlerOpts struct { | ||
logger *slog.Logger | ||
decompressor remoteWriteDecompressor | ||
logger *slog.Logger | ||
middlewares []func(http.Handler) http.Handler | ||
} | ||
|
||
// HandlerOption represents an option for the handler. | ||
|
@@ -360,22 +377,71 @@ func WithHandlerLogger(logger *slog.Logger) HandlerOption { | |
} | ||
} | ||
|
||
// WithHandlerDecompressor returns HandlerOption that allows providing remoteWriteDecompressor. | ||
// By default, SimpleSnappyDecompressor is used. | ||
func WithHandlerDecompressor(decompressor remoteWriteDecompressor) HandlerOption { | ||
// WithHandlerMiddleware returns HandlerOption that allows providing middlewares. | ||
// Multiple middlewares can be provided and will be applied in the order they are passed. | ||
// When using this option, SnappyDecompressorMiddleware is not applied by default so | ||
// it (or any other decompression middleware) needs to be added explicitly. | ||
func WithHandlerMiddlewares(middlewares ...func(http.Handler) http.Handler) HandlerOption { | ||
return func(o *handlerOpts) { | ||
o.decompressor = decompressor | ||
o.middlewares = middlewares | ||
} | ||
} | ||
|
||
// SnappyDecompressorMiddleware returns a middleware that checks if the request body is snappy-encoded and decompresses it. | ||
// If the request body is not snappy-encoded, it returns an error. | ||
// Used by default in NewRemoteWriteHandler. | ||
func SnappyDecompressorMiddleware(logger *slog.Logger) func(http.Handler) http.Handler { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Tried to convert this into a middleware with the ability for downstream users to override and add their own middlewares if needed. Let me know what you think, or if this is too much |
||
return func(next http.Handler) http.Handler { | ||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
enc := r.Header.Get("Content-Encoding") | ||
if enc != "" && enc != string(SnappyBlockCompression) { | ||
err := fmt.Errorf("%v encoding (compression) is not accepted by this server; only %v is acceptable", enc, SnappyBlockCompression) | ||
logger.Error("Error decoding remote write request", "err", err) | ||
http.Error(w, err.Error(), http.StatusUnsupportedMediaType) | ||
return | ||
} | ||
|
||
// Read the request body. | ||
bodyBytes, err := io.ReadAll(r.Body) | ||
if err != nil { | ||
logger.Error("Error reading request body", "err", err) | ||
http.Error(w, err.Error(), http.StatusBadRequest) | ||
return | ||
} | ||
|
||
decompressed, err := snappy.Decode(nil, bodyBytes) | ||
if err != nil { | ||
// TODO(bwplotka): Add more context to responded error? | ||
logger.Error("Error snappy decoding remote write request", "err", err) | ||
http.Error(w, err.Error(), http.StatusBadRequest) | ||
return | ||
} | ||
|
||
// Replace the body with decompressed data | ||
r.Body = io.NopCloser(bytes.NewReader(decompressed)) | ||
next.ServeHTTP(w, r) | ||
}) | ||
} | ||
} | ||
|
||
// NewRemoteWriteHandler returns HTTP handler that receives Remote Write 2.0 | ||
// protocol https://prometheus.io/docs/specs/remote_write_spec_2_0/. | ||
func NewRemoteWriteHandler(store writeStorage, opts ...HandlerOption) http.Handler { | ||
o := handlerOpts{logger: slog.New(nopSlogHandler{}), decompressor: &SimpleSnappyDecompressor{}} | ||
o := handlerOpts{ | ||
logger: slog.New(nopSlogHandler{}), | ||
middlewares: []func(http.Handler) http.Handler{SnappyDecompressorMiddleware(slog.New(nopSlogHandler{}))}, | ||
} | ||
for _, opt := range opts { | ||
opt(&o) | ||
} | ||
return &handler{opts: o, store: store} | ||
h := &handler{opts: o, store: store} | ||
|
||
// Apply all middlewares in order | ||
var handler http.Handler = h | ||
for i := len(o.middlewares) - 1; i >= 0; i-- { | ||
handler = o.middlewares[i](handler) | ||
} | ||
return handler | ||
} | ||
|
||
// ParseProtoMsg parses the content-type header and returns the proto message type. | ||
|
@@ -414,8 +480,6 @@ func ParseProtoMsg(contentType string) (WriteProtoFullName, error) { | |
func (h *handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { | ||
contentType := r.Header.Get("Content-Type") | ||
if contentType == "" { | ||
// Don't break yolo 1.0 clients if not needed. | ||
// We could give http.StatusUnsupportedMediaType, but let's assume 1.0 message by default. | ||
contentType = appProtoContentType | ||
} | ||
|
||
|
@@ -426,26 +490,15 @@ func (h *handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { | |
return | ||
} | ||
|
||
enc := r.Header.Get("Content-Encoding") | ||
if enc == "" { | ||
// Don't break yolo 1.0 clients if not needed. This is similar to what we did | ||
// before 2.0: https://github.com/prometheus/prometheus/blob/d78253319daa62c8f28ed47e40bafcad2dd8b586/storage/remote/write_handler.go#L62 | ||
// We could give http.StatusUnsupportedMediaType, but let's assume snappy by default. | ||
} else if enc != string(SnappyBlockCompression) { | ||
err := fmt.Errorf("%v encoding (compression) is not accepted by this server; only %v is acceptable", enc, SnappyBlockCompression) | ||
h.opts.logger.Error("Error decoding remote write request", "err", err) | ||
http.Error(w, err.Error(), http.StatusUnsupportedMediaType) | ||
} | ||
|
||
// Decompress the request body. | ||
decompressed, err := h.opts.decompressor.Decompress(r.Context(), r.Body) | ||
// Read the already decompressed body | ||
body, err := io.ReadAll(r.Body) | ||
if err != nil { | ||
h.opts.logger.Error("Error decompressing remote write request", "err", err.Error()) | ||
h.opts.logger.Error("Error reading request body", "err", err.Error()) | ||
http.Error(w, err.Error(), http.StatusBadRequest) | ||
return | ||
} | ||
|
||
stats, code, storeErr := h.store.Store(r.Context(), msgType, decompressed) | ||
stats, code, storeErr := h.store.Store(r.Context(), msgType, body) | ||
|
||
// Set required X-Prometheus-Remote-Write-Written-* response headers, in all cases. | ||
stats.SetHeaders(w) | ||
|
@@ -462,24 +515,3 @@ func (h *handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { | |
} | ||
w.WriteHeader(http.StatusNoContent) | ||
} | ||
|
||
// SimpleSnappyDecompressor is a simple implementation of the remoteWriteDecompressor interface. | ||
type SimpleSnappyDecompressor struct{} | ||
|
||
func (s *SimpleSnappyDecompressor) Decompress(ctx context.Context, body io.ReadCloser) (decompressed []byte, _ error) { | ||
// Read the request body. | ||
bodyBytes, err := io.ReadAll(body) | ||
if err != nil { | ||
return nil, fmt.Errorf("error reading request body: %w", err) | ||
} | ||
|
||
decompressed, err = snappy.Decode(nil, bodyBytes) | ||
if err != nil { | ||
// TODO(bwplotka): Add more context to responded error? | ||
return nil, fmt.Errorf("error snappy decoding request body: %w", err) | ||
} | ||
|
||
return decompressed, nil | ||
} | ||
|
||
var _ remoteWriteDecompressor = &SimpleSnappyDecompressor{} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,17 @@ | ||
// Copyright 2019 The Prometheus Authors | ||
// Licensed under the Apache License, Version 2.0 (the "License"); | ||
// you may not use this file except in compliance with the License. | ||
// You may obtain a copy of the License at | ||
// | ||
// http://www.apache.org/licenses/LICENSE-2.0 | ||
// | ||
// Unless required by applicable law or agreed to in writing, software | ||
// distributed under the License is distributed on an "AS IS" BASIS, | ||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
// See the License for the specific language governing permissions and | ||
// limitations under the License. | ||
|
||
// package exp contains experimental utilities and APIs for Prometheus. | ||
// | ||
// This package is experimental and may contain breaking changes or be removed in the future. | ||
package exp |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,12 @@ | ||
module github.com/prometheus/client_golang/exp | ||
|
||
go 1.21 | ||
|
||
require ( | ||
github.com/google/go-cmp v0.6.0 | ||
github.com/klauspost/compress v1.17.7 | ||
github.com/prometheus/common v0.48.0 | ||
google.golang.org/protobuf v1.33.0 | ||
) | ||
|
||
require github.com/prometheus/client_model v0.5.0 // indirect |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= | ||
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= | ||
github.com/klauspost/compress v1.17.7 h1:ehO88t2UGzQK66LMdE8tibEd1ErmzZjNEqWkjLAKQQg= | ||
github.com/klauspost/compress v1.17.7/go.mod h1:Di0epgTjJY877eYKx5yC51cX2A2Vl2ibi7bDH9ttBbw= | ||
github.com/prometheus/client_model v0.5.0 h1:VQw1hfvPvk3Uv6Qf29VrPF32JB6rtbgI6cYPYQjL0Qw= | ||
github.com/prometheus/client_model v0.5.0/go.mod h1:dTiFglRmd66nLR9Pv9f0mZi7B7fk5Pm3gvsjB5tr+kI= | ||
github.com/prometheus/common v0.48.0 h1:QO8U2CdOzSn1BBsmXJXduaaW+dY/5QLjfB8svtSzKKE= | ||
github.com/prometheus/common v0.48.0/go.mod h1:0/KsvlIEfPQCQ5I2iNSAWKPZziNCvRs5EC6ILDTlAPc= | ||
google.golang.org/protobuf v1.33.0 h1:uNO2rsAINq/JlFpSdYEKIZ0uKD/R9cpdv0T+yoGwGmI= | ||
google.golang.org/protobuf v1.33.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos= |
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Added a workspace file as well |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
go 1.21 | ||
|
||
use ( | ||
. | ||
./exp | ||
) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Passing http.Client directly here instead of api.Client structs. Seems like the most flexible way, without doing custom configs.