forked from cortexproject/cortex
-
Notifications
You must be signed in to change notification settings - Fork 0
/
user_state.go
402 lines (344 loc) · 11.5 KB
/
user_state.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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
package ingester
import (
"context"
"fmt"
"net/http"
"sync"
"time"
"github.com/go-kit/kit/log/level"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/common/model"
"github.com/prometheus/prometheus/pkg/labels"
tsdb_record "github.com/prometheus/prometheus/tsdb/record"
"github.com/segmentio/fasthash/fnv1a"
"github.com/weaveworks/common/httpgrpc"
"github.com/weaveworks/common/user"
"github.com/cortexproject/cortex/pkg/ingester/client"
"github.com/cortexproject/cortex/pkg/ingester/index"
"github.com/cortexproject/cortex/pkg/util"
"github.com/cortexproject/cortex/pkg/util/extract"
"github.com/cortexproject/cortex/pkg/util/spanlogger"
"github.com/cortexproject/cortex/pkg/util/validation"
)
// userStates holds the userState object for all users (tenants),
// each one containing all the in-memory series for a given user.
type userStates struct {
states sync.Map
limiter *Limiter
cfg Config
metrics *ingesterMetrics
}
type userState struct {
limiter *Limiter
userID string
fpLocker *fingerprintLocker
fpToSeries *seriesMap
mapper *fpMapper
index *index.InvertedIndex
ingestedAPISamples *ewmaRate
ingestedRuleSamples *ewmaRate
activeSeries *ActiveSeries
seriesInMetric *metricCounter
// Series metrics.
memSeries prometheus.Gauge
memSeriesCreatedTotal prometheus.Counter
memSeriesRemovedTotal prometheus.Counter
discardedSamples *prometheus.CounterVec
createdChunks prometheus.Counter
activeSeriesGauge prometheus.Gauge
}
// DiscardedSamples metric labels
const (
perUserSeriesLimit = "per_user_series_limit"
perMetricSeriesLimit = "per_metric_series_limit"
)
func newUserStates(limiter *Limiter, cfg Config, metrics *ingesterMetrics) *userStates {
return &userStates{
limiter: limiter,
cfg: cfg,
metrics: metrics,
}
}
func (us *userStates) cp() map[string]*userState {
states := map[string]*userState{}
us.states.Range(func(key, value interface{}) bool {
states[key.(string)] = value.(*userState)
return true
})
return states
}
//nolint:unused
func (us *userStates) gc() {
us.states.Range(func(key, value interface{}) bool {
state := value.(*userState)
if state.fpToSeries.length() == 0 {
us.states.Delete(key)
state.activeSeries.clear()
state.activeSeriesGauge.Set(0)
}
return true
})
}
func (us *userStates) updateRates() {
us.states.Range(func(key, value interface{}) bool {
state := value.(*userState)
state.ingestedAPISamples.tick()
state.ingestedRuleSamples.tick()
return true
})
}
// Labels will be copied if they are kept.
func (us *userStates) updateActiveSeriesForUser(userID string, now time.Time, lbls []labels.Label) {
if s, ok := us.get(userID); ok {
s.activeSeries.UpdateSeries(lbls, now, func(l labels.Labels) labels.Labels { return client.CopyLabels(l) })
}
}
func (us *userStates) purgeAndUpdateActiveSeries(purgeTime time.Time) {
us.states.Range(func(key, value interface{}) bool {
state := value.(*userState)
state.activeSeries.Purge(purgeTime)
state.activeSeriesGauge.Set(float64(state.activeSeries.Active()))
return true
})
}
func (us *userStates) get(userID string) (*userState, bool) {
state, ok := us.states.Load(userID)
if !ok {
return nil, ok
}
return state.(*userState), ok
}
func (us *userStates) getOrCreate(userID string) *userState {
state, ok := us.get(userID)
if !ok {
// Speculatively create a userState object and try to store it
// in the map. Another goroutine may have got there before
// us, in which case this userState will be discarded
state = &userState{
userID: userID,
limiter: us.limiter,
fpToSeries: newSeriesMap(),
fpLocker: newFingerprintLocker(16 * 1024),
index: index.New(),
ingestedAPISamples: newEWMARate(0.2, us.cfg.RateUpdatePeriod),
ingestedRuleSamples: newEWMARate(0.2, us.cfg.RateUpdatePeriod),
seriesInMetric: newMetricCounter(us.limiter),
memSeries: us.metrics.memSeries,
memSeriesCreatedTotal: us.metrics.memSeriesCreatedTotal.WithLabelValues(userID),
memSeriesRemovedTotal: us.metrics.memSeriesRemovedTotal.WithLabelValues(userID),
discardedSamples: validation.DiscardedSamples.MustCurryWith(prometheus.Labels{"user": userID}),
createdChunks: us.metrics.createdChunks,
activeSeries: NewActiveSeries(),
activeSeriesGauge: us.metrics.activeSeriesPerUser.WithLabelValues(userID),
}
state.mapper = newFPMapper(state.fpToSeries)
stored, ok := us.states.LoadOrStore(userID, state)
if !ok {
us.metrics.memUsers.Inc()
}
state = stored.(*userState)
}
return state
}
// teardown ensures metrics are accurately updated if a userStates struct is discarded
func (us *userStates) teardown() {
for _, u := range us.cp() {
u.memSeriesRemovedTotal.Add(float64(u.fpToSeries.length()))
u.memSeries.Sub(float64(u.fpToSeries.length()))
u.activeSeriesGauge.Set(0)
us.metrics.memUsers.Dec()
}
}
func (us *userStates) getViaContext(ctx context.Context) (*userState, bool, error) {
userID, err := user.ExtractOrgID(ctx)
if err != nil {
return nil, false, fmt.Errorf("no user id")
}
state, ok := us.get(userID)
return state, ok, nil
}
// NOTE: memory for `labels` is unsafe; anything retained beyond the
// life of this function must be copied
func (us *userStates) getOrCreateSeries(ctx context.Context, userID string, labels []client.LabelAdapter, record *WALRecord) (*userState, model.Fingerprint, *memorySeries, error) {
state := us.getOrCreate(userID)
// WARNING: `err` may have a reference to unsafe memory in `labels`
fp, series, err := state.getSeries(labels, record)
return state, fp, series, err
}
// NOTE: memory for `metric` is unsafe; anything retained beyond the
// life of this function must be copied
func (u *userState) getSeries(metric labelPairs, record *WALRecord) (model.Fingerprint, *memorySeries, error) {
rawFP := client.FastFingerprint(metric)
u.fpLocker.Lock(rawFP)
fp := u.mapper.mapFP(rawFP, metric)
if fp != rawFP {
u.fpLocker.Unlock(rawFP)
u.fpLocker.Lock(fp)
}
series, ok := u.fpToSeries.get(fp)
if ok {
return fp, series, nil
}
series, err := u.createSeriesWithFingerprint(fp, metric, record, false)
if err != nil {
u.fpLocker.Unlock(fp)
return 0, nil, err
}
return fp, series, nil
}
func (u *userState) createSeriesWithFingerprint(fp model.Fingerprint, metric labelPairs, record *WALRecord, recovery bool) (*memorySeries, error) {
// There's theoretically a relatively harmless race here if multiple
// goroutines get the length of the series map at the same time, then
// all proceed to add a new series. This is likely not worth addressing,
// as this should happen rarely (all samples from one push are added
// serially), and the overshoot in allowed series would be minimal.
if !recovery {
if err := u.limiter.AssertMaxSeriesPerUser(u.userID, u.fpToSeries.length()); err != nil {
return nil, makeLimitError(perUserSeriesLimit, err)
}
}
// MetricNameFromLabelAdapters returns a copy of the string in `metric`
metricName, err := extract.MetricNameFromLabelAdapters(metric)
if err != nil {
return nil, err
}
if !recovery {
// Check if the per-metric limit has been exceeded
if err = u.seriesInMetric.canAddSeriesFor(u.userID, metricName); err != nil {
// WARNING: returns a reference to `metric`
return nil, makeMetricLimitError(perMetricSeriesLimit, client.FromLabelAdaptersToLabels(metric), err)
}
}
u.memSeriesCreatedTotal.Inc()
u.memSeries.Inc()
u.seriesInMetric.increaseSeriesForMetric(metricName)
if record != nil {
lbls := make(labels.Labels, 0, len(metric))
for _, m := range metric {
lbls = append(lbls, labels.Label(m))
}
record.Series = append(record.Series, tsdb_record.RefSeries{
Ref: uint64(fp),
Labels: lbls,
})
}
labels := u.index.Add(metric, fp) // Add() returns 'interned' values so the original labels are not retained
series := newMemorySeries(labels, u.createdChunks)
u.fpToSeries.put(fp, series)
return series, nil
}
func (u *userState) removeSeries(fp model.Fingerprint, metric labels.Labels) {
u.fpToSeries.del(fp)
u.index.Delete(metric, fp)
metricName := metric.Get(model.MetricNameLabel)
if metricName == "" {
// Series without a metric name should never be able to make it into
// the ingester's memory storage.
panic("No metric name label")
}
u.seriesInMetric.decreaseSeriesForMetric(metricName)
u.memSeriesRemovedTotal.Inc()
u.memSeries.Dec()
}
// forSeriesMatching passes all series matching the given matchers to the
// provided callback. Deals with locking and the quirks of zero-length matcher
// values. There are 2 callbacks:
// - The `add` callback is called for each series while the lock is held, and
// is intend to be used by the caller to build a batch.
// - The `send` callback is called at certain intervals specified by batchSize
// with no locks held, and is intended to be used by the caller to send the
// built batches.
func (u *userState) forSeriesMatching(ctx context.Context, allMatchers []*labels.Matcher,
add func(context.Context, model.Fingerprint, *memorySeries) error,
send func(context.Context) error, batchSize int,
) error {
log, ctx := spanlogger.New(ctx, "forSeriesMatching")
defer log.Finish()
filters, matchers := util.SplitFiltersAndMatchers(allMatchers)
fps := u.index.Lookup(matchers)
if len(fps) > u.limiter.MaxSeriesPerQuery(u.userID) {
return httpgrpc.Errorf(http.StatusRequestEntityTooLarge, "exceeded maximum number of series in a query")
}
level.Debug(log).Log("series", len(fps))
// We only hold one FP lock at once here, so no opportunity to deadlock.
sent := 0
outer:
for _, fp := range fps {
if err := ctx.Err(); err != nil {
return err
}
u.fpLocker.Lock(fp)
series, ok := u.fpToSeries.get(fp)
if !ok {
u.fpLocker.Unlock(fp)
continue
}
for _, filter := range filters {
if !filter.Matches(series.metric.Get(filter.Name)) {
u.fpLocker.Unlock(fp)
continue outer
}
}
err := add(ctx, fp, series)
u.fpLocker.Unlock(fp)
if err != nil {
return err
}
sent++
if batchSize > 0 && sent%batchSize == 0 && send != nil {
if err = send(ctx); err != nil {
return nil
}
}
}
if batchSize > 0 && sent%batchSize > 0 && send != nil {
return send(ctx)
}
return nil
}
const numMetricCounterShards = 128
type metricCounterShard struct {
mtx sync.Mutex
m map[string]int
}
type metricCounter struct {
limiter *Limiter
shards []metricCounterShard
}
func newMetricCounter(limiter *Limiter) *metricCounter {
shards := make([]metricCounterShard, 0, numMetricCounterShards)
for i := 0; i < numMetricCounterShards; i++ {
shards = append(shards, metricCounterShard{
m: map[string]int{},
})
}
return &metricCounter{
limiter: limiter,
shards: shards,
}
}
func (m *metricCounter) decreaseSeriesForMetric(metricName string) {
shard := m.getShard(metricName)
shard.mtx.Lock()
defer shard.mtx.Unlock()
shard.m[metricName]--
if shard.m[metricName] == 0 {
delete(shard.m, metricName)
}
}
func (m *metricCounter) getShard(metricName string) *metricCounterShard {
shard := &m.shards[util.HashFP(model.Fingerprint(fnv1a.HashString64(metricName)))%numMetricCounterShards]
return shard
}
func (m *metricCounter) canAddSeriesFor(userID, metric string) error {
shard := m.getShard(metric)
shard.mtx.Lock()
defer shard.mtx.Unlock()
return m.limiter.AssertMaxSeriesPerMetric(userID, shard.m[metric])
}
func (m *metricCounter) increaseSeriesForMetric(metric string) {
shard := m.getShard(metric)
shard.mtx.Lock()
shard.m[metric]++
shard.mtx.Unlock()
}