forked from github/gh-ost
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgomysql_reader.go
More file actions
225 lines (207 loc) · 7.73 KB
/
gomysql_reader.go
File metadata and controls
225 lines (207 loc) · 7.73 KB
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
/*
Copyright 2022 GitHub Inc.
See https://github.com/github/gh-ost/blob/master/LICENSE
*/
package binlog
import (
"fmt"
"sync"
"github.com/github/gh-ost/go/base"
"github.com/github/gh-ost/go/mysql"
"github.com/github/gh-ost/go/sql"
"time"
gomysql "github.com/go-mysql-org/go-mysql/mysql"
"github.com/go-mysql-org/go-mysql/replication"
uuid "github.com/google/uuid"
"golang.org/x/net/context"
)
type GoMySQLReader struct {
migrationContext *base.MigrationContext
connectionConfig *mysql.ConnectionConfig
binlogSyncer *replication.BinlogSyncer
binlogStreamer *replication.BinlogStreamer
currentCoordinates mysql.BinlogCoordinates
currentCoordinatesMutex *sync.Mutex
// LastTrxCoords are the coordinates of the last transaction completely read.
// If using the file coordinates it is binlog position of the transaction's XID event.
LastTrxCoords mysql.BinlogCoordinates
// currentTrxCoords is set once per GTIDEvent and shared by all RowsEvents within
// the same transaction. It points to currentCoordinates (a *LazyGTIDCoordinates),
// which is replaced at the next GTIDEvent — so old entries retain valid references.
// Only accessed from within the StreamEvents goroutine; no mutex needed.
currentTrxCoords mysql.BinlogCoordinates
// lastCommittedGTIDSet is the MysqlGTIDSet from the most recently seen XIDEvent
// (or the initial coordinates). It is immutable once set and used as the base for
// LazyGTIDCoordinates so we avoid cloning the full set on each GTIDEvent.
// Only written from within StreamEvents; no mutex needed.
lastCommittedGTIDSet *gomysql.MysqlGTIDSet
}
func NewGoMySQLReader(migrationContext *base.MigrationContext) *GoMySQLReader {
connectionConfig := migrationContext.InspectorConnectionConfig
return &GoMySQLReader{
migrationContext: migrationContext,
connectionConfig: connectionConfig,
currentCoordinatesMutex: &sync.Mutex{},
binlogSyncer: replication.NewBinlogSyncer(replication.BinlogSyncerConfig{
ServerID: uint32(migrationContext.ReplicaServerId),
Flavor: gomysql.MySQLFlavor,
Host: connectionConfig.Key.Hostname,
Port: uint16(connectionConfig.Key.Port),
User: connectionConfig.User,
Password: connectionConfig.Password,
TLSConfig: connectionConfig.TLSConfig(),
UseDecimal: true,
TimestampStringLocation: time.UTC,
MaxReconnectAttempts: migrationContext.BinlogSyncerMaxReconnectAttempts,
}),
}
}
// ConnectBinlogStreamer
func (this *GoMySQLReader) ConnectBinlogStreamer(coordinates mysql.BinlogCoordinates) (err error) {
if coordinates.IsEmpty() {
return this.migrationContext.Log.Errorf("Empty coordinates at ConnectBinlogStreamer()")
}
this.currentCoordinatesMutex.Lock()
defer this.currentCoordinatesMutex.Unlock()
this.currentCoordinates = coordinates
this.migrationContext.Log.Infof("Connecting binlog streamer at %+v", coordinates)
// Start sync with specified GTID set or binlog file and position
if this.migrationContext.UseGTIDs {
coords := coordinates.(*mysql.GTIDBinlogCoordinates)
this.lastCommittedGTIDSet = coords.GTIDSet
this.binlogStreamer, err = this.binlogSyncer.StartSyncGTID(coords.GTIDSet)
} else {
coords := this.currentCoordinates.(*mysql.FileBinlogCoordinates)
this.binlogStreamer, err = this.binlogSyncer.StartSync(gomysql.Position{
Name: coords.LogFile,
Pos: uint32(coords.LogPos)},
)
}
return err
}
func (this *GoMySQLReader) GetCurrentBinlogCoordinates() mysql.BinlogCoordinates {
this.currentCoordinatesMutex.Lock()
defer this.currentCoordinatesMutex.Unlock()
return this.currentCoordinates.Clone()
}
func (this *GoMySQLReader) handleRowsEvent(ev *replication.BinlogEvent, rowsEvent *replication.RowsEvent, entriesChannel chan<- *BinlogEntry) error {
var currentCoords mysql.BinlogCoordinates
if this.migrationContext.UseGTIDs && this.currentTrxCoords != nil {
currentCoords = this.currentTrxCoords
} else {
currentCoords = this.GetCurrentBinlogCoordinates()
}
dml := ToEventDML(ev.Header.EventType.String())
if dml == NotDML {
return fmt.Errorf("Unknown DML type: %s", ev.Header.EventType.String())
}
for i, row := range rowsEvent.Rows {
if dml == UpdateDML && i%2 == 1 {
// An update has two rows (WHERE+SET)
// We do both at the same time
continue
}
binlogEntry := NewBinlogEntryAt(currentCoords)
binlogEntry.DmlEvent = NewBinlogDMLEvent(
string(rowsEvent.Table.Schema),
string(rowsEvent.Table.Table),
dml,
)
switch dml {
case InsertDML:
{
binlogEntry.DmlEvent.NewColumnValues = sql.ToColumnValues(row)
}
case UpdateDML:
{
binlogEntry.DmlEvent.WhereColumnValues = sql.ToColumnValues(row)
binlogEntry.DmlEvent.NewColumnValues = sql.ToColumnValues(rowsEvent.Rows[i+1])
}
case DeleteDML:
{
binlogEntry.DmlEvent.WhereColumnValues = sql.ToColumnValues(row)
}
}
// The channel will do the throttling. Whoever is reading from the channel
// decides whether action is taken synchronously (meaning we wait before
// next iteration) or asynchronously (we keep pushing more events)
// In reality, reads will be synchronous
entriesChannel <- binlogEntry
}
return nil
}
// StreamEvents
func (this *GoMySQLReader) StreamEvents(canStopStreaming func() bool, entriesChannel chan<- *BinlogEntry) error {
if canStopStreaming() {
return nil
}
for {
if canStopStreaming() {
break
}
ev, err := this.binlogStreamer.GetEvent(context.Background())
if err != nil {
return err
}
// Update binlog coords if using file-based coords.
// GTID coordinates are updated on receiving GTID events.
if !this.migrationContext.UseGTIDs {
this.currentCoordinatesMutex.Lock()
coords := this.currentCoordinates.(*mysql.FileBinlogCoordinates)
prevCoords := coords.Clone().(*mysql.FileBinlogCoordinates)
coords.LogPos = int64(ev.Header.LogPos)
coords.EventSize = int64(ev.Header.EventSize)
if coords.IsLogPosOverflowBeyond4Bytes(prevCoords) {
this.currentCoordinatesMutex.Unlock()
return fmt.Errorf("Unexpected rows event at %+v, the binlog end_log_pos is overflow 4 bytes", coords)
}
this.currentCoordinatesMutex.Unlock()
}
switch event := ev.Event.(type) {
case *replication.GTIDEvent:
if !this.migrationContext.UseGTIDs {
continue
}
sid, err := uuid.FromBytes(event.SID)
if err != nil {
return err
}
this.currentCoordinatesMutex.Lock()
this.currentCoordinates = mysql.NewLazyGTIDCoordinates(this.lastCommittedGTIDSet, sid, event.GNO)
this.currentTrxCoords = this.currentCoordinates
this.currentCoordinatesMutex.Unlock()
case *replication.RotateEvent:
if this.migrationContext.UseGTIDs {
continue
}
this.currentCoordinatesMutex.Lock()
coords := this.currentCoordinates.(*mysql.FileBinlogCoordinates)
coords.LogFile = string(event.NextLogName)
this.migrationContext.Log.Infof("rotate to next log from %s:%d to %s", coords.LogFile, int64(ev.Header.LogPos), event.NextLogName)
this.currentCoordinatesMutex.Unlock()
case *replication.XIDEvent:
if this.migrationContext.UseGTIDs {
gSet := event.GSet.(*gomysql.MysqlGTIDSet)
if coords, ok := this.LastTrxCoords.(*mysql.GTIDBinlogCoordinates); ok {
coords.GTIDSet = gSet
coords.UUIDSet = nil
} else {
this.LastTrxCoords = &mysql.GTIDBinlogCoordinates{GTIDSet: gSet}
}
this.lastCommittedGTIDSet = gSet
} else {
this.LastTrxCoords = this.currentCoordinates.Clone()
}
case *replication.RowsEvent:
if err := this.handleRowsEvent(ev, event, entriesChannel); err != nil {
return err
}
}
}
this.migrationContext.Log.Debugf("done streaming events")
return nil
}
func (this *GoMySQLReader) Close() error {
this.binlogSyncer.Close()
return nil
}