-
Notifications
You must be signed in to change notification settings - Fork 1
/
frontend.go
263 lines (221 loc) · 9.13 KB
/
frontend.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
/*
* Copyright (C) 2023 Intergral GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package frontend
import (
"bytes"
"fmt"
"io"
"net/http"
"net/url"
"path"
"strings"
"github.com/golang/protobuf/jsonpb"
"github.com/golang/protobuf/proto"
"github.com/intergral/deep/pkg/deeppb"
"github.com/opentracing/opentracing-go"
"github.com/pkg/errors"
"github.com/intergral/deep/pkg/deepql"
"github.com/intergral/deep/pkg/util"
"github.com/go-kit/log"
"github.com/go-kit/log/level"
"github.com/intergral/deep/modules/overrides"
"github.com/intergral/deep/modules/storage"
"github.com/intergral/deep/pkg/api"
"github.com/intergral/deep/pkg/deepdb"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
)
const (
snapshotByIDOp = "snapshots"
searchOp = "search"
)
type QueryFrontend struct {
SnapshotByID, Search http.Handler
logger log.Logger
store storage.Store
LoadTracepointHandler http.Handler
DelTracepointHandler http.Handler
}
// New returns a new QueryFrontend
func New(cfg Config, next http.RoundTripper, o *overrides.Overrides, store storage.Store, logger log.Logger, registerer prometheus.Registerer) (*QueryFrontend, error) {
level.Info(logger).Log("msg", "creating middleware in query frontend")
if cfg.SnapshotByID.QueryShards < minQueryShards || cfg.SnapshotByID.QueryShards > maxQueryShards {
return nil, fmt.Errorf("frontend query shards should be between %d and %d (both inclusive)", minQueryShards, maxQueryShards)
}
if cfg.Search.Sharder.ConcurrentRequests <= 0 {
return nil, fmt.Errorf("frontend search concurrent requests should be greater than 0")
}
if cfg.Search.Sharder.TargetBytesPerRequest <= 0 {
return nil, fmt.Errorf("frontend search target bytes per request should be greater than 0")
}
if cfg.Search.Sharder.QueryIngestersUntil < cfg.Search.Sharder.QueryBackendAfter {
return nil, fmt.Errorf("query backend after should be less than or equal to query ingester until")
}
queriesPerTenant := promauto.With(registerer).NewCounterVec(prometheus.CounterOpts{
Namespace: "deep",
Subsystem: "query_frontend",
Name: "queries_total",
Help: "Total queries received per tenant.",
}, []string{"tenant", "op", "status"})
retryWare := newRetryWare(cfg.MaxRetries, registerer)
snapshotByIDMiddleware := MergeMiddlewares(newSnapshotByIDMiddleware(cfg, logger), retryWare)
searchMiddleware := MergeMiddlewares(newSearchMiddleware(cfg, o, store, logger), retryWare)
snapshotByIDCounter := queriesPerTenant.MustCurryWith(prometheus.Labels{"op": snapshotByIDOp})
searchCounter := queriesPerTenant.MustCurryWith(prometheus.Labels{"op": searchOp})
loadTp := queriesPerTenant.MustCurryWith(prometheus.Labels{"op": "loadtp"})
delTp := queriesPerTenant.MustCurryWith(prometheus.Labels{"op": "deltp"})
snapshots := snapshotByIDMiddleware.Wrap(next)
search := searchMiddleware.Wrap(next)
tpMiddleware := newTracepointForwardMiddleware()
tpHandler := tpMiddleware.Wrap(next)
return &QueryFrontend{
SnapshotByID: newHandler(snapshots, snapshotByIDCounter, logger),
Search: newHandler(search, searchCounter, logger),
LoadTracepointHandler: newHandler(tpHandler, loadTp, logger),
DelTracepointHandler: newHandler(tpHandler, delTp, logger),
logger: logger,
store: store,
}, nil
}
func newTracepointForwardMiddleware() Middleware {
return MiddlewareFunc(func(next http.RoundTripper) http.RoundTripper {
return RoundTripperFunc(func(r *http.Request) (*http.Response, error) {
// We just need to modify the uri to match the api expectation
r.RequestURI = buildUpstreamRequestURI(api.PathPrefixTracepoints, r.RequestURI, r.URL.Query())
resp, err := next.RoundTrip(r)
return resp, err
})
})
}
// newSnapshotByIDMiddleware creates a new frontend middleware responsible for handling get snapshot requests.
func newSnapshotByIDMiddleware(cfg Config, logger log.Logger) Middleware {
return MiddlewareFunc(func(next http.RoundTripper) http.RoundTripper {
// We're constructing middleware in this statement, each middleware wraps the next one from left-to-right
// - the ShardingWare shards queries by splitting the block ID space
// - the RetryWare retries requests that have failed (error or http status 500)
rt := NewRoundTripper(
next,
newSnapshotByIDSharder(cfg.SnapshotByID.QueryShards, cfg.TolerateFailedBlocks, cfg.SnapshotByID.SLO, logger),
newHedgedRequestWare(cfg.SnapshotByID.Hedging),
)
return RoundTripperFunc(func(r *http.Request) (*http.Response, error) {
// validate snapshot
_, err := api.ParseSnapshotID(r)
if err != nil {
return &http.Response{
StatusCode: http.StatusBadRequest,
Body: io.NopCloser(strings.NewReader(err.Error())),
Header: http.Header{},
}, nil
}
// validate start and end parameter
_, _, _, _, _, reqErr := api.ValidateAndSanitizeRequest(r)
if reqErr != nil {
return &http.Response{
StatusCode: http.StatusBadRequest,
Body: io.NopCloser(strings.NewReader(reqErr.Error())),
Header: http.Header{},
}, nil
}
// check marshalling format
marshallingFormat := api.HeaderAcceptJSON
if r.Header.Get(api.HeaderAccept) == api.HeaderAcceptProtobuf {
marshallingFormat = api.HeaderAcceptProtobuf
}
// enforce all communication internal to Deep to be in protobuf bytes
r.Header.Set(api.HeaderAccept, api.HeaderAcceptProtobuf)
resp, err := rt.RoundTrip(r)
if resp != nil && resp.StatusCode == http.StatusOK {
body, err := io.ReadAll(resp.Body)
_ = resp.Body.Close()
if err != nil {
return nil, errors.Wrap(err, "error reading response body at query frontend")
}
responseObject := &deeppb.SnapshotByIDResponse{}
err = proto.Unmarshal(body, responseObject)
if err != nil {
return nil, err
}
if marshallingFormat == api.HeaderAcceptJSON {
var jsonSnapshot bytes.Buffer
marshaller := &jsonpb.Marshaler{}
err = marshaller.Marshal(&jsonSnapshot, responseObject.Snapshot)
if err != nil {
return nil, err
}
resp.Body = io.NopCloser(bytes.NewReader(jsonSnapshot.Bytes()))
} else {
snapshotBuffer, err := proto.Marshal(responseObject.Snapshot)
if err != nil {
return nil, err
}
resp.Body = io.NopCloser(bytes.NewReader(snapshotBuffer))
}
if resp.Header != nil {
resp.Header.Set(api.HeaderContentType, marshallingFormat)
}
}
span := opentracing.SpanFromContext(r.Context())
if span != nil {
span.SetTag("contentType", marshallingFormat)
}
return resp, err
})
})
}
// newSearchMiddleware creates a new frontend middleware to handle search and search tags requests.
func newSearchMiddleware(cfg Config, o *overrides.Overrides, reader deepdb.Reader, logger log.Logger) Middleware {
return MiddlewareFunc(func(next http.RoundTripper) http.RoundTripper {
ingesterSearchRT := next
backendSearchRT := NewRoundTripper(next, newSearchSharder(reader, o, cfg.Search.Sharder, cfg.Search.SLO, logger))
return RoundTripperFunc(func(r *http.Request) (*http.Response, error) {
if is, q := api.IsDeepQLReq(r); is {
expr, err := deepql.ParseString(q)
if err != nil {
return nil, err
}
if !expr.IsSearch() {
// forward to tracepoint handler as we are a command/trigger ql
r.RequestURI = buildUpstreamRequestURI(api.PathPrefixTracepoints, api.PathTracepointsQuery, r.URL.Query())
resp, err := next.RoundTrip(r)
return resp, err
}
// we might be ql but we are search so continue
}
// backend search queries require sharding so we pass through a special roundtripper
if api.IsBackendSearch(r) {
return backendSearchRT.RoundTrip(r)
}
// ingester search queries only need to be proxied to a single querier
tenantID, _ := util.ExtractTenantID(r.Context())
r.Header.Set(util.TenantIDHeaderName, tenantID)
r.RequestURI = buildUpstreamRequestURI(api.PathPrefixQuerier, r.RequestURI, nil)
return ingesterSearchRT.RoundTrip(r)
})
})
}
// buildUpstreamRequestURI returns a uri based on the passed parameters
// we do this because weaveworks/common uses the RequestURI field to translate from http.Request to httpgrpc.Request
// https://github.com/weaveworks/common/blob/47e357f4e1badb7da17ad74bae63e228bdd76e8f/httpgrpc/server/server.go#L48
func buildUpstreamRequestURI(prefix, originalURI string, params url.Values) string {
const queryDelimiter = "?"
uri := path.Join(prefix, originalURI)
if len(params) > 0 {
uri += queryDelimiter + params.Encode()
}
return uri
}