-
Notifications
You must be signed in to change notification settings - Fork 460
/
shard_by_series_base.go
223 lines (187 loc) · 6.34 KB
/
shard_by_series_base.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
// SPDX-License-Identifier: AGPL-3.0-only
package querymiddleware
import (
"context"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"github.com/go-kit/log"
"github.com/grafana/dskit/tenant"
"github.com/grafana/dskit/user"
"github.com/opentracing/opentracing-go"
otlog "github.com/opentracing/opentracing-go/log"
"github.com/pkg/errors"
"github.com/prometheus/prometheus/model/labels"
"github.com/prometheus/prometheus/promql/parser"
"golang.org/x/sync/errgroup"
apierror "github.com/grafana/mimir/pkg/api/error"
"github.com/grafana/mimir/pkg/querier/stats"
"github.com/grafana/mimir/pkg/storage/sharding"
"github.com/grafana/mimir/pkg/util"
"github.com/grafana/mimir/pkg/util/spanlogger"
)
type shardBySeriesBase struct {
upstream http.RoundTripper
limits Limits
logger log.Logger
}
func (s *shardBySeriesBase) shardBySeriesSelector(ctx context.Context, spanLog *spanlogger.SpanLogger, r *http.Request, mergeFn func(ctx context.Context, reponses []*http.Response, encoding string) *http.Response) (*http.Response, error) {
tenantID, err := tenant.TenantID(ctx)
if err != nil {
return nil, apierror.New(apierror.TypeBadData, err.Error())
}
defaultShardCount := s.limits.QueryShardingTotalShards(tenantID)
shardCount := setShardCountFromHeader(defaultShardCount, r, spanLog)
if shardCount < 2 {
spanLog.DebugLog("msg", "query sharding disabled for request")
return s.upstream.RoundTrip(r)
}
if maxShards := s.limits.QueryShardingMaxShardedQueries(tenantID); shardCount > maxShards {
return nil, apierror.New(
apierror.TypeBadData,
fmt.Sprintf("shard count %d exceeds allowed maximum (%d)", shardCount, maxShards),
)
}
selector, err := parseSelector(r)
if err != nil {
return nil, apierror.New(apierror.TypeBadData, err.Error())
}
spanLog.DebugLog(
"msg", "sharding active series query",
"shardCount", shardCount, "selector", selector.String(),
)
reqs, err := buildShardedRequests(ctx, r, shardCount, selector)
if err != nil {
return nil, apierror.New(apierror.TypeInternal, err.Error())
}
resp, err := doShardedRequests(ctx, reqs, s.upstream)
if err != nil {
if errors.Is(err, errShardCountTooLow) {
return nil, apierror.New(apierror.TypeBadData, fmt.Errorf("%w: try increasing the requested shard count", err).Error())
}
return nil, apierror.New(apierror.TypeInternal, err.Error())
}
acceptEncoding := r.Header.Get("Accept-Encoding")
return mergeFn(ctx, resp, acceptEncoding), nil
}
func setShardCountFromHeader(origShardCount int, r *http.Request, spanLog *spanlogger.SpanLogger) int {
for _, value := range r.Header.Values(totalShardsControlHeader) {
shards, err := strconv.ParseInt(value, 10, 32)
if err != nil {
continue
}
if shards >= 0 {
spanLog.DebugLog("msg", fmt.Sprintf("using shard count from header %s: %d", totalShardsControlHeader, shards))
return int(shards)
}
}
return origShardCount
}
func parseSelector(req *http.Request) (*parser.VectorSelector, error) {
values, err := util.ParseRequestFormWithoutConsumingBody(req)
if err != nil {
return nil, err
}
valSelector := values.Get("selector")
if valSelector == "" {
return nil, errors.New("selector parameter is required")
}
parsed, err := parser.ParseExpr(valSelector)
if err != nil {
return nil, fmt.Errorf("invalid selector: %w", err)
}
selector, ok := parsed.(*parser.VectorSelector)
if !ok {
return nil, fmt.Errorf("invalid selector: %w", err)
}
return selector, nil
}
func buildShardedRequests(ctx context.Context, req *http.Request, numRequests int, selector parser.Expr) ([]*http.Request, error) {
reqs := make([]*http.Request, numRequests)
for i := 0; i < numRequests; i++ {
r, err := http.NewRequestWithContext(ctx, http.MethodGet, req.URL.Path, http.NoBody)
if err != nil {
return nil, err
}
sharded, err := shardedSelector(numRequests, i, selector)
if err != nil {
return nil, err
}
vals := url.Values{}
vals.Set("selector", sharded.String())
r.URL.RawQuery = vals.Encode()
// This is the field read by httpgrpc.FromHTTPRequest, so we need to populate it
// here to ensure the request parameter makes it to the querier.
r.RequestURI = r.URL.String()
if err := user.InjectOrgIDIntoHTTPRequest(ctx, r); err != nil {
return nil, err
}
reqs[i] = r
}
return reqs, nil
}
func doShardedRequests(ctx context.Context, upstreamRequests []*http.Request, next http.RoundTripper) ([]*http.Response, error) {
resps := make([]*http.Response, len(upstreamRequests))
g, ctx := errgroup.WithContext(ctx)
queryStats := stats.FromContext(ctx)
for i, req := range upstreamRequests {
i, r := i, req
g.Go(func() error {
partialStats, childCtx := stats.ContextWithEmptyStats(ctx)
partialStats.AddShardedQueries(1)
var span opentracing.Span
span, childCtx = opentracing.StartSpanFromContext(childCtx, "shardBySeries.doShardedRequest")
defer span.Finish()
resp, err := next.RoundTrip(r.WithContext(childCtx))
if err != nil {
span.LogFields(otlog.Error(err))
return err
}
if resp.StatusCode != http.StatusOK {
span.LogFields(otlog.Int("statusCode", resp.StatusCode))
if resp.StatusCode == http.StatusRequestEntityTooLarge {
return errShardCountTooLow
}
var body []byte
if resp.Body != nil {
body, _ = io.ReadAll(resp.Body)
}
return fmt.Errorf("received unexpected response from upstream: status %d, body: %s", resp.StatusCode, string(body))
}
resps[i] = resp
span.LogFields(otlog.Uint64("seriesCount", partialStats.LoadFetchedSeries()))
queryStats.Merge(partialStats)
return nil
})
}
err := g.Wait()
if err != nil {
// If there was an error, we need to read and close all response bodies.
for _, resp := range resps {
if resp != nil {
_, _ = io.ReadAll(resp.Body)
_ = resp.Body.Close()
}
}
}
return resps, err
}
func shardedSelector(shardCount, currentShard int, expr parser.Expr) (parser.Expr, error) {
originalSelector, ok := expr.(*parser.VectorSelector)
if !ok {
return nil, errors.New("invalid selector")
}
shardMatcher, err := labels.NewMatcher(
labels.MatchEqual, sharding.ShardLabel,
sharding.ShardSelector{ShardIndex: uint64(currentShard), ShardCount: uint64(shardCount)}.LabelValue(),
)
if err != nil {
return nil, err
}
return &parser.VectorSelector{
Name: originalSelector.Name,
LabelMatchers: append([]*labels.Matcher{shardMatcher}, originalSelector.LabelMatchers...),
}, nil
}