-
Notifications
You must be signed in to change notification settings - Fork 455
/
parser.go
324 lines (262 loc) · 8.48 KB
/
parser.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
// SPDX-License-Identifier: AGPL-3.0-only
package main
import (
"bytes"
"compress/gzip"
"context"
"flag"
"fmt"
"io"
"log"
"mime"
"net/http"
"net/url"
"strings"
"github.com/grafana/regexp"
"github.com/prometheus/prometheus/model/labels"
promql_parser "github.com/prometheus/prometheus/promql/parser"
"go.opentelemetry.io/collector/pdata/pmetric/pmetricotlp"
"github.com/grafana/mimir/pkg/mimirpb"
"github.com/grafana/mimir/pkg/util"
)
const maxBufferPoolSize = 1024 * 1024
var bufferPool = util.NewBucketedBufferPool(1e3, maxBufferPoolSize, 2)
type parser struct {
processorConfig processorConfig
requestHeaders bool
requestRawBody bool
decodePush bool
includeSamples bool
responseHeaders bool
responseRawBody bool
responseDecodeBody bool
tenantRegexpStr string
tenantRegexp *regexp.Regexp
pathRegexpStr string
pathRegexp *regexp.Regexp
ignorePathRegexpStr string
ignorePathRegexp *regexp.Regexp
metricSelector string
matchers []*labels.Matcher
}
func (rp *parser) RegisterFlags(f *flag.FlagSet) {
rp.processorConfig.RegisterFlags(f)
f.StringVar(&rp.pathRegexpStr, "path", "", "Output only requests matching this URL path (regex).")
f.StringVar(&rp.ignorePathRegexpStr, "ignore-path", "", "If not empty, and URL path matches this regex, request is ignored.")
f.StringVar(&rp.tenantRegexpStr, "tenant", "", "Output only requests for this tenant (regex).")
f.StringVar(&rp.metricSelector, "select", "", "If set, only output write requests that include series matching this selector. Used only when -request.decode-remote-write is enabled. (Only works for Prometheus requests)")
f.BoolVar(&rp.requestHeaders, "request.headers", false, "Include request headers in the output")
f.BoolVar(&rp.requestRawBody, "request.raw-body", false, "Include raw request body in the output")
f.BoolVar(&rp.decodePush, "request.decode-remote-write", false, "Decode Prometheus or OTEL metrics requests. Only for POST requests that contain /push (Prometheus) or /metrics (OTEL) in the path")
f.BoolVar(&rp.includeSamples, "request.samples", false, "Include samples in the output. Used only when -request.decode-remote-write is enabled. (Only works with Prometheus requests)")
f.BoolVar(&rp.responseHeaders, "response.headers", false, "Include HTTP headers in the response")
f.BoolVar(&rp.responseRawBody, "response.raw-body", false, "Include raw body in the response")
f.BoolVar(&rp.responseDecodeBody, "response.decode-body", true, "Decode body (eg. gzip). If response body is JSON, it is included in json_body field.")
}
func (rp *parser) prepare() {
if rp.ignorePathRegexpStr != "" {
rp.ignorePathRegexp = regexp.MustCompile(rp.ignorePathRegexpStr)
}
if rp.pathRegexpStr != "" {
rp.pathRegexp = regexp.MustCompile(rp.pathRegexpStr)
}
if rp.tenantRegexpStr != "" {
rp.tenantRegexp = regexp.MustCompile(rp.tenantRegexpStr)
}
if rp.metricSelector != "" {
var err error
rp.matchers, err = promql_parser.ParseMetricSelector(rp.metricSelector)
if err != nil {
log.Fatalln("failed to parse matcher selector", "err", err)
}
for _, m := range rp.matchers {
log.Println("using matcher:", m.String())
}
}
}
func (rp *parser) processHTTPRequest(req *http.Request, body []byte) *request {
if rp.ignorePathRegexp != nil && rp.ignorePathRegexp.MatchString(req.URL.Path) {
return &request{ignored: true}
}
if rp.pathRegexp != nil && !rp.pathRegexp.MatchString(req.URL.Path) {
return &request{ignored: true}
}
tenant := req.Header.Get("X-Scope-OrgId")
if tenant == "" {
tenant, _, _ = req.BasicAuth()
}
if rp.tenantRegexp != nil && (tenant == "" || !rp.tenantRegexp.MatchString(tenant)) {
return &request{ignored: true}
}
r := request{
Method: req.Method,
URL: requestURL{
Path: req.URL.Path,
Query: req.URL.Query(),
},
Tenant: tenant,
}
if rp.requestRawBody {
r.RawBody = string(body)
}
if ct, _, _ := mime.ParseMediaType(req.Header.Get("Content-Type")); ct == "application/x-www-form-urlencoded" {
vs, _ := url.ParseQuery(string(body))
r.Form = vs
}
if rp.requestHeaders {
r.Headers = req.Header
}
if rp.decodePush && req.Method == "POST" && strings.Contains(req.URL.Path, "/push") {
var matched bool
rb := util.NewRequestBuffers(bufferPool)
r.cleanup = rb.CleanUp
r.PushRequest, matched = rp.decodePushRequest(req, body, rp.matchers, rb)
if !matched {
r.ignored = true
}
}
// Support POST to /otlp/v1/metrics
if rp.decodePush && req.Method == "POST" && strings.Contains(req.URL.Path, "/metrics") {
var matched bool
r.PushRequest, matched = rp.decodeOTLPRequest(req, body)
if !matched {
r.ignored = true
}
}
return &r
}
func (rp *parser) decodePushRequest(req *http.Request, body []byte, matchers []*labels.Matcher, buffers *util.RequestBuffers) (*pushRequest, bool) {
res := &pushRequest{Version: req.Header.Get("X-Prometheus-Remote-Write-Version")}
var wr mimirpb.WriteRequest
if _, err := util.ParseProtoReader(context.Background(), bytes.NewReader(body), int(req.ContentLength), 100<<20, buffers, &wr, util.RawSnappy); err != nil {
res.Error = fmt.Errorf("failed to decode decodePush request: %s", err).Error()
return nil, true
}
// See if we find the matching series. If not, we ignore this request.
if matchers != nil {
matched := false
for _, ts := range wr.Timeseries {
lbls := mimirpb.FromLabelAdaptersToLabels(ts.Labels)
if matches(lbls, matchers) {
matched = true
break
}
}
if !matched {
return nil, false
}
}
for _, ts := range wr.Timeseries {
t := timeseries{
Labels: mimirpb.FromLabelAdaptersToLabels(ts.Labels),
}
if rp.includeSamples {
t.Samples = ts.TimeSeries.Samples
t.Exemplars = ts.TimeSeries.Exemplars
} else {
t.SamplesCount = len(ts.TimeSeries.Samples)
t.ExemplarsCount = len(ts.TimeSeries.Exemplars)
}
res.TimeSeries = append(res.TimeSeries, t)
}
res.Metadata = wr.Metadata
return res, true
}
func matches(lbls labels.Labels, matchers []*labels.Matcher) bool {
for _, m := range matchers {
val := lbls.Get(m.Name)
if !m.Matches(val) {
return false
}
}
return true
}
func (rp *parser) processHTTPResponse(resp *http.Response, body []byte) *response {
out := response{
Status: resp.Status,
StatusCode: resp.StatusCode,
Proto: resp.Proto,
}
const ce = "Content-Encoding"
if rp.responseDecodeBody && resp.Header.Get(ce) == "gzip" {
// decode body
var err error
var r *gzip.Reader
r, err = gzip.NewReader(bytes.NewReader(body))
if err == nil {
var newBody []byte
newBody, err = io.ReadAll(r)
if err == nil {
body = newBody
}
}
if err != nil {
out.Error = fmt.Sprintf("failed to gzip-decode response body: %s", err.Error())
}
}
ct, _, _ := mime.ParseMediaType(resp.Header.Get("Content-Type"))
if ct == "application/json" && rp.responseDecodeBody {
out.JSONBody = body
}
if ct == "text/plain" {
out.TextBody = string(body)
}
if rp.responseHeaders {
out.Headers = resp.Header
}
if rp.responseRawBody {
out.RawBody = string(body)
}
return &out
}
const (
pbContentType = "application/x-protobuf"
jsonContentType = "application/json"
)
func (rp *parser) decodeOTLPRequest(req *http.Request, body []byte) (*otlpPushRequest, bool) {
res := &otlpPushRequest{}
var decoderFunc func(buf []byte) (pmetricotlp.ExportRequest, error)
contentType := req.Header.Get("Content-Type")
switch contentType {
case pbContentType:
decoderFunc = func(buf []byte) (pmetricotlp.ExportRequest, error) {
req := pmetricotlp.NewExportRequest()
return req, req.UnmarshalProto(buf)
}
case jsonContentType:
decoderFunc = func(buf []byte) (pmetricotlp.ExportRequest, error) {
req := pmetricotlp.NewExportRequest()
return req, req.UnmarshalJSON(buf)
}
default:
res.Error = fmt.Sprintf("unsupported content type: %s", contentType)
return nil, false
}
// Handle compression.
contentEncoding := req.Header.Get("Content-Encoding")
switch contentEncoding {
case "gzip":
gr, err := gzip.NewReader(bytes.NewReader(body))
if err != nil {
res.Error = fmt.Sprintf("failed to decode gzip request: %v", err)
return nil, true
}
body, err = io.ReadAll(gr)
if err != nil {
res.Error = fmt.Sprintf("failed to decode gzip request: %v", err)
return nil, true
}
case "":
// No compression.
default:
res.Error = fmt.Sprintf("unsupported compression for otel: %s", contentEncoding)
return nil, true
}
var err error
res.ExportRequest, err = decoderFunc(body)
if err != nil {
res.Error = fmt.Sprintf("failed to decode request: %v", err)
return nil, true
}
return res, true
}