forked from vitessio/vitess
-
Notifications
You must be signed in to change notification settings - Fork 0
/
binlog.go
441 lines (383 loc) · 12.8 KB
/
binlog.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
// 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 tabletmanager
// This file handles the binlog players launched on masters for filtered
// replication
import (
"fmt"
"math/rand" // not crypto-safe is OK here
"sync"
"time"
log "github.com/golang/glog"
"github.com/youtube/vitess/go/mysql"
"github.com/youtube/vitess/go/stats"
"github.com/youtube/vitess/go/vt/binlog/binlogplayer"
"github.com/youtube/vitess/go/vt/concurrency"
"github.com/youtube/vitess/go/vt/key"
"github.com/youtube/vitess/go/vt/mysqlctl"
myproto "github.com/youtube/vitess/go/vt/mysqlctl/proto"
"github.com/youtube/vitess/go/vt/topo"
)
func init() {
rand.Seed(time.Now().UnixNano())
}
// BinlogPlayerController controls one player
type BinlogPlayerController struct {
ts topo.Server
dbConfig *mysql.ConnectionParams
mysqld *mysqlctl.Mysqld
// Information about us
cell string
keyspaceIdType key.KeyspaceIdType
keyRange key.KeyRange
// Information about the source
sourceShard topo.SourceShard
// interrupted is the channel to close to stop the playback
interrupted chan struct{}
// done is the channel to wait for to be sure the player is done
done chan struct{}
// stopAtGroupId contains the stopping point for this player, if any
stopAtGroupId int64
}
func NewBinlogPlayerController(ts topo.Server, dbConfig *mysql.ConnectionParams, mysqld *mysqlctl.Mysqld, cell string, keyspaceIdType key.KeyspaceIdType, keyRange key.KeyRange, sourceShard topo.SourceShard) *BinlogPlayerController {
blc := &BinlogPlayerController{
ts: ts,
dbConfig: dbConfig,
mysqld: mysqld,
cell: cell,
keyspaceIdType: keyspaceIdType,
keyRange: keyRange,
sourceShard: sourceShard,
}
return blc
}
func (bpc *BinlogPlayerController) String() string {
return "BinlogPlayerController(" + bpc.sourceShard.String() + ")"
}
// Start will start the player in the background and run forever
func (bpc *BinlogPlayerController) Start() {
if bpc.interrupted != nil {
log.Warningf("%v: already started", bpc)
return
}
log.Infof("%v: starting binlog player", bpc)
bpc.interrupted = make(chan struct{}, 1)
bpc.done = make(chan struct{}, 1)
bpc.stopAtGroupId = 0 // run forever
go bpc.Loop()
}
// StartUntil will start the Player until we reach the given groupId
func (bpc *BinlogPlayerController) StartUntil(groupId int64) error {
if bpc.interrupted != nil {
return fmt.Errorf("%v: already started", bpc)
}
log.Infof("%v: starting binlog player until %v", bpc, groupId)
bpc.interrupted = make(chan struct{}, 1)
bpc.done = make(chan struct{}, 1)
bpc.stopAtGroupId = groupId
go bpc.Loop()
return nil
}
// WaitForStop will wait until the player is stopped. Use this after StartUntil.
func (bpc *BinlogPlayerController) WaitForStop(waitTimeout time.Duration) error {
if bpc.interrupted == nil {
log.Warningf("%v: not started", bpc)
return fmt.Errorf("WaitForStop called but player not started")
}
timer := time.After(waitTimeout)
select {
case <-bpc.done:
bpc.interrupted = nil
bpc.done = nil
return nil
case <-timer:
bpc.Stop()
return fmt.Errorf("WaitForStop timeout, stopping current player")
}
}
func (bpc *BinlogPlayerController) Stop() {
if bpc.interrupted == nil {
log.Warningf("%v: not started", bpc)
return
}
log.Infof("%v: stopping binlog player", bpc)
close(bpc.interrupted)
select {
case <-bpc.done:
bpc.interrupted = nil
bpc.done = nil
return
}
}
func (bpc *BinlogPlayerController) Loop() {
for {
err := bpc.Iteration()
if err == nil {
// this happens when we get interrupted
break
}
log.Warningf("%v: %v", bpc, err)
// sleep for a bit before retrying to connect
time.Sleep(5 * time.Second)
}
log.Infof("%v: exited main binlog player loop", bpc)
close(bpc.done)
}
func (bpc *BinlogPlayerController) DisableSuperToSetTimestamp() {
if err := bpc.mysqld.ExecuteMysqlCommand("set @@global.super_to_set_timestamp = 0"); err != nil {
log.Warningf("Cannot set super_to_set_timestamp=0: %v", err)
} else {
log.Info("Successfully set super_to_set_timestamp=0")
}
}
func (bpc *BinlogPlayerController) Iteration() (err error) {
defer func() {
if x := recover(); x != nil {
log.Errorf("%v: caught panic: %v", bpc, x)
err = fmt.Errorf("panic: %v", x)
}
}()
// Enable any user to set the timestamp.
// We do it on every iteration to be sure, in case mysql was
// restarted.
bpc.DisableSuperToSetTimestamp()
// create the db connection, connect it
vtClient := binlogplayer.NewDbClient(bpc.dbConfig)
if err := vtClient.Connect(); err != nil {
return fmt.Errorf("can't connect to database: %v", err)
}
defer vtClient.Close()
// Read the start position
startPosition, err := binlogplayer.ReadStartPosition(vtClient, bpc.sourceShard.Uid)
if err != nil {
return fmt.Errorf("can't read startPosition: %v", err)
}
// Find the server list for the source shard in our cell
addrs, err := bpc.ts.GetEndPoints(bpc.cell, bpc.sourceShard.Keyspace, bpc.sourceShard.Shard, topo.TYPE_REPLICA)
if err != nil {
return fmt.Errorf("can't find any source tablet for %v %v %v: %v", bpc.cell, bpc.sourceShard.String(), topo.TYPE_REPLICA, err)
}
if len(addrs.Entries) == 0 {
return fmt.Errorf("empty source tablet list for %v %v %v", bpc.cell, bpc.sourceShard.String(), topo.TYPE_REPLICA)
}
newServerIndex := rand.Intn(len(addrs.Entries))
addr := fmt.Sprintf("%v:%v", addrs.Entries[newServerIndex].Host, addrs.Entries[newServerIndex].NamedPortMap["_vtocc"])
// check which kind of replication we're doing, tables or keyrange
if len(bpc.sourceShard.Tables) > 0 {
// tables, just get them
player := binlogplayer.NewBinlogPlayerTables(vtClient, addr, bpc.sourceShard.Tables, startPosition, bpc.stopAtGroupId)
return player.ApplyBinlogEvents(bpc.interrupted)
} else {
// the data we have to replicate is the intersection of the
// source keyrange and our keyrange
overlap, err := key.KeyRangesOverlap(bpc.sourceShard.KeyRange, bpc.keyRange)
if err != nil {
return fmt.Errorf("Source shard %v doesn't overlap destination shard %v", bpc.sourceShard.KeyRange, bpc.keyRange)
}
player := binlogplayer.NewBinlogPlayerKeyRange(vtClient, addr, bpc.keyspaceIdType, overlap, startPosition, bpc.stopAtGroupId)
return player.ApplyBinlogEvents(bpc.interrupted)
}
}
func (bpc *BinlogPlayerController) BlpPosition(vtClient *binlogplayer.DBClient) (*myproto.BlpPosition, error) {
return binlogplayer.ReadStartPosition(vtClient, bpc.sourceShard.Uid)
}
// BinlogPlayerMap controls all the players.
// It can be stopped and restarted.
type BinlogPlayerMap struct {
// Immutable, set at construction time
ts topo.Server
dbConfig *mysql.ConnectionParams
mysqld *mysqlctl.Mysqld
// This mutex protects the map and the state
mu sync.Mutex
players map[uint32]*BinlogPlayerController
state int64
}
const (
BPM_STATE_RUNNING int64 = iota
BPM_STATE_STOPPED
)
func NewBinlogPlayerMap(ts topo.Server, dbConfig *mysql.ConnectionParams, mysqld *mysqlctl.Mysqld) *BinlogPlayerMap {
return &BinlogPlayerMap{
ts: ts,
dbConfig: dbConfig,
mysqld: mysqld,
players: make(map[uint32]*BinlogPlayerController),
state: BPM_STATE_RUNNING,
}
}
func RegisterBinlogPlayerMap(blm *BinlogPlayerMap) {
stats.Publish("BinlogPlayerMapSize", stats.IntFunc(blm.size))
}
func (blm *BinlogPlayerMap) size() int64 {
blm.mu.Lock()
result := len(blm.players)
blm.mu.Unlock()
return int64(result)
}
// addPlayer adds a new player to the map. It assumes we have the lock.
func (blm *BinlogPlayerMap) addPlayer(cell string, keyspaceIdType key.KeyspaceIdType, keyRange key.KeyRange, sourceShard topo.SourceShard) {
bpc, ok := blm.players[sourceShard.Uid]
if ok {
log.Infof("Already playing logs for %v", sourceShard)
return
}
bpc = NewBinlogPlayerController(blm.ts, blm.dbConfig, blm.mysqld, cell, keyspaceIdType, keyRange, sourceShard)
blm.players[sourceShard.Uid] = bpc
if blm.state == BPM_STATE_RUNNING {
bpc.Start()
}
}
// StopAllPlayersAndReset stops all the binlog players, and reset the map of
// players.
func (blm *BinlogPlayerMap) StopAllPlayersAndReset() {
hadPlayers := false
blm.mu.Lock()
for _, bpc := range blm.players {
if blm.state == BPM_STATE_RUNNING {
bpc.Stop()
}
hadPlayers = true
}
blm.players = make(map[uint32]*BinlogPlayerController)
blm.mu.Unlock()
if hadPlayers {
blm.enableSuperToSetTimestamp()
}
}
// RefreshMap reads the right data from topo.Server and makes sure
// we're playing the right logs.
func (blm *BinlogPlayerMap) RefreshMap(tablet topo.Tablet, keyspaceInfo *topo.KeyspaceInfo, shardInfo *topo.ShardInfo) {
log.Infof("Refreshing map of binlog players")
if keyspaceInfo == nil {
log.Warningf("Could not read keyspaceInfo, not changing anything")
return
}
if shardInfo == nil {
log.Warningf("Could not read shardInfo, not changing anything")
return
}
blm.mu.Lock()
// get the existing sources and build a map of sources to remove
toRemove := make(map[uint32]bool)
hadPlayers := false
for source := range blm.players {
toRemove[source] = true
hadPlayers = true
}
// for each source, add it if not there, and delete from toRemove
for _, sourceShard := range shardInfo.SourceShards {
blm.addPlayer(tablet.Alias.Cell, keyspaceInfo.ShardingColumnType, tablet.KeyRange, sourceShard)
delete(toRemove, sourceShard.Uid)
}
hasPlayers := len(shardInfo.SourceShards) > 0
// remove all entries from toRemove
for source := range toRemove {
blm.players[source].Stop()
delete(blm.players, source)
}
blm.mu.Unlock()
if hadPlayers && !hasPlayers {
blm.enableSuperToSetTimestamp()
}
}
// After this is called, the clients will need super privileges
// to set timestamp
func (blm *BinlogPlayerMap) enableSuperToSetTimestamp() {
if err := blm.mysqld.ExecuteMysqlCommand("set @@global.super_to_set_timestamp = 1"); err != nil {
log.Warningf("Cannot set super_to_set_timestamp=1: %v", err)
} else {
log.Info("Successfully set super_to_set_timestamp=1")
}
}
// Stop stops the current players, but does not remove them from the map.
// Call 'Start' to restart the playback.
func (blm *BinlogPlayerMap) Stop() {
blm.mu.Lock()
defer blm.mu.Unlock()
if blm.state == BPM_STATE_STOPPED {
log.Warningf("BinlogPlayerMap already stopped")
return
}
log.Infof("Stopping map of binlog players")
for _, bpc := range blm.players {
bpc.Stop()
}
blm.state = BPM_STATE_STOPPED
}
// Start restarts the current players
func (blm *BinlogPlayerMap) Start() {
blm.mu.Lock()
defer blm.mu.Unlock()
if blm.state == BPM_STATE_RUNNING {
log.Warningf("BinlogPlayerMap already started")
return
}
log.Infof("Starting map of binlog players")
for _, bpc := range blm.players {
bpc.Start()
}
blm.state = BPM_STATE_RUNNING
}
// BlpPositionList returns the current position of all the players
func (blm *BinlogPlayerMap) BlpPositionList() (*myproto.BlpPositionList, error) {
// create a db connection for this purpose
vtClient := binlogplayer.NewDbClient(blm.dbConfig)
if err := vtClient.Connect(); err != nil {
return nil, fmt.Errorf("can't connect to database: %v", err)
}
defer vtClient.Close()
result := &myproto.BlpPositionList{}
blm.mu.Lock()
defer blm.mu.Unlock()
for _, bpc := range blm.players {
blp, err := bpc.BlpPosition(vtClient)
if err != nil {
return nil, fmt.Errorf("can't read current position for %v: %v", bpc, err)
}
result.Entries = append(result.Entries, *blp)
}
return result, nil
}
// RunUntil will run all the players until they reach the given position.
// Holds the map lock during that exercise, shouldn't take long at all.
func (blm *BinlogPlayerMap) RunUntil(blpPositionList *myproto.BlpPositionList, waitTimeout time.Duration) error {
// lock and check state
blm.mu.Lock()
defer blm.mu.Unlock()
if blm.state != BPM_STATE_STOPPED {
return fmt.Errorf("RunUntil: player not stopped: %v", blm.state)
}
log.Infof("Starting map of binlog players until position")
// find the exact stop position for all players, to be sure
// we're not doing anything wrong
groupIds := make(map[uint32]int64)
for _, bpc := range blm.players {
pos, err := blpPositionList.FindBlpPositionById(bpc.sourceShard.Uid)
if err != nil {
return fmt.Errorf("No binlog position passed in for player Uid %v", bpc.sourceShard.Uid)
}
groupIds[bpc.sourceShard.Uid] = pos.GroupId
}
// start all the players giving them where to stop
for _, bpc := range blm.players {
if err := bpc.StartUntil(groupIds[bpc.sourceShard.Uid]); err != nil {
return err
}
}
// wait for all players to be stopped, or timeout
wg := sync.WaitGroup{}
rec := concurrency.AllErrorRecorder{}
for _, bpc := range blm.players {
wg.Add(1)
go func(bpc *BinlogPlayerController) {
if err := bpc.WaitForStop(waitTimeout); err != nil {
rec.RecordError(err)
}
wg.Done()
}(bpc)
}
wg.Wait()
return rec.Error()
}