forked from vitessio/vitess
-
Notifications
You must be signed in to change notification settings - Fork 1
/
event_streamer.go
292 lines (263 loc) · 8.52 KB
/
event_streamer.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
// Copyright 2012, 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 binlog
import (
"bytes"
"encoding/base64"
"fmt"
"strconv"
log "github.com/golang/glog"
mproto "github.com/youtube/vitess/go/mysql/proto"
"github.com/youtube/vitess/go/sqltypes"
"github.com/youtube/vitess/go/sync2"
"github.com/youtube/vitess/go/vt/binlog/proto"
"github.com/youtube/vitess/go/vt/mysqlctl"
myproto "github.com/youtube/vitess/go/vt/mysqlctl/proto"
"github.com/youtube/vitess/go/vt/sqlparser"
)
var (
binlogSetInsertID = []byte("SET INSERT_ID=")
binlogSetInsertIDLen = len(binlogSetInsertID)
streamCommentStart = []byte("/* _stream ")
streamCommentStartLen = len(streamCommentStart)
)
type sendEventFunc func(event *proto.StreamEvent) error
// EventStreamer is an adapter on top of a BinlogStreamer that convert
// the events into StreamEvent objects.
type EventStreamer struct {
bls *BinlogStreamer
sendEvent sendEventFunc
}
// NewEventStreamer returns a new EventStreamer on top of a BinlogStreamer
func NewEventStreamer(dbname string, mysqld mysqlctl.MysqlDaemon, startPos myproto.ReplicationPosition, sendEvent sendEventFunc) *EventStreamer {
evs := &EventStreamer{
sendEvent: sendEvent,
}
evs.bls = NewBinlogStreamer(dbname, mysqld, nil, startPos, evs.transactionToEvent)
return evs
}
// Stream starts streaming updates
func (evs *EventStreamer) Stream(ctx *sync2.ServiceContext) error {
return evs.bls.Stream(ctx)
}
func (evs *EventStreamer) transactionToEvent(trans *proto.BinlogTransaction) error {
var err error
var insertid int64
for _, stmt := range trans.Statements {
switch stmt.Category {
case proto.BL_SET:
if bytes.HasPrefix(stmt.Sql, binlogSetInsertID) {
insertid, err = strconv.ParseInt(string(stmt.Sql[binlogSetInsertIDLen:]), 10, 64)
if err != nil {
binlogStreamerErrors.Add("EventStreamer", 1)
log.Errorf("%v: %s", err, stmt.Sql)
}
}
case proto.BL_DML:
var dmlEvent *proto.StreamEvent
dmlEvent, insertid, err = evs.buildDMLEvent(stmt.Sql, insertid)
if err != nil {
dmlEvent = &proto.StreamEvent{
Category: "ERR",
Sql: string(stmt.Sql),
}
}
dmlEvent.Timestamp = trans.Timestamp
if err = evs.sendEvent(dmlEvent); err != nil {
return err
}
case proto.BL_DDL:
ddlEvent := &proto.StreamEvent{
Category: "DDL",
Sql: string(stmt.Sql),
Timestamp: trans.Timestamp,
}
if err = evs.sendEvent(ddlEvent); err != nil {
return err
}
case proto.BL_UNRECOGNIZED:
unrecognized := &proto.StreamEvent{
Category: "ERR",
Sql: string(stmt.Sql),
Timestamp: trans.Timestamp,
}
if err = evs.sendEvent(unrecognized); err != nil {
return err
}
default:
binlogStreamerErrors.Add("EventStreamer", 1)
log.Errorf("Unrecognized event: %v: %s", stmt.Category, stmt.Sql)
}
}
posEvent := &proto.StreamEvent{
Category: "POS",
TransactionID: trans.TransactionID,
Timestamp: trans.Timestamp,
}
if err = evs.sendEvent(posEvent); err != nil {
return err
}
return nil
}
/*
buildDMLEvent parses the tuples of the full stream comment.
The _stream comment is extracted into a StreamEvent.
*/
// Example query: insert into vtocc_e(foo) values ('foo') /* _stream vtocc_e (eid id name ) (null 1 'bmFtZQ==' ); */
// the "null" value is used for auto-increment columns.
func (evs *EventStreamer) buildDMLEvent(sql []byte, insertid int64) (*proto.StreamEvent, int64, error) {
// first extract the comment
commentIndex := bytes.LastIndex(sql, streamCommentStart)
if commentIndex == -1 {
return nil, insertid, fmt.Errorf("missing stream comment")
}
dmlComment := string(sql[commentIndex+streamCommentStartLen:])
// then strat building the response
dmlEvent := &proto.StreamEvent{
Category: "DML",
}
tokenizer := sqlparser.NewStringTokenizer(dmlComment)
// first parse the table name
typ, val := tokenizer.Scan()
if typ != sqlparser.ID {
return nil, insertid, fmt.Errorf("expecting table name in stream comment")
}
dmlEvent.TableName = string(val)
// then parse the PK names
var err error
dmlEvent.PrimaryKeyFields, err = parsePkNames(tokenizer)
if err != nil {
return nil, insertid, err
}
// then parse the PK values, one at a time
for typ, val = tokenizer.Scan(); typ != ';'; typ, val = tokenizer.Scan() {
switch typ {
case '(':
// pkTuple is a list of pk values
var pkTuple []sqltypes.Value
pkTuple, insertid, err = parsePkTuple(tokenizer, insertid, dmlEvent.PrimaryKeyFields)
if err != nil {
return nil, insertid, err
}
dmlEvent.PrimaryKeyValues = append(dmlEvent.PrimaryKeyValues, pkTuple)
default:
return nil, insertid, fmt.Errorf("expecting '('")
}
}
return dmlEvent, insertid, nil
}
// parsePkNames parses something like (eid id name )
func parsePkNames(tokenizer *sqlparser.Tokenizer) ([]mproto.Field, error) {
var columns []mproto.Field
if typ, _ := tokenizer.Scan(); typ != '(' {
return nil, fmt.Errorf("expecting '('")
}
for typ, val := tokenizer.Scan(); typ != ')'; typ, val = tokenizer.Scan() {
switch typ {
case sqlparser.ID:
columns = append(columns, mproto.Field{
Name: string(val),
})
default:
return nil, fmt.Errorf("syntax error at position: %d", tokenizer.Position)
}
}
return columns, nil
}
// parsePkTuple parses something like (null 1 'bmFtZQ==' )
func parsePkTuple(tokenizer *sqlparser.Tokenizer, insertid int64, fields []mproto.Field) ([]sqltypes.Value, int64, error) {
var result []sqltypes.Value
// start scanning the list
index := 0
for typ, val := tokenizer.Scan(); typ != ')'; typ, val = tokenizer.Scan() {
if index >= len(fields) {
return nil, insertid, fmt.Errorf("length mismatch in values")
}
switch typ {
case '-':
// handle negative numbers
typ2, val2 := tokenizer.Scan()
if typ2 != sqlparser.NUMBER {
return nil, insertid, fmt.Errorf("expecting number after '-'")
}
// check value
fullVal := append([]byte{'-'}, val2...)
if _, err := strconv.ParseInt(string(fullVal), 0, 64); err != nil {
return nil, insertid, err
}
// update type
switch fields[index].Type {
case mproto.VT_DECIMAL:
// we haven't updated the type yet
fields[index].Type = mproto.VT_LONGLONG
case mproto.VT_LONGLONG:
// nothing to do there
default:
// we already set this to something incompatible!
return nil, insertid, fmt.Errorf("incompatible negative number field with type %v", fields[index].Type)
}
// update value
result = append(result, sqltypes.MakeNumeric(fullVal))
case sqlparser.NUMBER:
// check value
if _, err := strconv.ParseUint(string(val), 0, 64); err != nil {
return nil, insertid, err
}
// update type
switch fields[index].Type {
case mproto.VT_DECIMAL:
// we haven't updated the type yet
fields[index].Type = mproto.VT_LONGLONG
case mproto.VT_LONGLONG:
// nothing to do there
default:
// we already set this to something incompatible!
return nil, insertid, fmt.Errorf("incompatible number field with type %v", fields[index].Type)
}
// update value
result = append(result, sqltypes.MakeNumeric(val))
case sqlparser.NULL:
// update type
switch fields[index].Type {
case mproto.VT_DECIMAL:
// we haven't updated the type yet
fields[index].Type = mproto.VT_LONGLONG
case mproto.VT_LONGLONG:
// nothing to do there
default:
// we already set this to something incompatible!
return nil, insertid, fmt.Errorf("incompatible auto-increment field with type %v", fields[index].Type)
}
// update value
result = append(result, sqltypes.MakeNumeric(strconv.AppendInt(nil, insertid, 10)))
insertid++
case sqlparser.STRING:
// update type
switch fields[index].Type {
case mproto.VT_DECIMAL:
// we haven't updated the type yet
fields[index].Type = mproto.VT_VARCHAR
case mproto.VT_VARCHAR:
// nothing to do there
default:
// we already set this to something incompatible!
return nil, insertid, fmt.Errorf("incompatible string field with type %v", fields[index].Type)
}
// update value
decoded := make([]byte, base64.StdEncoding.DecodedLen(len(val)))
numDecoded, err := base64.StdEncoding.Decode(decoded, val)
if err != nil {
return nil, insertid, err
}
result = append(result, sqltypes.MakeString(decoded[:numDecoded]))
default:
return nil, insertid, fmt.Errorf("syntax error at position: %d", tokenizer.Position)
}
index++
}
if index != len(fields) {
return nil, insertid, fmt.Errorf("length mismatch in values")
}
return result, insertid, nil
}