This repository has been archived by the owner on Aug 23, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 106
/
meta_record_idx.go
513 lines (435 loc) · 15.7 KB
/
meta_record_idx.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
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
package bigtable
import (
"bytes"
"context"
"encoding/binary"
"fmt"
"strconv"
"strings"
"sync"
"time"
"cloud.google.com/go/bigtable"
btUtils "github.com/grafana/metrictank/bigtable"
"github.com/grafana/metrictank/expr/tagquery"
"github.com/grafana/metrictank/idx"
"github.com/grafana/metrictank/idx/metatags"
log "github.com/sirupsen/logrus"
)
var (
errIdxUpdatesDisabled = fmt.Errorf("BigTable index updates are disabled")
)
type MetaRecordIdx struct {
wg sync.WaitGroup
shutdown chan struct{}
cfg *Config
status metatags.MetaRecordStatusByOrg
memoryIdx idx.MetaRecordIdx
client *bigtable.Client
adminClient *bigtable.AdminClient
metaRecordTable *bigtable.Table
metaRecordBatchTable *bigtable.Table
}
func NewBigTableMetaRecordIdx(cfg *Config, memoryIdx idx.MetaRecordIdx) *MetaRecordIdx {
return &MetaRecordIdx{
shutdown: make(chan struct{}),
cfg: cfg,
status: metatags.NewMetaRecordStatusByOrg(),
memoryIdx: memoryIdx,
}
}
func (m *MetaRecordIdx) Init() error {
ctx := context.Background()
err := m.connect(ctx)
if err != nil {
return err
}
err = btUtils.EnsureTableExists(ctx, m.cfg.createCf, m.adminClient, "meta_records", map[string]bigtable.GCPolicy{
m.cfg.metaRecordCf: bigtable.MaxVersionsPolicy(1),
})
if err != nil {
return err
}
err = btUtils.EnsureTableExists(ctx, m.cfg.createCf, m.adminClient, "meta_record_batches", map[string]bigtable.GCPolicy{
m.cfg.metaRecordBatchCf: bigtable.MaxVersionsPolicy(1),
})
if err != nil {
return err
}
m.metaRecordBatchTable = m.client.Open(m.cfg.batchTableName)
m.metaRecordTable = m.client.Open(m.cfg.tableName)
return nil
}
func (m *MetaRecordIdx) connect(ctx context.Context) error {
var err error
m.client, err = bigtable.NewClient(ctx, m.cfg.gcpProject, m.cfg.bigtableInstance)
if err != nil {
log.Errorf("bt-meta-record-idx: failed to create bigtable client: %s", err)
return err
}
m.adminClient, err = bigtable.NewAdminClient(ctx, m.cfg.gcpProject, m.cfg.bigtableInstance)
if err != nil {
log.Errorf("bt-meta-record-idx: failed to create bigtable admin client: %s", err)
}
return err
}
func (m *MetaRecordIdx) Start() {
m.wg.Add(1)
go m.pollBigtable()
if m.cfg.updateRecords {
m.wg.Add(1)
go m.pruneMetaRecords()
}
}
func (m *MetaRecordIdx) Stop() {
close(m.shutdown)
m.wg.Wait()
m.client.Close()
m.adminClient.Close()
}
func (m *MetaRecordIdx) pollBigtable() {
defer m.wg.Done()
ticker := time.NewTicker(m.cfg.pollInterval)
for {
select {
case <-m.shutdown:
ticker.Stop()
return
case <-ticker.C:
m.loadMetaRecords()
}
}
}
func (m *MetaRecordIdx) loadMetaRecords() {
batches, err := m.readMetaRecordBatches()
if err != nil {
log.Errorf("bt-meta-record-idx: Failed to load meta records from idx: %s", err)
return
}
toLoad := make(map[uint32]metatags.UUID)
for batchId, properties := range batches {
load, batchId := m.status.Update(properties.orgId, batchId, uint64(properties.createdAt), uint64(properties.lastUpdate))
if load {
toLoad[properties.orgId] = batchId
}
}
for orgId, batchId := range toLoad {
log.Infof("bt-meta-record-idx: Loading meta record batch %s of org %d", batchId.String(), orgId)
records, err := m.readMetaRecordsOfBatch(orgId, batchId)
if err != nil {
log.Errorf("bt-meta-record-idx: Failed to read meta records of batch (%d/%s): %s", orgId, batchId.String(), err)
continue
}
err = m.memoryIdx.MetaTagRecordSwap(orgId, records)
if err != nil {
log.Errorf("bt-meta-record-idx: Error when trying to swap batch of meta records in memory index (%d/%s): %s", orgId, batchId.String(), err)
continue
}
}
}
func (m *MetaRecordIdx) pruneMetaRecords() {
defer m.wg.Done()
ticker := time.NewTicker(m.cfg.pruneInterval)
for {
select {
case <-m.shutdown:
ticker.Stop()
return
case <-ticker.C:
log.Infof("bt-meta-record-idx: Pruning meta record tables")
batches, err := m.readMetaRecordBatches()
if err != nil {
log.Errorf("bt-meta-record-idx: Skipping pruning because couldn't load meta record batches: %s", err)
continue
}
for batchId, properties := range batches {
now := time.Now().Unix()
if uint64(now)-uint64(m.cfg.pruneAge.Seconds()) <= uint64(properties.createdAt/1000) {
continue
}
log.Infof("bt-meta-record-idx: Pruning meta record batch %d/%s", properties.orgId, batchId.String())
currentBatchId, _, _ := m.status.GetStatus(properties.orgId)
if batchId != currentBatchId {
err := m.pruneBatch(properties.orgId, batchId)
if err != nil {
log.Errorf("bt-meta-record-idx: Error when pruning batch %d/%s: %s", properties.orgId, batchId.String(), err)
}
}
}
}
}
}
type metaRecordBatches map[metatags.UUID]metaRecordBatchProperties
type metaRecordBatchProperties struct {
orgId uint32
createdAt int64
lastUpdate int64
}
func (m *MetaRecordIdx) readMetaRecordBatches() (metaRecordBatches, error) {
res := make(metaRecordBatches)
ctx := context.Background()
err := m.metaRecordBatchTable.ReadRows(ctx, bigtable.InfiniteRange(""), func(row bigtable.Row) bool {
var uuid metatags.UUID
var err error
var properties metaRecordBatchProperties
properties.orgId, uuid, err = decodeMetaRecordBatchRowKey(row.Key())
if err != nil {
log.Errorf("bt-meta-record-idx: Failed to decode meta record batch row key %q: %s", row.Key(), err)
return false
}
columns, ok := row[m.cfg.metaRecordBatchCf]
if !ok {
log.Errorf("bt-meta-record-idx: Row from meta record batch table was missing expected column family %s", m.cfg.metaRecordBatchCf)
return false
}
for _, col := range columns {
switch strings.SplitN(col.Column, ":", 2)[1] {
case "lastupdate":
properties.lastUpdate, err = binary.ReadVarint(bytes.NewReader(col.Value))
if err != nil {
log.Errorf("bt-meta-record-idx: Row from meta record batch table contained invalid lastupdate value %x: %s", col.Value, err)
return false
}
case "createdat":
properties.createdAt, err = binary.ReadVarint(bytes.NewReader(col.Value))
if err != nil {
log.Errorf("bt-meta-record-idx: Row from meta record batch table contained invalid createdat value %x: %s", col.Value, err)
return false
}
}
}
res[uuid] = properties
return true
}, bigtable.RowFilter(bigtable.ChainFilters(bigtable.FamilyFilter(m.cfg.metaRecordBatchCf), bigtable.LatestNFilter(1))))
if err != nil {
log.Errorf("bt-meta-record-idx: Failed to load meta record batches: %s", err)
return nil, err
}
return res, nil
}
func (m *MetaRecordIdx) readMetaRecordsOfBatch(orgId uint32, batchId metatags.UUID) ([]tagquery.MetaTagRecord, error) {
var res []tagquery.MetaTagRecord
ctx := context.Background()
err := m.metaRecordTable.ReadRows(ctx, bigtable.PrefixRange(formatMetaRecordRowKey(orgId, batchId, "")), func(row bigtable.Row) bool {
var record tagquery.MetaTagRecord
var err error
_, _, record.Expressions, err = decodeMetaRecordRowKey(row.Key())
if err != nil {
log.Errorf("bt-meta-record-idx: Failed to decode meta record row key %q: %s", row.Key(), err)
return false
}
columns, ok := row[m.cfg.metaRecordCf]
if !ok {
log.Errorf("bt-meta-record-idx: Row from meta record table was missing expected column family %s", m.cfg.metaRecordCf)
return false
}
for _, col := range columns {
switch strings.SplitN(col.Column, ":", 2)[1] {
case "metatags":
err = record.MetaTags.UnmarshalJSON([]byte(col.Value))
if err != nil {
log.Errorf("bt-meta-record-idx: Row from meta record table contained invalid metatags value %q: %s", col.Value, err)
return false
}
}
}
res = append(res, record)
return true
}, bigtable.RowFilter(bigtable.ChainFilters(bigtable.FamilyFilter(m.cfg.metaRecordCf), bigtable.LatestNFilter(1))))
if err != nil {
log.Errorf("bt-meta-record-idx: Failed to load meta records of batch (%d/%s):%s", orgId, batchId.String(), err)
return nil, err
}
return res, nil
}
func (m *MetaRecordIdx) pruneBatch(orgId uint32, batchId metatags.UUID) error {
// unfortunately dropping a row range requires using the admin client
err := m.adminClient.DropRowRange(context.Background(), m.cfg.tableName, formatMetaRecordRowKey(orgId, batchId, ""))
if err != nil {
log.Errorf("bt-meta-record-idx: Failed to drop row range by prefix %s: %s", formatMetaRecordRowKey(orgId, batchId, ""), err)
}
mut := bigtable.NewMutation()
mut.DeleteRow()
err = m.metaRecordBatchTable.Apply(context.Background(), formatMetaRecordBatchRowKey(orgId, batchId), mut)
if err != nil {
log.Errorf("bt-meta-record-idx: Failed to delete meta record batch (%d/%s): %s", orgId, batchId.String(), err)
}
return err
}
func (m *MetaRecordIdx) MetaTagRecordUpsert(orgId uint32, record tagquery.MetaTagRecord) error {
if !m.cfg.updateRecords {
return errIdxUpdatesDisabled
}
batchId, _, _ := m.status.GetStatus(orgId)
// if a record has no meta tags associated with it, then we delete it
var err error
if len(record.MetaTags) > 0 {
err = m.persistMetaRecord(orgId, batchId, record)
} else {
err = m.deleteMetaRecord(orgId, batchId, record)
}
if err != nil {
log.Errorf("bt-meta-record-idx: Failed to update meta records in bigtable: %s", err)
return fmt.Errorf("Failed to update bigtable: %s", err)
}
err = m.markMetaRecordBatchUpdated(orgId, batchId)
if err != nil {
log.Errorf("bt-meta-record-idx: Failed to update meta records in bigtable: %s", err)
return fmt.Errorf("Failed to update bigtable: %s", err)
}
return nil
}
func formatMetaRecordBatchRowKey(orgId uint32, batchId metatags.UUID) string {
return strconv.Itoa(int(orgId)) + "_" + batchId.String()
}
func decodeMetaRecordBatchRowKey(key string) (uint32, metatags.UUID, error) {
var uuid metatags.UUID
parts := strings.SplitN(key, "_", 2)
if len(parts) < 2 {
return 0, uuid, fmt.Errorf("Invalid row key format: %q", key)
}
orgId, err := strconv.Atoi(parts[0])
if err != nil {
return 0, uuid, fmt.Errorf("Invalid org id %q in row key: %q", parts[0], key)
}
uuid, err = metatags.ParseUUID(parts[1])
if err != nil {
return 0, uuid, fmt.Errorf("Failed to parse uuid %q in row key %q: %s", uuid, key, err)
}
return uint32(orgId), uuid, nil
}
func (m *MetaRecordIdx) markMetaRecordBatchUpdated(orgId uint32, batchId metatags.UUID) error {
now := make([]byte, 8)
binary.PutVarint(now, time.Now().UnixNano()/1000000)
mut := bigtable.NewMutation()
mut.Set(m.cfg.metaRecordBatchCf, "lastupdate", bigtable.Now(), now)
if batchId == metatags.DefaultBatchId {
// if the current batch id is the default batch id, then this batch has most likely not
// been persisted yet and we're going to persist it for the first time now. since this
// is the default batch which always exists, we set "createdat" to 0.
mut.Set(m.cfg.metaRecordBatchCf, "createdat", bigtable.Now(), make([]byte, 8))
}
err := m.metaRecordBatchTable.Apply(context.Background(), formatMetaRecordBatchRowKey(orgId, batchId), mut)
if err != nil {
log.Errorf("bt-meta-record-idx: Failed to mark meta record batch (%d/%s) as updated: %s", orgId, batchId.String(), err)
}
return err
}
func (m *MetaRecordIdx) MetaTagRecordSwap(orgId uint32, records []tagquery.MetaTagRecord) error {
if !m.cfg.updateRecords {
return errIdxUpdatesDisabled
}
newBatchId, err := metatags.RandomUUID()
if err != nil {
return fmt.Errorf("Failed to generate new batch id")
}
var expressions, metaTags []byte
rowKeys := make([]string, len(records))
muts := make([]*bigtable.Mutation, len(records))
for i, record := range records {
record.Expressions.Sort()
expressions, err = record.Expressions.MarshalJSON()
if err != nil {
return fmt.Errorf("Failed to marshal expressions: %s", err)
}
record.MetaTags.Sort()
metaTags, err = record.MetaTags.MarshalJSON()
if err != nil {
return fmt.Errorf("Failed to marshal meta tags: %s", err)
}
rowKeys[i] = formatMetaRecordRowKey(orgId, newBatchId, string(expressions))
muts[i] = bigtable.NewMutation()
muts[i].Set(m.cfg.metaRecordCf, "metatags", bigtable.Now(), metaTags)
}
select {
case <-m.shutdown:
return fmt.Errorf("meta-record-idx: Shutting down")
default:
}
errs, err := m.metaRecordTable.ApplyBulk(context.Background(), rowKeys, muts)
if err != nil {
log.Errorf("bt-meta-record-idx: Failed to apply meta records in bulk: %s", err)
return err
} else if len(errs) > 0 {
for _, err = range errs {
if err != nil {
log.Errorf("bt-meta-record-idx: One or multiple errors when storing %d records, first error: %s", len(rowKeys), err)
return err
}
}
}
select {
case <-m.shutdown:
return fmt.Errorf("meta-record-idx: Shutting down")
default:
}
return m.createNewBatch(orgId, newBatchId)
}
func (m *MetaRecordIdx) createNewBatch(orgId uint32, batchId metatags.UUID) error {
now := make([]byte, 8)
binary.PutVarint(now, time.Now().UnixNano()/1000000)
mut := bigtable.NewMutation()
mut.Set(m.cfg.metaRecordBatchCf, "lastupdate", bigtable.Now(), now)
mut.Set(m.cfg.metaRecordBatchCf, "createdat", bigtable.Now(), now)
rowKey := formatMetaRecordBatchRowKey(orgId, batchId)
err := m.metaRecordBatchTable.Apply(context.Background(), rowKey, mut)
if err != nil {
log.Errorf("bt-meta-record-idx: Failed to create new batch (%d/%s): %s", orgId, batchId.String(), err)
}
return err
}
func formatMetaRecordRowKey(orgId uint32, batchId metatags.UUID, expressions string) string {
return strconv.Itoa(int(orgId)) + "_" + batchId.String() + "_" + expressions
}
func decodeMetaRecordRowKey(key string) (uint32, metatags.UUID, tagquery.Expressions, error) {
parts := strings.SplitN(key, "_", 3)
if len(parts) < 3 {
return 0, metatags.UUID{}, tagquery.Expressions{}, fmt.Errorf("Invalid row key format: %q", key)
}
orgId, err := strconv.Atoi(parts[0])
if err != nil {
return 0, metatags.UUID{}, tagquery.Expressions{}, fmt.Errorf("Invalid org id in key %q: %q", key, parts[0])
}
uuid, err := metatags.ParseUUID(parts[1])
if err != nil {
return 0, metatags.UUID{}, tagquery.Expressions{}, fmt.Errorf("Failed to parse uuid %q in key %q: %s", parts[1], key, err)
}
var expressions tagquery.Expressions
err = expressions.UnmarshalJSON([]byte(parts[2]))
if err != nil {
return 0, metatags.UUID{}, expressions, fmt.Errorf("Failed to parse expressions string %q in key %q: %s", parts[2], key, err)
}
return uint32(orgId), uuid, expressions, nil
}
func (m *MetaRecordIdx) persistMetaRecord(orgId uint32, batchId metatags.UUID, record tagquery.MetaTagRecord) error {
expressions, err := record.Expressions.MarshalJSON()
if err != nil {
return fmt.Errorf("Failed to marshal expressions: %s", err)
}
metaTags, err := record.MetaTags.MarshalJSON()
if err != nil {
return fmt.Errorf("Failed to marshal meta tags: %s", err)
}
mut := bigtable.NewMutation()
mut.Set(m.cfg.metaRecordCf, "metatags", bigtable.Now(), metaTags)
err = m.metaRecordTable.Apply(context.Background(), formatMetaRecordRowKey(orgId, batchId, string(expressions)), mut)
if err != nil {
log.Errorf("bt-meta-record-idx: Failed to persist meta record (%d/%s/%s/%s): %s", orgId, batchId.String(), expressions, metaTags, err)
}
return err
}
func (m *MetaRecordIdx) deleteMetaRecord(orgId uint32, batchId metatags.UUID, record tagquery.MetaTagRecord) error {
expressions, err := record.Expressions.MarshalJSON()
if err != nil {
return fmt.Errorf("Failed to marshal record expressions: %s", err)
}
mut := bigtable.NewMutation()
mut.DeleteRow()
err = m.metaRecordTable.Apply(context.Background(), formatMetaRecordRowKey(orgId, batchId, string(expressions)), mut)
if err != nil {
log.Errorf("bt-meta-record-idx: Failed to delete meta record (%d/%s/%s): %s", orgId, batchId.String(), expressions, err)
}
return err
}
func (m *MetaRecordIdx) MetaTagRecordList(orgId uint32) []tagquery.MetaTagRecord {
return m.memoryIdx.MetaTagRecordList(orgId)
}