forked from vitessio/vitess
-
Notifications
You must be signed in to change notification settings - Fork 0
/
split_diff.go
449 lines (393 loc) · 14.2 KB
/
split_diff.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
// Copyright 2013, Google Inc. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package worker
import (
"fmt"
"strings"
"sync"
"time"
log "github.com/golang/glog"
"github.com/youtube/vitess/go/sync2"
"github.com/youtube/vitess/go/vt/concurrency"
"github.com/youtube/vitess/go/vt/key"
myproto "github.com/youtube/vitess/go/vt/mysqlctl/proto"
"github.com/youtube/vitess/go/vt/topo"
"github.com/youtube/vitess/go/vt/wrangler"
)
const (
// all the states for the worker
stateSDNotSarted = "not started"
stateSDDone = "done"
stateSDError = "error"
stateSDInit = "initializing"
stateSDFindTargets = "finding target instances"
stateSDSynchronizeReplication = "synchronizing replication"
stateSDDiff = "running the diff"
stateSDCleanUp = "cleaning up"
)
// SplitDiffWorker executes a diff between a destination shard and its
// source shards in a shard split case.
type SplitDiffWorker struct {
wr *wrangler.Wrangler
cell string
keyspace string
shard string
cleaner *wrangler.Cleaner
// all subsequent fields are protected by the mutex
mu sync.Mutex
state string
// populated if state == stateSDError
err error
// populated during stateSDInit, read-only after that
keyspaceInfo *topo.KeyspaceInfo
shardInfo *topo.ShardInfo
// populated during stateSDFindTargets, read-only after that
sourceAliases []topo.TabletAlias
destinationAlias topo.TabletAlias
// populated during stateSDDiff
diffLogs []string
sourceSchemaDefinitions []*myproto.SchemaDefinition
destinationSchemaDefinition *myproto.SchemaDefinition
}
// NewSplitDiff returns a new SplitDiffWorker object.
func NewSplitDiffWorker(wr *wrangler.Wrangler, cell, keyspace, shard string) Worker {
return &SplitDiffWorker{
wr: wr,
cell: cell,
keyspace: keyspace,
shard: shard,
cleaner: &wrangler.Cleaner{},
state: stateSDNotSarted,
}
}
func (sdw *SplitDiffWorker) setState(state string) {
sdw.mu.Lock()
sdw.state = state
sdw.mu.Unlock()
}
func (sdw *SplitDiffWorker) recordError(err error) {
sdw.mu.Lock()
sdw.state = stateSDError
sdw.err = err
sdw.mu.Unlock()
}
func (sdw *SplitDiffWorker) StatusAsHTML() string {
sdw.mu.Lock()
defer sdw.mu.Unlock()
result := "<b>Working on:</b> " + sdw.keyspace + "/" + sdw.shard + "</br>\n"
result += "<b>State:</b> " + sdw.state + "</br>\n"
switch sdw.state {
case stateSDError:
result += "<b>Error</b>: " + sdw.err.Error() + "</br>\n"
case stateSDDiff:
result += "<b>Running</b>:</br>\n"
result += strings.Join(sdw.diffLogs, "</br>\n")
case stateSDDone:
result += "<b>Success</b>:</br>\n"
result += strings.Join(sdw.diffLogs, "</br>\n")
}
return result
}
func (sdw *SplitDiffWorker) StatusAsText() string {
sdw.mu.Lock()
defer sdw.mu.Unlock()
result := "Working on: " + sdw.keyspace + "/" + sdw.shard + "\n"
result += "State: " + sdw.state + "\n"
switch sdw.state {
case stateSDError:
result += "Error: " + sdw.err.Error() + "\n"
case stateSDDiff:
result += "Running:\n"
result += strings.Join(sdw.diffLogs, "\n")
case stateSDDone:
result += "Success:\n"
result += strings.Join(sdw.diffLogs, "\n")
}
return result
}
func (sdw *SplitDiffWorker) CheckInterrupted() bool {
select {
case <-interrupted:
sdw.recordError(topo.ErrInterrupted)
return true
default:
}
return false
}
// Run is mostly a wrapper to run the cleanup at the end.
func (sdw *SplitDiffWorker) Run() {
err := sdw.run()
sdw.setState(stateSDCleanUp)
cerr := sdw.cleaner.CleanUp(sdw.wr)
if cerr != nil {
if err != nil {
log.Errorf("CleanUp failed in addition to job error: %v", cerr)
} else {
err = cerr
}
}
if err != nil {
sdw.recordError(err)
return
}
sdw.setState(stateSDDone)
}
func (sdw *SplitDiffWorker) run() error {
// first state: read what we need to do
if err := sdw.init(); err != nil {
return err
}
if sdw.CheckInterrupted() {
return topo.ErrInterrupted
}
// second state: find targets
if err := sdw.findTargets(); err != nil {
return err
}
if sdw.CheckInterrupted() {
return topo.ErrInterrupted
}
// third phase: synchronize replication
if err := sdw.synchronizeReplication(); err != nil {
return err
}
if sdw.CheckInterrupted() {
return topo.ErrInterrupted
}
// fourth phase: diff
if err := sdw.diff(); err != nil {
return err
}
return nil
}
// init phase:
// - read the shard info, make sure it has sources
func (sdw *SplitDiffWorker) init() error {
sdw.setState(stateSDInit)
var err error
sdw.keyspaceInfo, err = sdw.wr.TopoServer().GetKeyspace(sdw.keyspace)
if err != nil {
return fmt.Errorf("Cannot read keyspace %v: %v", sdw.keyspace, err)
}
sdw.shardInfo, err = sdw.wr.TopoServer().GetShard(sdw.keyspace, sdw.shard)
if err != nil {
return fmt.Errorf("Cannot read shard %v/%v: %v", sdw.keyspace, sdw.shard, err)
}
if len(sdw.shardInfo.SourceShards) == 0 {
return fmt.Errorf("Shard %v/%v has no source shard", sdw.keyspace, sdw.shard)
}
if sdw.shardInfo.MasterAlias.IsZero() {
return fmt.Errorf("Shard %v/%v has no master", sdw.keyspace, sdw.shard)
}
return nil
}
// findTargets phase:
// - find one rdonly per source shard
// - find one rdonly in destination shard
// - mark them all as 'checker' pointing back to us
func (sdw *SplitDiffWorker) findTargets() error {
sdw.setState(stateSDFindTargets)
// find an appropriate endpoint in destination shard
var err error
sdw.destinationAlias, err = findChecker(sdw.wr, sdw.cleaner, sdw.cell, sdw.keyspace, sdw.shard)
if err != nil {
return err
}
// find an appropriate endpoint in the source shards
sdw.sourceAliases = make([]topo.TabletAlias, len(sdw.shardInfo.SourceShards))
for i, ss := range sdw.shardInfo.SourceShards {
sdw.sourceAliases[i], err = findChecker(sdw.wr, sdw.cleaner, sdw.cell, sdw.keyspace, ss.Shard)
if err != nil {
return err
}
}
return nil
}
// synchronizeReplication phase:
// 1 - ask the master of the destination shard to pause filtered replication,
// and return the source binlog positions
// (add a cleanup task to restart filtered replication on master)
// 2 - stop all the source 'checker' at a binlog position higher than the
// destination master. Get that new list of positions.
// (add a cleanup task to restart binlog replication on them, and change
// the existing ChangeSlaveType cleanup action to 'spare' type)
// 3 - ask the master of the destination shard to resume filtered replication
// up to the new list of positions, and return its binlog position.
// 4 - wait until the destination checker is equal or passed that master binlog
// position, and stop its replication.
// (add a cleanup task to restart binlog replication on it, and change
// the existing ChangeSlaveType cleanup action to 'spare' type)
// 5 - restart filtered replication on destination master.
// (remove the cleanup task that does the same)
// At this point, all checker instances are stopped at the same point.
func (sdw *SplitDiffWorker) synchronizeReplication() error {
sdw.setState(stateSDSynchronizeReplication)
// 1 - stop the master binlog replication, get its current position
log.Infof("Stopping master binlog replication on %v", sdw.shardInfo.MasterAlias)
blpPositionList, err := sdw.wr.ActionInitiator().StopBlp(sdw.shardInfo.MasterAlias, 30*time.Second)
if err != nil {
return err
}
wrangler.RecordStartBlpAction(sdw.cleaner, sdw.shardInfo.MasterAlias, 30*time.Second)
// 2 - stop all the source 'checker' at a binlog position
// higher than the destination master
stopPositionList := myproto.BlpPositionList{
Entries: make([]myproto.BlpPosition, len(sdw.shardInfo.SourceShards)),
}
for i, ss := range sdw.shardInfo.SourceShards {
// find where we should be stopping
pos, err := blpPositionList.FindBlpPositionById(ss.Uid)
if err != nil {
return fmt.Errorf("No binlog position on the master for Uid %v", ss.Uid)
}
// stop replication
log.Infof("Stopping slave[%v] %v at a minimum of %v", i, sdw.sourceAliases[i], pos.GroupId)
stoppedAt, err := sdw.wr.ActionInitiator().StopSlaveMinimum(sdw.sourceAliases[i], pos.GroupId, 30*time.Second)
if err != nil {
return fmt.Errorf("Cannot stop slave %v at right binlog position %v: %v", sdw.sourceAliases[i], pos.GroupId, err)
}
stopPositionList.Entries[i].Uid = ss.Uid
stopPositionList.Entries[i].GroupId = stoppedAt.MasterLogGroupId
// change the cleaner actions from ChangeSlaveType(rdonly)
// to StartSlave() + ChangeSlaveType(spare)
wrangler.RecordStartSlaveAction(sdw.cleaner, sdw.sourceAliases[i], 30*time.Second)
action, err := wrangler.FindChangeSlaveTypeActionByTarget(sdw.cleaner, sdw.sourceAliases[i])
if err != nil {
return fmt.Errorf("cannot find ChangeSlaveType action for %v: %v", sdw.sourceAliases[i], err)
}
action.TabletType = topo.TYPE_SPARE
}
// 3 - ask the master of the destination shard to resume filtered
// replication up to the new list of positions
log.Infof("Restarting master %v until it catches up to %v", sdw.shardInfo.MasterAlias, stopPositionList)
masterPos, err := sdw.wr.ActionInitiator().RunBlpUntil(sdw.shardInfo.MasterAlias, &stopPositionList, 30*time.Second)
if err != nil {
return err
}
// 4 - wait until the destination checker is equal or passed
// that master binlog position, and stop its replication.
log.Infof("Waiting for destination checker %v to catch up to %v", sdw.destinationAlias, masterPos.MasterLogGroupId)
_, err = sdw.wr.ActionInitiator().StopSlaveMinimum(sdw.destinationAlias, masterPos.MasterLogGroupId, 30*time.Second)
if err != nil {
return err
}
wrangler.RecordStartSlaveAction(sdw.cleaner, sdw.destinationAlias, 30*time.Second)
action, err := wrangler.FindChangeSlaveTypeActionByTarget(sdw.cleaner, sdw.destinationAlias)
if err != nil {
return fmt.Errorf("cannot find ChangeSlaveType action for %v: %v", sdw.destinationAlias, err)
}
action.TabletType = topo.TYPE_SPARE
// 5 - restart filtered replication on destination master
log.Infof("Restarting filtered replication on master %v", sdw.shardInfo.MasterAlias)
err = sdw.wr.ActionInitiator().StartBlp(sdw.shardInfo.MasterAlias, 30*time.Second)
if err := sdw.cleaner.RemoveActionByName(wrangler.StartBlpActionName, sdw.shardInfo.MasterAlias.String()); err != nil {
log.Warningf("Cannot find cleaning action %v/%v: %v", wrangler.StartBlpActionName, sdw.shardInfo.MasterAlias.String(), err)
}
if err != nil {
return err
}
return nil
}
// diff phase: will create a list of messages regarding the diff.
// - get the schema on all checkers
// - if some table schema mismatches, record them (use existing schema diff tools).
// - for each table in destination, run a diff pipeline.
func (sdw *SplitDiffWorker) diffLog(msg string) {
sdw.mu.Lock()
sdw.diffLogs = append(sdw.diffLogs, msg)
sdw.mu.Unlock()
log.Infof("diffLog: %v", msg)
}
func (sdw *SplitDiffWorker) diff() error {
sdw.setState(stateSDDiff)
sdw.diffLog("Gathering schema information...")
sdw.sourceSchemaDefinitions = make([]*myproto.SchemaDefinition, len(sdw.sourceAliases))
wg := sync.WaitGroup{}
rec := concurrency.AllErrorRecorder{}
wg.Add(1)
go func() {
var err error
sdw.destinationSchemaDefinition, err = sdw.wr.GetSchema(sdw.destinationAlias, nil, false)
rec.RecordError(err)
sdw.diffLog(fmt.Sprintf("Got schema from destination %v", sdw.destinationAlias))
wg.Done()
}()
for i, sourceAlias := range sdw.sourceAliases {
wg.Add(1)
go func(i int, sourceAlias topo.TabletAlias) {
var err error
sdw.sourceSchemaDefinitions[i], err = sdw.wr.GetSchema(sourceAlias, nil, false)
rec.RecordError(err)
sdw.diffLog(fmt.Sprintf("Got schema from source[%v] %v", i, sourceAlias))
wg.Done()
}(i, sourceAlias)
}
wg.Wait()
if rec.HasErrors() {
return rec.Error()
}
// TODO(alainjobart) Checking against each source may be
// overkill, if all sources have the same schema?
sdw.diffLog("Diffing the schema...")
rec = concurrency.AllErrorRecorder{}
for i, sourceSchemaDefinition := range sdw.sourceSchemaDefinitions {
sourceName := fmt.Sprintf("source[%v]", i)
myproto.DiffSchema("destination", sdw.destinationSchemaDefinition, sourceName, sourceSchemaDefinition, &rec)
}
if rec.HasErrors() {
sdw.diffLog("Different schemas: " + rec.Error().Error())
} else {
sdw.diffLog("Schema match, good.")
}
// run the diffs, 8 at a time
sdw.diffLog("Running the diffs...")
sem := sync2.NewSemaphore(8, 0)
for _, tableDefinition := range sdw.destinationSchemaDefinition.TableDefinitions {
wg.Add(1)
go func(tableDefinition myproto.TableDefinition) {
defer wg.Done()
sem.Acquire()
defer sem.Release()
log.Infof("Starting the diff on table %v", tableDefinition.Name)
if len(sdw.sourceAliases) != 1 {
sdw.diffLog("Don't support more than one source for table yet: " + tableDefinition.Name)
return
}
overlap, err := key.KeyRangesOverlap(sdw.shardInfo.KeyRange, sdw.shardInfo.SourceShards[0].KeyRange)
if err != nil {
sdw.diffLog("Source shard doesn't overlap with destination????: " + err.Error())
return
}
sourceQueryResultReader, err := TableScanByKeyRange(sdw.wr.TopoServer(), sdw.sourceAliases[0], &tableDefinition, overlap, sdw.keyspaceInfo.ShardingColumnType)
if err != nil {
sdw.diffLog("TableScanByKeyRange(source) failed: " + err.Error())
return
}
defer sourceQueryResultReader.Close()
destinationQueryResultReader, err := TableScanByKeyRange(sdw.wr.TopoServer(), sdw.destinationAlias, &tableDefinition, key.KeyRange{}, sdw.keyspaceInfo.ShardingColumnType)
if err != nil {
sdw.diffLog("TableScanByKeyRange(destination) failed: " + err.Error())
return
}
defer destinationQueryResultReader.Close()
differ, err := NewRowDiffer(sourceQueryResultReader, destinationQueryResultReader, &tableDefinition)
if err != nil {
sdw.diffLog("NewRowDiffer() failed: " + err.Error())
return
}
report, err := differ.Go()
if err != nil {
sdw.diffLog("Differ.Go failed: " + err.Error())
} else {
if report.HasDifferences() {
sdw.diffLog(fmt.Sprintf("Table %v has differences: %v", tableDefinition.Name, report.String()))
} else {
sdw.diffLog(fmt.Sprintf("Table %v checks out (%v rows processed, %v qps)", tableDefinition.Name, report.processedRows, report.processingQPS))
}
}
}(tableDefinition)
}
wg.Wait()
return nil
}