/
poller.go
366 lines (309 loc) · 11.9 KB
/
poller.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
/*
* 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 blocklist
import (
"context"
"fmt"
"math/rand"
"sort"
"strconv"
"time"
"github.com/go-kit/log"
"github.com/go-kit/log/level"
"github.com/google/uuid"
"github.com/intergral/deep/pkg/boundedwaitgroup"
"github.com/intergral/deep/pkg/deepdb/backend"
opentracing "github.com/opentracing/opentracing-go"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"go.uber.org/atomic"
)
const (
blockStatusLiveLabel = "live"
blockStatusCompactedLabel = "compacted"
)
var (
metricBackendObjects = promauto.NewGaugeVec(prometheus.GaugeOpts{
Namespace: "deep",
Subsystem: "db",
Name: "backend_objects_total",
Help: "Total number of objects (snapshots) in the backend",
}, []string{"tenant", "status"})
metricBackendBytes = promauto.NewGaugeVec(prometheus.GaugeOpts{
Namespace: "deep",
Subsystem: "db",
Name: "backend_bytes_total",
Help: "Total number of bytes in the backend.",
}, []string{"tenant", "status"})
metricBlocklistErrors = promauto.NewCounterVec(prometheus.CounterOpts{
Namespace: "deep",
Subsystem: "db",
Name: "blocklist_poll_errors_total",
Help: "Total number of times an error occurred while polling the blocklist.",
}, []string{"tenant"})
metricBlocklistPollDuration = promauto.NewHistogram(prometheus.HistogramOpts{
Namespace: "deep",
Subsystem: "db",
Name: "blocklist_poll_duration_seconds",
Help: "Records the amount of time to poll and update the blocklist.",
Buckets: prometheus.LinearBuckets(0, 60, 5),
})
metricBlocklistLength = promauto.NewGaugeVec(prometheus.GaugeOpts{
Namespace: "deep",
Subsystem: "db",
Name: "blocklist_length",
Help: "Total number of blocks per tenant.",
}, []string{"tenant"})
metricTenantIndexErrors = promauto.NewCounterVec(prometheus.CounterOpts{
Namespace: "deep",
Subsystem: "db",
Name: "blocklist_tenant_index_errors_total",
Help: "Total number of times an error occurred while retrieving or building the tenant index.",
}, []string{"tenant"})
metricTenantIndexBuilder = promauto.NewGaugeVec(prometheus.GaugeOpts{
Namespace: "deep",
Subsystem: "db",
Name: "blocklist_tenant_index_builder",
Help: "A value of 1 indicates this instance of deepdb is building the tenant index.",
}, []string{"tenant"})
metricTenantIndexAgeSeconds = promauto.NewGaugeVec(prometheus.GaugeOpts{
Namespace: "deep",
Subsystem: "db",
Name: "blocklist_tenant_index_age_seconds",
Help: "Age in seconds of the last pulled tenant index.",
}, []string{"tenant"})
)
// Config is used to configure the poller
type PollerConfig struct {
PollConcurrency uint
PollFallback bool
TenantIndexBuilders int
StaleTenantIndex time.Duration
PollJitterMs int
}
// JobSharder is used to determine if a particular job is owned by this process
type JobSharder interface {
// Owns is used to ask if a job, identified by a string, is owned by this process
Owns(string) bool
}
// OwnsNothingSharder owns nothing. You do not want this developer on your team.
var OwnsNothingSharder = ownsNothingSharder{}
type ownsNothingSharder struct{}
func (ownsNothingSharder) Owns(_ string) bool {
return false
}
const jobPrefix = "build-tenant-index-"
// Poller retrieves the blocklist
type Poller struct {
reader backend.Reader
writer backend.Writer
compactor backend.Compactor
cfg *PollerConfig
sharder JobSharder
logger log.Logger
}
// NewPoller creates the Poller
func NewPoller(cfg *PollerConfig, sharder JobSharder, reader backend.Reader, compactor backend.Compactor, writer backend.Writer, logger log.Logger) *Poller {
return &Poller{
reader: reader,
compactor: compactor,
writer: writer,
cfg: cfg,
sharder: sharder,
logger: logger,
}
}
// Do does the doing of getting a blocklist
func (p *Poller) Do() (PerTenant, PerTenantCompacted, error) {
start := time.Now()
defer func() { metricBlocklistPollDuration.Observe(time.Since(start).Seconds()) }()
ctx := context.Background()
tenants, err := p.reader.Tenants(ctx)
if err != nil {
metricBlocklistErrors.WithLabelValues("").Inc()
return nil, nil, err
}
blocklist := PerTenant{}
compactedBlocklist := PerTenantCompacted{}
for _, tenantID := range tenants {
newBlockList, newCompactedBlockList, err := p.pollTenantAndCreateIndex(ctx, tenantID)
if err != nil {
return nil, nil, err
}
metricBlocklistLength.WithLabelValues(tenantID).Set(float64(len(newBlockList)))
blocklist[tenantID] = newBlockList
compactedBlocklist[tenantID] = newCompactedBlockList
backendMetaMetrics := sumTotalBackendMetaMetrics(newBlockList, newCompactedBlockList)
metricBackendObjects.WithLabelValues(tenantID, blockStatusLiveLabel).Set(float64(backendMetaMetrics.blockMetaTotalObjects))
metricBackendObjects.WithLabelValues(tenantID, blockStatusCompactedLabel).Set(float64(backendMetaMetrics.compactedBlockMetaTotalObjects))
metricBackendBytes.WithLabelValues(tenantID, blockStatusLiveLabel).Set(float64(backendMetaMetrics.blockMetaTotalBytes))
metricBackendBytes.WithLabelValues(tenantID, blockStatusCompactedLabel).Set(float64(backendMetaMetrics.compactedBlockMetaTotalBytes))
}
return blocklist, compactedBlocklist, nil
}
func (p *Poller) pollTenantAndCreateIndex(ctx context.Context, tenantID string) ([]*backend.BlockMeta, []*backend.CompactedBlockMeta, error) {
span, derivedCtx := opentracing.StartSpanFromContext(ctx, "poll tenant index")
span.SetTag("tenantID", tenantID)
defer span.Finish()
// are we a tenant index builder?
if !p.buildTenantIndex(tenantID) {
metricTenantIndexBuilder.WithLabelValues(tenantID).Set(0)
i, err := p.reader.TenantIndex(derivedCtx, tenantID)
err = p.tenantIndexPollError(i, err)
if err == nil {
// success! return the retrieved index
metricTenantIndexAgeSeconds.WithLabelValues(tenantID).Set(float64(time.Since(i.CreatedAt) / time.Second))
level.Info(p.logger).Log("msg", "successfully pulled tenant index", "tenant", tenantID, "createdAt", i.CreatedAt, "metas", len(i.Meta), "compactedMetas", len(i.CompactedMeta))
return i.Meta, i.CompactedMeta, nil
}
metricTenantIndexErrors.WithLabelValues(tenantID).Inc()
// there was an error, return the error if we're not supposed to fallback to polling
if !p.cfg.PollFallback {
return nil, nil, err
}
// polling fallback is true, log the error and continue in this method to completely poll the backend
level.Error(p.logger).Log("msg", "failed to pull bucket index for tenant. falling back to polling", "tenant", tenantID, "err", err)
}
// if we're here then we have been configured to be a tenant index builder OR there was a failure to pull
// the tenant index and we are configured to fall back to polling
metricTenantIndexBuilder.WithLabelValues(tenantID).Set(1)
blocklist, compactedBlocklist, err := p.pollTenantBlocks(derivedCtx, tenantID)
if err != nil {
return nil, nil, err
}
// everything is happy, write this tenant index
level.Info(p.logger).Log("msg", "writing tenant index", "tenant", tenantID, "metas", len(blocklist), "compactedMetas", len(compactedBlocklist))
err = p.writer.WriteTenantIndex(derivedCtx, tenantID, blocklist, compactedBlocklist)
if err != nil {
metricTenantIndexErrors.WithLabelValues(tenantID).Inc()
level.Error(p.logger).Log("msg", "failed to write tenant index", "tenant", tenantID, "err", err)
}
metricTenantIndexAgeSeconds.WithLabelValues(tenantID).Set(0)
return blocklist, compactedBlocklist, nil
}
func (p *Poller) pollTenantBlocks(ctx context.Context, tenantID string) ([]*backend.BlockMeta, []*backend.CompactedBlockMeta, error) {
blockIDs, err := p.reader.Blocks(ctx, tenantID)
if err != nil {
metricBlocklistErrors.WithLabelValues(tenantID).Inc()
return []*backend.BlockMeta{}, []*backend.CompactedBlockMeta{}, err
}
bg := boundedwaitgroup.New(p.cfg.PollConcurrency)
chMeta := make(chan *backend.BlockMeta, len(blockIDs))
chCompactedMeta := make(chan *backend.CompactedBlockMeta, len(blockIDs))
anyError := atomic.Error{}
for _, blockID := range blockIDs {
bg.Add(1)
go func(uuid uuid.UUID) {
defer bg.Done()
if p.cfg.PollJitterMs > 0 {
time.Sleep(time.Duration(rand.Intn(p.cfg.PollJitterMs)) * time.Millisecond)
}
m, cm, err := p.pollBlock(ctx, tenantID, uuid)
if m != nil {
chMeta <- m
} else if cm != nil {
chCompactedMeta <- cm
} else if err != nil {
anyError.Store(err)
}
}(blockID)
}
bg.Wait()
close(chMeta)
close(chCompactedMeta)
if err = anyError.Load(); err != nil {
metricTenantIndexErrors.WithLabelValues(tenantID).Inc()
return nil, nil, err
}
newBlockList := make([]*backend.BlockMeta, 0, len(blockIDs))
for m := range chMeta {
newBlockList = append(newBlockList, m)
}
sort.Slice(newBlockList, func(i, j int) bool {
return newBlockList[i].StartTime.Before(newBlockList[j].StartTime)
})
newCompactedBlocklist := make([]*backend.CompactedBlockMeta, 0, len(blockIDs))
for cm := range chCompactedMeta {
newCompactedBlocklist = append(newCompactedBlocklist, cm)
}
sort.Slice(newCompactedBlocklist, func(i, j int) bool {
return newCompactedBlocklist[i].StartTime.Before(newCompactedBlocklist[j].StartTime)
})
return newBlockList, newCompactedBlocklist, nil
}
func (p *Poller) pollBlock(ctx context.Context, tenantID string, blockID uuid.UUID) (*backend.BlockMeta, *backend.CompactedBlockMeta, error) {
var compactedBlockMeta *backend.CompactedBlockMeta
blockMeta, err := p.reader.BlockMeta(ctx, blockID, tenantID)
// if the normal meta doesn't exist maybe it's compacted.
if err == backend.ErrDoesNotExist {
blockMeta = nil
compactedBlockMeta, err = p.compactor.CompactedBlockMeta(blockID, tenantID)
}
// blocks in intermediate states may not have a compacted or normal block meta.
// this is not necessarily an error, just bail out
if err == backend.ErrDoesNotExist {
return nil, nil, nil
}
if err != nil {
return nil, nil, err
}
return blockMeta, compactedBlockMeta, nil
}
func (p *Poller) buildTenantIndex(tenant string) bool {
for i := 0; i < p.cfg.TenantIndexBuilders; i++ {
job := jobPrefix + strconv.Itoa(i) + "-" + tenant
if p.sharder.Owns(job) {
return true
}
}
return false
}
func (p *Poller) tenantIndexPollError(idx *backend.TenantIndex, err error) error {
if err != nil {
return err
}
if p.cfg.StaleTenantIndex != 0 && time.Since(idx.CreatedAt) > p.cfg.StaleTenantIndex {
return fmt.Errorf("tenant index created at %s is stale", idx.CreatedAt)
}
return nil
}
type backendMetaMetrics struct {
blockMetaTotalObjects int
compactedBlockMetaTotalObjects int
blockMetaTotalBytes uint64
compactedBlockMetaTotalBytes uint64
}
func sumTotalBackendMetaMetrics(blockMeta []*backend.BlockMeta, compactedBlockMeta []*backend.CompactedBlockMeta) backendMetaMetrics {
var sumTotalObjectsBM int
var sumTotalObjectsCBM int
var sumTotalBytesBM uint64
var sumTotalBytesCBM uint64
for _, bm := range blockMeta {
sumTotalObjectsBM += bm.TotalObjects
sumTotalBytesBM += bm.Size
}
for _, cbm := range compactedBlockMeta {
sumTotalObjectsCBM += cbm.TotalObjects
sumTotalBytesCBM += cbm.Size
}
return backendMetaMetrics{
blockMetaTotalObjects: sumTotalObjectsBM,
compactedBlockMetaTotalObjects: sumTotalObjectsCBM,
blockMetaTotalBytes: sumTotalBytesBM,
compactedBlockMetaTotalBytes: sumTotalBytesCBM,
}
}