forked from grafana/tempo
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathingester.go
More file actions
336 lines (273 loc) · 8.28 KB
/
ingester.go
File metadata and controls
336 lines (273 loc) · 8.28 KB
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
package ingester
import (
"context"
"errors"
"fmt"
"sync"
"time"
"github.com/go-kit/kit/log/level"
"github.com/opentracing/opentracing-go"
ot_log "github.com/opentracing/opentracing-go/log"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"github.com/weaveworks/common/user"
"github.com/cortexproject/cortex/pkg/ring"
"github.com/cortexproject/cortex/pkg/util/log"
"github.com/cortexproject/cortex/pkg/util/services"
"github.com/grafana/tempo/modules/overrides"
"github.com/grafana/tempo/modules/storage"
"github.com/grafana/tempo/pkg/flushqueues"
"github.com/grafana/tempo/pkg/tempopb"
"github.com/grafana/tempo/pkg/validation"
tempodb_wal "github.com/grafana/tempo/tempodb/wal"
)
// ErrReadOnly is returned when the ingester is shutting down and a push was
// attempted.
var ErrReadOnly = errors.New("Ingester is shutting down")
var metricFlushQueueLength = promauto.NewGauge(prometheus.GaugeOpts{
Namespace: "tempo",
Name: "ingester_flush_queue_length",
Help: "The total number of series pending in the flush queue.",
})
// Ingester builds blocks out of incoming traces
type Ingester struct {
services.Service
cfg Config
instancesMtx sync.RWMutex
instances map[string]*instance
readonly bool
lifecycler *ring.Lifecycler
store storage.Store
flushQueues *flushqueues.ExclusiveQueues
flushQueuesDone sync.WaitGroup
limiter *Limiter
subservicesWatcher *services.FailureWatcher
}
// New makes a new Ingester.
func New(cfg Config, store storage.Store, limits *overrides.Overrides) (*Ingester, error) {
i := &Ingester{
cfg: cfg,
instances: map[string]*instance{},
store: store,
flushQueues: flushqueues.New(cfg.ConcurrentFlushes, metricFlushQueueLength),
}
i.flushQueuesDone.Add(cfg.ConcurrentFlushes)
for j := 0; j < cfg.ConcurrentFlushes; j++ {
go i.flushLoop(j)
}
var err error
i.lifecycler, err = ring.NewLifecycler(cfg.LifecyclerConfig, i, "ingester", cfg.OverrideRingKey, true, prometheus.DefaultRegisterer)
if err != nil {
return nil, fmt.Errorf("NewLifecycler failed %w", err)
}
// Now that the lifecycler has been created, we can create the limiter
// which depends on it.
i.limiter = NewLimiter(limits, i.lifecycler, cfg.LifecyclerConfig.RingConfig.ReplicationFactor)
i.subservicesWatcher = services.NewFailureWatcher()
i.subservicesWatcher.WatchService(i.lifecycler)
i.Service = services.NewBasicService(i.starting, i.loop, i.stopping)
return i, nil
}
func (i *Ingester) starting(ctx context.Context) error {
err := i.replayWal()
if err != nil {
return fmt.Errorf("failed to replay wal %w", err)
}
// Now that user states have been created, we can start the lifecycler.
// Important: we want to keep lifecycler running until we ask it to stop, so we need to give it independent context
if err := i.lifecycler.StartAsync(context.Background()); err != nil {
return fmt.Errorf("failed to start lifecycler %w", err)
}
if err := i.lifecycler.AwaitRunning(ctx); err != nil {
return fmt.Errorf("failed to start lifecycle %w", err)
}
return nil
}
func (i *Ingester) loop(ctx context.Context) error {
flushTicker := time.NewTicker(i.cfg.FlushCheckPeriod)
defer flushTicker.Stop()
for {
select {
case <-flushTicker.C:
i.sweepAllInstances(false)
case <-ctx.Done():
return nil
case err := <-i.subservicesWatcher.Chan():
return fmt.Errorf("ingester subservice failed %w", err)
}
}
}
// stopping is run when ingester is asked to stop
func (i *Ingester) stopping(_ error) error {
i.markUnavailable()
if i.flushQueues != nil {
i.flushQueues.Stop()
i.flushQueuesDone.Wait()
}
return nil
}
func (i *Ingester) markUnavailable() {
// Lifecycler can be nil if the ingester is for a flusher.
if i.lifecycler != nil {
// Next initiate our graceful exit from the ring.
if err := services.StopAndAwaitTerminated(context.Background(), i.lifecycler); err != nil {
level.Warn(log.Logger).Log("msg", "failed to stop ingester lifecycler", "err", err)
}
}
// This will prevent us accepting any more samples
i.stopIncomingRequests()
}
// Push implements tempopb.Pusher.Push
func (i *Ingester) Push(ctx context.Context, req *tempopb.PushRequest) (*tempopb.PushResponse, error) {
instanceID, err := user.ExtractOrgID(ctx)
if err != nil {
return nil, err
} else if i.readonly {
return nil, ErrReadOnly
}
instance, err := i.getOrCreateInstance(instanceID)
if err != nil {
return nil, err
}
err = instance.Push(ctx, req)
return &tempopb.PushResponse{}, err
}
// PushBytes implements tempopb.Pusher.PushBytes
func (i *Ingester) PushBytes(ctx context.Context, req *tempopb.PushBytesRequest) (*tempopb.PushResponse, error) {
// Unmarshal and push each request
for _, v := range req.Requests {
r := tempopb.PushRequest{}
err := r.Unmarshal(v)
if err != nil {
return nil, err
}
_, err = i.Push(ctx, &r)
if err != nil {
return nil, err
}
}
return &tempopb.PushResponse{}, nil
}
// FindTraceByID implements tempopb.Querier.f
func (i *Ingester) FindTraceByID(ctx context.Context, req *tempopb.TraceByIDRequest) (*tempopb.TraceByIDResponse, error) {
if !validation.ValidTraceID(req.TraceID) {
return nil, fmt.Errorf("invalid trace id")
}
// tracing instrumentation
span, ctx := opentracing.StartSpanFromContext(ctx, "ingester.FindTraceByID")
defer span.Finish()
instanceID, err := user.ExtractOrgID(ctx)
if err != nil {
return nil, err
}
inst, ok := i.getInstanceByID(instanceID)
if !ok || inst == nil {
return &tempopb.TraceByIDResponse{}, nil
}
trace, err := inst.FindTraceByID(req.TraceID)
if err != nil {
return nil, err
}
span.LogFields(ot_log.Bool("trace found", trace != nil))
return &tempopb.TraceByIDResponse{
Trace: trace,
}, nil
}
func (i *Ingester) CheckReady(ctx context.Context) error {
if err := i.lifecycler.CheckReady(ctx); err != nil {
return fmt.Errorf("ingester check ready failed %w", err)
}
return nil
}
func (i *Ingester) getOrCreateInstance(instanceID string) (*instance, error) {
inst, ok := i.getInstanceByID(instanceID)
if ok {
return inst, nil
}
i.instancesMtx.Lock()
defer i.instancesMtx.Unlock()
inst, ok = i.instances[instanceID]
if !ok {
var err error
inst, err = newInstance(instanceID, i.limiter, i.store)
if err != nil {
return nil, err
}
i.instances[instanceID] = inst
}
return inst, nil
}
func (i *Ingester) getInstanceByID(id string) (*instance, bool) {
i.instancesMtx.RLock()
defer i.instancesMtx.RUnlock()
inst, ok := i.instances[id]
return inst, ok
}
func (i *Ingester) getInstances() []*instance {
i.instancesMtx.RLock()
defer i.instancesMtx.RUnlock()
instances := make([]*instance, 0, len(i.instances))
for _, instance := range i.instances {
instances = append(instances, instance)
}
return instances
}
// stopIncomingRequests implements ring.Lifecycler.
func (i *Ingester) stopIncomingRequests() {
i.instancesMtx.Lock()
defer i.instancesMtx.Unlock()
i.readonly = true
}
// TransferOut implements ring.Lifecycler.
func (i *Ingester) TransferOut(ctx context.Context) error {
return ring.ErrTransferDisabled
}
func (i *Ingester) replayWal() error {
blocks, err := i.store.WAL().AllBlocks()
// todo: should this fail startup?
if err != nil {
return nil
}
level.Info(log.Logger).Log("msg", "beginning wal replay", "numBlocks", len(blocks))
for _, b := range blocks {
tenantID := b.TenantID()
level.Info(log.Logger).Log("msg", "beginning block replay", "tenantID", tenantID)
instance, err := i.getOrCreateInstance(tenantID)
if err != nil {
return err
}
err = i.replayBlock(b, instance)
if err != nil {
// there was an error, log and keep on keeping on
level.Error(log.Logger).Log("msg", "error replaying block. removing", "error", err)
}
err = b.Clear()
if err != nil {
return err
}
}
return nil
}
func (i *Ingester) replayBlock(b *tempodb_wal.ReplayBlock, instance *instance) error {
iterator, err := b.Iterator()
if err != nil {
return err
}
defer iterator.Close()
for {
id, obj, err := iterator.Next()
if id == nil {
break
}
if err != nil {
return err
}
// obj gets written to disk immediately but the id escapes the iterator and needs to be copied
writeID := append([]byte(nil), id...)
err = instance.PushBytes(context.Background(), writeID, obj)
if err != nil {
return err
}
}
return nil
}