forked from cashapp/cloner
/
snapshotter.go
569 lines (507 loc) · 16 KB
/
snapshotter.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
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
package clone
import (
"context"
"database/sql"
"fmt"
_ "net/http/pprof"
"sort"
"github.com/cenkalti/backoff/v4"
"github.com/dlmiddlecote/sqlstats"
"github.com/mightyguava/autotx"
"github.com/pkg/errors"
"github.com/prometheus/client_golang/prometheus"
"github.com/sirupsen/logrus"
"golang.org/x/sync/errgroup"
"golang.org/x/sync/semaphore"
)
var (
snapshotChunkReconciles = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "snapshot_chunk_reconciles",
Help: "How many events we reconcile with ongoing chunks before writing during snapshotting.",
},
[]string{"table", "type"},
)
)
func init() {
prometheus.MustRegister(snapshotChunkReconciles)
}
// Snapshotter receives transactions and requests to snapshot and writes transactions and strongly consistent chunk snapshots
type Snapshotter struct {
config Replicate
source *sql.DB
sourceCollector *sqlstats.StatsCollector
sourceSchema string
sourceRetry RetryOptions
// chunks receives chunks from the chunker, they are processed on the main replication thread and appended to ongoingChunks below
chunks chan Chunk
// ongoingChunks holds the currently ongoing chunks, only access from the replication thread
ongoingChunks []*ChunkSnapshot
}
func NewSnapshotter(config Replicate) (*Snapshotter, error) {
var err error
s := Snapshotter{
config: config,
sourceRetry: RetryOptions{
Limiter: nil, // will we ever use concurrency limiter again? probably not?
AcquireMetric: readLimiterDelay.WithLabelValues("source"),
MaxRetries: config.ReadRetries,
Timeout: config.ReadTimeout,
},
chunks: make(chan Chunk, config.ChunkParallelism),
}
s.sourceSchema, err = s.config.Source.Schema()
if err != nil {
return nil, errors.WithStack(err)
}
source, err := s.config.Source.DB()
if err != nil {
return nil, errors.WithStack(err)
}
s.source = source
s.sourceCollector = sqlstats.NewStatsCollector("source", source)
return &s, nil
}
func (s *Snapshotter) Init(ctx context.Context) error {
err := s.source.PingContext(ctx)
if err != nil {
return errors.WithStack(err)
}
if s.config.CreateTables {
err = s.createWatermarkTable(ctx)
if err != nil {
return errors.WithStack(err)
}
}
return nil
}
func (s *Snapshotter) Run(ctx context.Context, b backoff.BackOff, source chan Transaction, sink chan Transaction) error {
prometheus.MustRegister(s.sourceCollector)
defer prometheus.Unregister(s.sourceCollector)
for {
err := s.maybeSnapshotChunks(ctx)
if err != nil {
return errors.WithStack(err)
}
var transaction Transaction
select {
case transaction = <-source:
case <-ctx.Done():
return ctx.Err()
}
// If we have chunks to process then we will process the watermarks in the transactions
if len(s.ongoingChunks) > 0 {
newMutations := make([]Mutation, 0, len(transaction.Mutations))
for _, mutation := range transaction.Mutations {
err := s.reconcileOngoingChunks(mutation)
if err != nil {
return errors.WithStack(err)
}
newMutations, err = s.handleWatermark(ctx, mutation, newMutations)
if err != nil {
return errors.WithStack(err)
}
}
transaction.Mutations = newMutations
}
select {
case sink <- transaction:
case <-ctx.Done():
return ctx.Err()
}
// We've committed a transaction, we can reset the backoff
b.Reset()
}
}
func (s *Snapshotter) createWatermarkTable(ctx context.Context) error {
// TODO retries with backoff?
timeoutCtx, cancel := context.WithTimeout(ctx, s.config.WriteTimeout)
defer cancel()
// TODO we should probably have a "task VARCHAR" column as well so we can run multiple snapshots from the same database
// TODO primary key here should probably be (task,table_name,chunk_seq)
stmt := fmt.Sprintf(`
CREATE TABLE IF NOT EXISTS %s (
id BIGINT(20) NOT NULL AUTO_INCREMENT,
task VARCHAR(255) NOT NULL,
table_name VARCHAR(255) NOT NULL,
chunk_seq BIGINT(20) NOT NULL,
low TINYINT DEFAULT 0,
high TINYINT DEFAULT 0,
PRIMARY KEY (id)
)
`, "`"+s.config.WatermarkTable+"`")
_, err := s.source.ExecContext(timeoutCtx, stmt)
if err != nil {
return errors.Wrapf(err, "could not create checkpoint table in target database:\n%s", stmt)
}
return nil
}
// ChunkSnapshot is a mutable struct for representing the current reconciliation state of a chunk, it is used single
// threaded by the replication thread only
type ChunkSnapshot struct {
InsideWatermarks bool
Rows []*Row
Chunk Chunk
}
func (c *ChunkSnapshot) findRow(row []interface{}) (*Row, int, error) {
n := len(c.Rows)
i := sort.Search(n, func(i int) bool {
return c.Rows[i].PkAfterOrEqual(row)
})
var candidate *Row
if n == i {
i = -1
} else {
candidate = c.Rows[i]
if !candidate.PkEqual(row) {
candidate = nil
}
}
return candidate, i, nil
}
func (c *ChunkSnapshot) updateRow(i int, row []interface{}) {
c.Rows[i] = c.Rows[i].Updated(row)
}
func (c *ChunkSnapshot) deleteRow(i int) {
c.Rows = append(c.Rows[:i], c.Rows[i+1:]...)
}
func (c *ChunkSnapshot) insertRow(i int, row []interface{}) {
r := &Row{
Table: c.Chunk.Table,
Data: row,
}
if i == -1 {
// We found no place to insert it so we append it
c.Rows = append(c.Rows, r)
} else {
c.Rows = append(c.Rows[:i], append([]*Row{r}, c.Rows[i:]...)...)
}
}
// reconcileOngoingChunks reconciles any ongoing chunks with the changes in the binlog event
func (s *Snapshotter) reconcileOngoingChunks(mutation Mutation) error {
// should be O(<rows in the RowsEvent> * lg <rows in the chunk>) given that we can binary chop into chunk
// RowsEvent is usually not that large so I don't think we need to index anything, that will probably be slower
for _, chunk := range s.ongoingChunks {
err := chunk.reconcileBinlogEvent(mutation)
if err != nil {
return errors.WithStack(err)
}
}
return nil
}
// reconcileBinlogEvent will apply the row
func (c *ChunkSnapshot) reconcileBinlogEvent(mutation Mutation) error {
tableSchema := mutation.Table.MysqlTable
if !c.InsideWatermarks {
return nil
}
if c.Chunk.Table.MysqlTable.Name != tableSchema.Name {
return nil
}
if c.Chunk.Table.MysqlTable.Schema != tableSchema.Schema {
return nil
}
if mutation.Type == Delete {
for _, row := range mutation.Rows {
if !c.Chunk.ContainsRow(row) {
// The row is outside of our range, we can skip it
continue
}
snapshotChunkReconciles.WithLabelValues(mutation.Table.Name, mutation.Type.String()).Inc()
// find the row using binary chop (the chunk rows are sorted)
existingRow, i, err := c.findRow(row)
if existingRow == nil {
// Row already deleted, this event probably happened after the low watermark but before the chunk read
} else {
if err != nil {
return errors.WithStack(err)
}
c.deleteRow(i)
}
}
} else {
for _, row := range mutation.Rows {
if !c.Chunk.ContainsRow(row) {
// The row is outside of our range, we can skip it
continue
}
snapshotChunkReconciles.WithLabelValues(mutation.Table.Name, mutation.Type.String()).Inc()
existingRow, i, err := c.findRow(row)
if err != nil {
return errors.WithStack(err)
}
if existingRow == nil {
// This is either an insert or an update of a row that is deleted after the low watermark but before
// the chunk read, either way we just insert it and if the delete event comes we take it away again
c.insertRow(i, row)
} else {
// We found a matching row, it must be an update
c.updateRow(i, row)
}
}
}
return nil
}
func (s *Snapshotter) findOngoingChunkFromWatermark(mutation Mutation) (*ChunkSnapshot, error) {
logger := logrus.WithField("task", "snapshotter")
tableSchema := mutation.Table.MysqlTable
tableNameI, err := tableSchema.GetColumnValue("table_name", mutation.Rows[0])
if err != nil {
return nil, errors.WithStack(err)
}
tableName := tableNameI.(string)
chunkSeqI, err := tableSchema.GetColumnValue("chunk_seq", mutation.Rows[0])
if err != nil {
return nil, errors.WithStack(err)
}
chunkSeq := chunkSeqI.(int64)
for _, chunk := range s.ongoingChunks {
if chunk.Chunk.Seq == chunkSeq && chunk.Chunk.Table.Name == tableName {
return chunk, nil
}
}
logger.Warnf("could not find chunk for watermark for table '%s', "+
"we may be receiving the watermark events before the chunk "+
"or this is a watermark left behind from an earlier failed snapshot "+
"attempt that crashed before it completed", tableName)
return nil, nil
}
func (s *Snapshotter) removeOngoingChunk(chunk *ChunkSnapshot) {
n := 0
for _, x := range s.ongoingChunks {
if x != chunk {
s.ongoingChunks[n] = x
n++
}
}
s.ongoingChunks = s.ongoingChunks[:n]
}
// snapshot runs a snapshot asynchronously unless a snapshot is already running
func (s *Snapshotter) snapshot(ctx context.Context) error {
go func() {
logger := logrus.WithContext(ctx).WithField("task", "chunking")
err := s.clearWatermarkTable(ctx)
if err != nil {
logger.WithError(err).Errorf("failed to clear watermark table ahead of snapshot: %v", err)
return
}
err = s.chunkTables(ctx)
if err != nil {
logger.WithError(err).Errorf("failed to chunk tables: %v", err)
}
}()
return nil
}
func (s *Snapshotter) handleWatermark(ctx context.Context, watermark Mutation, result []Mutation) ([]Mutation, error) {
if watermark.Table.Name != s.config.WatermarkTable {
// Nothing to do, we just add the mutation untouched and return
result = append(result, watermark)
return result, nil
}
if watermark.Type == Delete {
// Someone is probably just cleaning out the watermark table
// Watermark mutations aren't replicated so we don't bother adding it
return result, nil
}
if len(watermark.Rows) != 1 {
return result, errors.Errorf("more than a single row was written to the watermark table at the same time")
}
row := watermark.Rows[0]
task, err := watermark.Table.MysqlTable.GetColumnValue("task", row)
if err != nil {
return result, errors.WithStack(err)
}
if task != s.config.TaskName {
// This is not for us, we just add the mutation untouched and return
result = append(result, watermark)
return result, nil
}
low, err := watermark.Table.MysqlTable.GetColumnValue("low", row)
if err != nil {
return result, errors.WithStack(err)
}
high, err := watermark.Table.MysqlTable.GetColumnValue("high", row)
if err != nil {
return result, errors.WithStack(err)
}
if low.(int8) == 1 {
ongoingChunk, err := s.findOngoingChunkFromWatermark(watermark)
if err != nil {
return result, errors.WithStack(err)
}
if ongoingChunk == nil {
return result, nil
}
ongoingChunk.InsideWatermarks = true
}
if high.(int8) == 1 {
ongoingChunk, err := s.findOngoingChunkFromWatermark(watermark)
if err != nil {
return result, errors.WithStack(err)
}
if ongoingChunk == nil {
return result, nil
}
ongoingChunk.InsideWatermarks = false
rows := make([][]interface{}, len(ongoingChunk.Rows))
for i, row := range ongoingChunk.Rows {
rows[i] = row.Data
}
result = append(result, Mutation{
Type: Repair,
Table: ongoingChunk.Chunk.Table,
Rows: rows,
Chunk: ongoingChunk.Chunk,
})
s.removeOngoingChunk(ongoingChunk)
err = s.deleteWatermark(ctx, watermark)
if err != nil {
return nil, errors.WithStack(err)
}
}
return result, nil
}
func (s *Snapshotter) chunkTables(ctx context.Context) error {
tables, err := loadTables(ctx, s.config.ReaderConfig, s.config.Source, s.source)
if err != nil {
return errors.WithStack(err)
}
g, ctx := errgroup.WithContext(ctx)
tableParallelism := semaphore.NewWeighted(s.config.TableParallelism)
logger := logrus.WithContext(ctx).WithField("task", "chunking")
for _, t := range tables {
table := t
err = tableParallelism.Acquire(ctx, 1)
if err != nil {
return errors.WithStack(err)
}
g.Go(func() error {
defer tableParallelism.Release(1)
logger := logger.WithField("table", table.Name)
logger.Infof("'%s' chunking start", table.Name)
err := generateTableChunksAsync(ctx, table, s.source, s.chunks, s.sourceRetry)
logger.Infof("'%s' chunking done", table.Name)
if err != nil {
return errors.Wrapf(err, "failed to chunk: '%s'", table.Name)
}
return nil
})
}
err = g.Wait()
logger.Infof("all tables chunking done")
return errors.WithStack(err)
}
func (s *Snapshotter) snapshotChunk(ctx context.Context, chunk Chunk) (*ChunkSnapshot, error) {
// 1. insert the low watermark
// 2. read the entire chunk
// 3. insert the high watermark
_, err := s.source.ExecContext(ctx,
fmt.Sprintf("INSERT INTO %s (task, table_name, chunk_seq, low) VALUES (?, ?, ?, 1)",
s.config.WatermarkTable),
s.config.TaskName, chunk.Table.Name, chunk.Seq)
if err != nil {
return nil, errors.WithStack(err)
}
// TODO does not support snapshotting from a replica because it writes to the same source as it reads the chunk
// if we want to support snapshotting from a replica we need to do this:
// 1) write low watermark to master
// 2) observe binlogs out of replica
// 3) when we receive low watermark in replica -> read the chunk snapshot
// 4) write high watermark to master
stream, err := bufferChunk(ctx, s.sourceRetry, s.source, "source", chunk)
if err != nil {
return nil, errors.WithStack(err)
}
rows, err := readAll(stream)
if err != nil {
return nil, errors.WithStack(err)
}
snapshot := &ChunkSnapshot{Chunk: chunk, Rows: rows}
chunksSnapshotted.WithLabelValues(s.config.TaskName, chunk.Table.Name).Inc()
_, err = s.source.ExecContext(ctx,
fmt.Sprintf("INSERT INTO %s (task, table_name, chunk_seq, high) VALUES (?, ?, ?, 1)",
s.config.WatermarkTable),
s.config.TaskName, chunk.Table.Name, chunk.Seq)
if err != nil {
return nil, errors.WithStack(err)
}
return snapshot, nil
}
func (s *Snapshotter) maybeSnapshotChunks(ctx context.Context) error {
// We read new snapshots when we have finished processing all of the ongoing chunks
if len(s.ongoingChunks) > 0 {
return nil
}
// Grab as many chunks as is available
var chunks []Chunk
for i := 0; i < s.config.ChunkParallelism; i++ {
select {
case chunk := <-s.chunks:
chunks = append(chunks, chunk)
default:
if i == 0 {
// There are no chunks queued up, let's bail fast
return nil
}
}
}
if len(chunks) == 0 {
return nil
}
g, ctx := errgroup.WithContext(ctx)
snapshotCh := make(chan *ChunkSnapshot, s.config.ChunkParallelism)
for _, c := range chunks {
chunk := c
g.Go(func() error {
snapshot, err := s.snapshotChunk(ctx, chunk)
if err != nil {
return errors.WithStack(err)
}
snapshotCh <- snapshot
return nil
})
}
err := g.Wait()
if err != nil {
return errors.WithStack(err)
}
close(snapshotCh)
snapshots := make([]*ChunkSnapshot, 0, s.config.ChunkParallelism)
for snapshot := range snapshotCh {
snapshots = append(snapshots, snapshot)
}
s.ongoingChunks = snapshots
return nil
}
func (s *Snapshotter) clearWatermarkTable(ctx context.Context) error {
retry := s.sourceRetry
// wiping the watermark table might take quite a long time after a failed snapshot,
// let's use a much longer read timeout here
retry.Timeout = 10 * retry.Timeout
err := Retry(ctx, retry, func(ctx context.Context) error {
return errors.WithStack(autotx.Transact(ctx, s.source, func(tx *sql.Tx) error {
_, err := tx.ExecContext(ctx, fmt.Sprintf("DELETE FROM %s", s.config.WatermarkTable))
return errors.WithStack(err)
}))
})
return errors.WithStack(err)
}
func (s *Snapshotter) deleteWatermark(ctx context.Context, mutation Mutation) error {
tableSchema := mutation.Table.MysqlTable
tableNameI, err := tableSchema.GetColumnValue("table_name", mutation.Rows[0])
if err != nil {
return errors.WithStack(err)
}
tableName := tableNameI.(string)
chunkSeqI, err := tableSchema.GetColumnValue("chunk_seq", mutation.Rows[0])
if err != nil {
return errors.WithStack(err)
}
chunkSeq := chunkSeqI.(int64)
return Retry(ctx, s.sourceRetry, func(ctx context.Context) error {
_, err := s.source.ExecContext(ctx,
fmt.Sprintf("DELETE FROM %s WHERE task = ? AND table_name = ? AND chunk_seq = ?", s.config.WatermarkTable),
s.config.TaskName, tableName, chunkSeq)
return err
})
}