forked from cashapp/cloner
/
reader.go
193 lines (168 loc) · 4.38 KB
/
reader.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
package clone
import (
"context"
"database/sql"
"math/rand"
"github.com/pkg/errors"
"github.com/platinummonkey/go-concurrency-limits/core"
"github.com/prometheus/client_golang/prometheus"
log "github.com/sirupsen/logrus"
"golang.org/x/sync/errgroup"
"golang.org/x/sync/semaphore"
)
var (
tablesTotalMetric = prometheus.NewCounter(
prometheus.CounterOpts{
Name: "tables",
Help: "How many total tables to do.",
},
)
rowCountMetric = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "estimated_rows",
Help: "How many total tables to do.",
},
[]string{"table"},
)
tablesDoneMetric = prometheus.NewCounter(
prometheus.CounterOpts{
Name: "tables_done",
Help: "How many tables done.",
},
)
)
func init() {
prometheus.MustRegister(tablesTotalMetric)
prometheus.MustRegister(rowCountMetric)
prometheus.MustRegister(tablesDoneMetric)
}
type Reader struct {
config ReaderConfig
table *Table
source *sql.DB
target *sql.DB
sourceRetry RetryOptions
targetRetry RetryOptions
}
func (r *Reader) Diff(ctx context.Context, diffs chan Diff) error {
return errors.WithStack(r.read(ctx, diffs, true))
}
func (r *Reader) Read(ctx context.Context, diffs chan Diff) error {
// TODO this can be refactored to a separate method
return errors.WithStack(r.read(ctx, diffs, false))
}
func (r *Reader) read(ctx context.Context, diffsCh chan Diff, diff bool) error {
g, ctx := errgroup.WithContext(ctx)
chunkCh := make(chan Chunk)
// Generate chunks of source table
g.Go(func() error {
if r.config.ShuffleChunks {
chunks, err := generateTableChunks(ctx, r.table, r.source, r.sourceRetry)
if err != nil {
return errors.WithStack(err)
}
rand.Shuffle(len(chunks), func(i, j int) { chunks[i], chunks[j] = chunks[j], chunks[i] })
for _, chunk := range chunks {
select {
case chunkCh <- chunk:
case <-ctx.Done():
return ctx.Err()
}
}
} else {
err := generateTableChunksAsync(ctx, r.table, r.source, chunkCh, r.sourceRetry)
if err != nil {
return errors.WithStack(err)
}
}
close(chunkCh)
return nil
})
logger := log.WithContext(ctx).WithField("task", "reader")
logger = logger.WithField("table", r.table.Name)
// Generate diffs from all chunks
chunkCount := 0
rowCount := 0
readerParallelism := semaphore.NewWeighted(r.config.ReaderParallelism)
for c := range chunkCh {
chunk := c
chunkCount += 1
rowCount += c.Size
err := readerParallelism.Acquire(ctx, 1)
if err != nil {
return errors.WithStack(err)
}
g.Go(func() (err error) {
defer readerParallelism.Release(1)
return r.processChunk(ctx, diffsCh, diff, chunk)
})
}
err := g.Wait()
if err != nil {
return errors.WithStack(err)
}
logger.Infof("reads done: %s (chunks=%d rows=%d)", r.table.Name, chunkCount, rowCount)
return nil
}
func (r *Reader) processChunk(ctx context.Context, diffsCh chan Diff, diff bool, chunk Chunk) (err error) {
if chunk.First {
log.Infof("processing first chunk of a table, %s", chunk.String())
}
if chunk.Last {
log.Infof("processing last chunk of a table, %s", chunk.String())
}
var diffs []Diff
if diff {
diffs, err = r.diffChunk(ctx, chunk)
} else {
diffs, err = r.readChunk(ctx, chunk)
}
if err != nil {
log.WithField("table", chunk.Table.Name).
WithError(err).
WithContext(ctx).
Warnf("failed to read chunk %s[%v - %v] after retries and backoff, "+
"since this is a best effort clone we just give up: %+v",
chunk.Table.Name, chunk.Start, chunk.End, err)
return nil
}
if len(diffs) > 0 {
chunksWithDiffs.WithLabelValues(chunk.Table.Name).Inc()
}
chunksProcessed.WithLabelValues(chunk.Table.Name).Inc()
for _, diff := range diffs {
select {
case diffsCh <- diff:
case <-ctx.Done():
return ctx.Err()
}
}
return nil
}
func NewReader(
config ReaderConfig,
table *Table,
source *sql.DB,
sourceLimiter core.Limiter,
target *sql.DB,
targetLimiter core.Limiter,
) *Reader {
return &Reader{
config: config,
table: table,
source: source,
sourceRetry: RetryOptions{
Limiter: sourceLimiter,
AcquireMetric: readLimiterDelay.WithLabelValues("source"),
MaxRetries: config.ReadRetries,
Timeout: config.ReadTimeout,
},
target: target,
targetRetry: RetryOptions{
Limiter: targetLimiter,
AcquireMetric: readLimiterDelay.WithLabelValues("target"),
MaxRetries: config.ReadRetries,
Timeout: config.ReadTimeout,
},
}
}