| 1 |
// Copyright The OpenTelemetry Authors |
| 2 |
// SPDX-License-Identifier: Apache-2.0 |
| 3 |
|
| 4 |
// This file contains helper functions regarding compression/decompression for confighttp. |
| 5 |
|
| 6 |
package confighttp // import "go.opentelemetry.io/collector/config/confighttp" |
| 7 |
|
| 8 |
import ( |
| 9 |
"bufio" |
| 10 |
"bytes" |
| 11 |
"compress/gzip" |
| 12 |
"compress/zlib" |
| 13 |
"errors" |
| 14 |
"fmt" |
| 15 |
"io" |
| 16 |
"maps" |
| 17 |
"net/http" |
| 18 |
"sync" |
| 19 |
|
| 20 |
"github.com/golang/snappy" |
| 21 |
"github.com/klauspost/compress/zstd" |
| 22 |
"github.com/pierrec/lz4/v4" |
| 23 |
|
| 24 |
"go.opentelemetry.io/collector/config/configcompression" |
| 25 |
"go.opentelemetry.io/collector/featuregate" |
| 26 |
) |
| 27 |
|
| 28 |
var enableFramedSnappy = featuregate.GlobalRegistry().MustRegister( |
| 29 |
"confighttp.framedSnappy", |
| 30 |
featuregate.StageBeta, |
| 31 |
featuregate.WithRegisterFromVersion("v0.125.0"), |
| 32 |
featuregate.WithRegisterDescription("Content encoding 'snappy' will compress/decompress block snappy format while 'x-snappy-framed' will compress/decompress framed snappy format."), |
| 33 |
featuregate.WithRegisterReferenceURL("https://github.com/open-telemetry/opentelemetry-collector/issues/10584"), |
| 34 |
) |
| 35 |
|
| 36 |
func defaultCompressionAlgorithms() []string { |
| 37 |
if enableFramedSnappy.IsEnabled() { |
| 38 |
return []string{"", "gzip", "zstd", "zlib", "snappy", "deflate", "lz4", "x-snappy-framed"} |
| 39 |
} |
| 40 |
return []string{"", "gzip", "zstd", "zlib", "snappy", "deflate", "lz4"} |
| 41 |
} |
| 42 |
|
| 43 |
type compressRoundTripper struct { |
| 44 |
rt http.RoundTripper |
| 45 |
compressionType configcompression.Type |
| 46 |
compressionParams configcompression.CompressionParams |
| 47 |
compressor *compressor |
| 48 |
} |
| 49 |
|
| 50 |
var zstdReaderPool sync.Pool |
| 51 |
|
| 52 |
type pooledZstdReadCloser struct { |
| 53 |
inner *zstd.Decoder |
| 54 |
} |
| 55 |
|
| 56 |
func (pzrc *pooledZstdReadCloser) Read(dst []byte) (int, error) { |
| 57 |
if pzrc.inner == nil { |
| 58 |
return 0, zstd.ErrDecoderClosed |
| 59 |
} |
| 60 |
return pzrc.inner.Read(dst) |
| 61 |
} |
| 62 |
|
| 63 |
func (pzrc *pooledZstdReadCloser) Close() error { |
| 64 |
if pzrc.inner != nil { |
| 65 |
err := pzrc.inner.Reset(nil) |
| 66 |
if err != nil { |
| 67 |
return err |
| 68 |
} |
| 69 |
zstdReaderPool.Put(pzrc.inner) |
| 70 |
pzrc.inner = nil |
| 71 |
} |
| 72 |
return nil |
| 73 |
} |
| 74 |
|
| 75 |
var availableDecoders = map[string]func(body io.ReadCloser) (io.ReadCloser, error){ |
| 76 |
"": func(io.ReadCloser) (io.ReadCloser, error) { |
| 77 |
// Not a compressed payload. Nothing to do. |
| 78 |
return nil, nil |
| 79 |
}, |
| 80 |
"gzip": func(body io.ReadCloser) (io.ReadCloser, error) { |
| 81 |
gr, err := gzip.NewReader(body) |
| 82 |
if err != nil { |
| 83 |
return nil, err |
| 84 |
} |
| 85 |
return gr, nil |
| 86 |
}, |
| 87 |
"zstd": func(body io.ReadCloser) (io.ReadCloser, error) { |
| 88 |
v := zstdReaderPool.Get() |
| 89 |
var zr *zstd.Decoder |
| 90 |
var err error |
| 91 |
if v == nil { |
| 92 |
// NOTE(tigrannajaryan): |
| 93 |
// Concurrency 1 disables async decoding. We don't need async decoding, it is pointless |
| 94 |
// for our use-case (a server accepting decoding http requests). |
| 95 |
// Disabling async improves performance (I benchmarked it previously when working |
| 96 |
// on https://github.com/open-telemetry/opentelemetry-collector-contrib/pull/23257). |
| 97 |
zr, err = zstd.NewReader(body, zstd.WithDecoderConcurrency(1)) |
| 98 |
} else { |
| 99 |
zr = v.(*zstd.Decoder) |
| 100 |
err = zr.Reset(body) |
| 101 |
} |
| 102 |
if err != nil { |
| 103 |
return nil, err |
| 104 |
} |
| 105 |
return &pooledZstdReadCloser{inner: zr}, nil |
| 106 |
}, |
| 107 |
"zlib": func(body io.ReadCloser) (io.ReadCloser, error) { |
| 108 |
zr, err := zlib.NewReader(body) |
| 109 |
if err != nil { |
| 110 |
return nil, err |
| 111 |
} |
| 112 |
return zr, nil |
| 113 |
}, |
| 114 |
"snappy": snappyHandler, |
| 115 |
//nolint:unparam // Ignoring the linter request to remove error return since it needs to match the method signature |
| 116 |
"lz4": func(body io.ReadCloser) (io.ReadCloser, error) { |
| 117 |
return &compressReadCloser{ |
| 118 |
Reader: lz4.NewReader(body), |
| 119 |
orig: body, |
| 120 |
}, nil |
| 121 |
}, |
| 122 |
//nolint:unparam // Ignoring the linter request to remove error return since it needs to match the method signature |
| 123 |
"x-snappy-framed": func(body io.ReadCloser) (io.ReadCloser, error) { |
| 124 |
return &compressReadCloser{ |
| 125 |
Reader: snappy.NewReader(body), |
| 126 |
orig: body, |
| 127 |
}, nil |
| 128 |
}, |
| 129 |
} |
| 130 |
|
| 131 |
// snappyFramingHeader is always the first 10 bytes of a snappy framed stream. |
| 132 |
var snappyFramingHeader = []byte{ |
| 133 |
0xff, 0x06, 0x00, 0x00, |
| 134 |
0x73, 0x4e, 0x61, 0x50, 0x70, 0x59, // "sNaPpY" |
| 135 |
} |
| 136 |
|
| 137 |
// snappyHandler returns an io.ReadCloser that auto-detects the snappy format. |
| 138 |
// This is necessary because the collector previously used "content-encoding: snappy" |
| 139 |
// but decompressed and compressed the payloads using the snappy framing format. |
| 140 |
// However, "content-encoding: snappy" is uses the block format, and "x-snappy-framed" |
| 141 |
// is the framing format. This handler is a (hopefully temporary) hack to |
| 142 |
// make this work in a backwards-compatible way. |
| 143 |
// |
| 144 |
// See https://github.com/google/snappy/blob/6af9287fbdb913f0794d0148c6aa43b58e63c8e3/framing_format.txt#L27-L36 |
| 145 |
// for more details on the framing format. |
| 146 |
func snappyHandler(body io.ReadCloser) (io.ReadCloser, error) { |
| 147 |
br := bufio.NewReader(body) |
| 148 |
|
| 149 |
peekBytes, err := br.Peek(len(snappyFramingHeader)) |
| 150 |
if err != nil && !errors.Is(err, io.EOF) { |
| 151 |
return nil, err |
| 152 |
} |
| 153 |
|
| 154 |
isFramed := len(peekBytes) >= len(snappyFramingHeader) && bytes.Equal(peekBytes[:len(snappyFramingHeader)], snappyFramingHeader) |
| 155 |
|
| 156 |
if isFramed { |
| 157 |
return &compressReadCloser{ |
| 158 |
Reader: snappy.NewReader(br), |
| 159 |
orig: body, |
| 160 |
}, nil |
| 161 |
} |
| 162 |
compressed, err := io.ReadAll(br) |
| 163 |
if err != nil { |
| 164 |
return nil, err |
| 165 |
} |
| 166 |
decoded, err := snappy.Decode(nil, compressed) |
| 167 |
if err != nil { |
| 168 |
return nil, err |
| 169 |
} |
| 170 |
return io.NopCloser(bytes.NewReader(decoded)), nil |
| 171 |
} |
| 172 |
|
| 173 |
func newCompressionParams(level configcompression.Level) configcompression.CompressionParams { |
| 174 |
return configcompression.CompressionParams{ |
| 175 |
Level: level, |
| 176 |
} |
| 177 |
} |
| 178 |
|
| 179 |
func newCompressRoundTripper(rt http.RoundTripper, compressionType configcompression.Type, compressionParams configcompression.CompressionParams) (*compressRoundTripper, error) { |
| 180 |
encoder, err := newCompressor(compressionType, compressionParams) |
| 181 |
if err != nil { |
| 182 |
return nil, err |
| 183 |
} |
| 184 |
return &compressRoundTripper{ |
| 185 |
rt: rt, |
| 186 |
compressionType: compressionType, |
| 187 |
compressionParams: compressionParams, |
| 188 |
compressor: encoder, |
| 189 |
}, nil |
| 190 |
} |
| 191 |
|
| 192 |
func (r *compressRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) { |
| 193 |
if req.Header.Get(headerContentEncoding) != "" { |
| 194 |
// If the header already specifies a content encoding then skip compression |
| 195 |
// since we don't want to compress it again. This is a safeguard that normally |
| 196 |
// should not happen since CompressRoundTripper is not intended to be used |
| 197 |
// with http clients which already do their own compression. |
| 198 |
return r.rt.RoundTrip(req) |
| 199 |
} |
| 200 |
|
| 201 |
// Compress the body. |
| 202 |
buf := bytes.NewBuffer([]byte{}) |
| 203 |
if err := r.compressor.compress(buf, req.Body); err != nil { |
| 204 |
return nil, err |
| 205 |
} |
| 206 |
|
| 207 |
// Create a new request since the docs say that we cannot modify the "req" |
| 208 |
// (see https://golang.org/pkg/net/http/#RoundTripper). |
| 209 |
cReq, err := http.NewRequestWithContext(req.Context(), req.Method, req.URL.String(), buf) |
| 210 |
if err != nil { |
| 211 |
return nil, err |
| 212 |
} |
| 213 |
|
| 214 |
// Clone the headers and add the encoding header. |
| 215 |
cReq.Header = req.Header.Clone() |
| 216 |
cReq.Header.Add(headerContentEncoding, string(r.compressionType)) |
| 217 |
|
| 218 |
return r.rt.RoundTrip(cReq) |
| 219 |
} |
| 220 |
|
| 221 |
type decompressor struct { |
| 222 |
errHandler func(w http.ResponseWriter, r *http.Request, errorMsg string, statusCode int) |
| 223 |
base http.Handler |
| 224 |
decoders map[string]func(body io.ReadCloser) (io.ReadCloser, error) |
| 225 |
maxRequestBodySize int64 |
| 226 |
} |
| 227 |
|
| 228 |
// httpContentDecompressor offloads the task of handling compressed HTTP requests |
| 229 |
// by identifying the compression format in the "Content-Encoding" header and re-writing |
| 230 |
// request body so that the handlers further in the chain can work on decompressed data. |
| 231 |
func httpContentDecompressor(h http.Handler, maxRequestBodySize int64, eh func(w http.ResponseWriter, r *http.Request, errorMsg string, statusCode int), enableDecoders []string, decoders map[string]func(body io.ReadCloser) (io.ReadCloser, error)) http.Handler { |
| 232 |
errHandler := defaultErrorHandler |
| 233 |
if eh != nil { |
| 234 |
errHandler = eh |
| 235 |
} |
| 236 |
|
| 237 |
enabled := map[string]func(body io.ReadCloser) (io.ReadCloser, error){} |
| 238 |
for _, dec := range enableDecoders { |
| 239 |
if dec == "x-frame-snappy" && !enableFramedSnappy.IsEnabled() { |
| 240 |
continue |
| 241 |
} |
| 242 |
enabled[dec] = availableDecoders[dec] |
| 243 |
|
| 244 |
if dec == "deflate" { |
| 245 |
enabled["deflate"] = availableDecoders["zlib"] |
| 246 |
} |
| 247 |
} |
| 248 |
|
| 249 |
d := &decompressor{ |
| 250 |
maxRequestBodySize: maxRequestBodySize, |
| 251 |
errHandler: errHandler, |
| 252 |
base: h, |
| 253 |
decoders: enabled, |
| 254 |
} |
| 255 |
|
| 256 |
maps.Copy(d.decoders, decoders) |
| 257 |
|
| 258 |
return d |
| 259 |
} |
| 260 |
|
| 261 |
func (d *decompressor) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| 262 |
newBody, err := d.newBodyReader(r) |
| 263 |
if err != nil { |
| 264 |
d.errHandler(w, r, err.Error(), http.StatusBadRequest) |
| 265 |
return |
| 266 |
} |
| 267 |
if newBody != nil { |
| 268 |
defer newBody.Close() |
| 269 |
// "Content-Encoding" header is removed to avoid decompressing twice |
| 270 |
// in case the next handler(s) have implemented a similar mechanism. |
| 271 |
r.Header.Del("Content-Encoding") |
| 272 |
// "Content-Length" is set to -1 as the size of the decompressed body is unknown. |
| 273 |
r.Header.Del("Content-Length") |
| 274 |
r.ContentLength = -1 |
| 275 |
r.Body = http.MaxBytesReader(w, newBody, d.maxRequestBodySize) |
| 276 |
} |
| 277 |
d.base.ServeHTTP(w, r) |
| 278 |
} |
| 279 |
|
| 280 |
func (d *decompressor) newBodyReader(r *http.Request) (io.ReadCloser, error) { |
| 281 |
if len(d.decoders) == 0 { |
| 282 |
return nil, nil // Signal: don't replace r.Body |
| 283 |
} |
| 284 |
encoding := r.Header.Get(headerContentEncoding) |
| 285 |
|
| 286 |
decoder, ok := d.decoders[encoding] |
| 287 |
if !ok { |
| 288 |
return nil, fmt.Errorf("unsupported %s: %s", headerContentEncoding, encoding) |
| 289 |
} |
| 290 |
return decoder(r.Body) |
| 291 |
} |
| 292 |
|
| 293 |
// defaultErrorHandler writes the error message in plain text. |
| 294 |
func defaultErrorHandler(w http.ResponseWriter, _ *http.Request, errMsg string, statusCode int) { |
| 295 |
http.Error(w, errMsg, statusCode) |
| 296 |
} |