forked from dolthub/vitess
-
Notifications
You must be signed in to change notification settings - Fork 0
/
updatestreamctl.go
318 lines (266 loc) · 9.35 KB
/
updatestreamctl.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
/*
Copyright 2017 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package binlog
import (
"fmt"
"sync"
"golang.org/x/net/context"
"vitess.io/vitess/go/mysql"
"vitess.io/vitess/go/stats"
"vitess.io/vitess/go/sync2"
"vitess.io/vitess/go/tb"
"vitess.io/vitess/go/vt/log"
"vitess.io/vitess/go/vt/topo"
"vitess.io/vitess/go/vt/vttablet/tabletserver/schema"
binlogdatapb "vitess.io/vitess/go/vt/proto/binlogdata"
topodatapb "vitess.io/vitess/go/vt/proto/topodata"
)
/* API and config for UpdateStream Service */
const (
usDisabled int64 = iota
usEnabled
)
var usStateNames = map[int64]string{
usEnabled: "Enabled",
usDisabled: "Disabled",
}
var (
streamCount = stats.NewCountersWithSingleLabel("UpdateStreamStreamCount", "update stream count", "type")
updateStreamErrors = stats.NewCountersWithSingleLabel("UpdateStreamErrors", "update stream error count", "type")
keyrangeStatements = stats.NewCounter("UpdateStreamKeyRangeStatements", "update stream key range statement count")
keyrangeTransactions = stats.NewCounter("UpdateStreamKeyRangeTransactions", "update stream key range transaction count")
tablesStatements = stats.NewCounter("UpdateStreamTablesStatements", "update stream table statement count")
tablesTransactions = stats.NewCounter("UpdateStreamTablesTransactions", "update stream table transaction count")
)
// UpdateStreamControl is the interface an UpdateStream service implements
// to bring it up or down.
type UpdateStreamControl interface {
// Enable will allow any new RPC calls
Enable()
// Disable will interrupt all current calls, and disallow any new call
Disable()
// IsEnabled returns true iff the service is enabled
IsEnabled() bool
}
// UpdateStreamControlMock is an implementation of UpdateStreamControl
// to be used in tests
type UpdateStreamControlMock struct {
enabled bool
sync.Mutex
}
// NewUpdateStreamControlMock creates a new UpdateStreamControlMock
func NewUpdateStreamControlMock() *UpdateStreamControlMock {
return &UpdateStreamControlMock{}
}
// Enable is part of UpdateStreamControl
func (m *UpdateStreamControlMock) Enable() {
m.Lock()
m.enabled = true
m.Unlock()
}
// Disable is part of UpdateStreamControl
func (m *UpdateStreamControlMock) Disable() {
m.Lock()
m.enabled = false
m.Unlock()
}
// IsEnabled is part of UpdateStreamControl
func (m *UpdateStreamControlMock) IsEnabled() bool {
m.Lock()
defer m.Unlock()
return m.enabled
}
// UpdateStreamImpl is the real implementation of UpdateStream
// and UpdateStreamControl
type UpdateStreamImpl struct {
// the following variables are set at construction time
ts *topo.Server
keyspace string
cell string
cp *mysql.ConnParams
se *schema.Engine
// actionLock protects the following variables
actionLock sync.Mutex
state sync2.AtomicInt64
stateWaitGroup sync.WaitGroup
streams StreamList
}
// StreamList is a map of context.CancelFunc to mass-interrupt ongoing
// calls.
type StreamList struct {
sync.Mutex
currentIndex int
streams map[int]context.CancelFunc
}
// Init must be called before using the list.
func (sl *StreamList) Init() {
sl.Lock()
sl.streams = make(map[int]context.CancelFunc)
sl.currentIndex = 0
sl.Unlock()
}
// Add adds a CancelFunc to the map.
func (sl *StreamList) Add(c context.CancelFunc) int {
sl.Lock()
defer sl.Unlock()
sl.currentIndex++
sl.streams[sl.currentIndex] = c
return sl.currentIndex
}
// Delete removes a CancelFunc from the list.
func (sl *StreamList) Delete(i int) {
sl.Lock()
delete(sl.streams, i)
sl.Unlock()
}
// Stop stops all the current streams.
func (sl *StreamList) Stop() {
sl.Lock()
for _, c := range sl.streams {
c()
}
sl.Unlock()
}
// RegisterUpdateStreamServiceFunc is the type to use for delayed
// registration of RPC servers until we have all the objects
type RegisterUpdateStreamServiceFunc func(UpdateStream)
// RegisterUpdateStreamServices is the list of all registration
// callbacks to invoke
var RegisterUpdateStreamServices []RegisterUpdateStreamServiceFunc
// NewUpdateStream returns a new UpdateStreamImpl object
func NewUpdateStream(ts *topo.Server, keyspace string, cell string, cp *mysql.ConnParams, se *schema.Engine) *UpdateStreamImpl {
return &UpdateStreamImpl{
ts: ts,
keyspace: keyspace,
cell: cell,
cp: cp,
se: se,
}
}
// RegisterService needs to be called to publish stats, and to start listening
// to clients. Only once instance can call this in a process.
func (updateStream *UpdateStreamImpl) RegisterService() {
// publish the stats
stats.Publish("UpdateStreamState", stats.StringFunc(func() string {
return usStateNames[updateStream.state.Get()]
}))
// and register all the RPC protocols
for _, f := range RegisterUpdateStreamServices {
f(updateStream)
}
}
func logError() {
if x := recover(); x != nil {
log.Errorf("%s at\n%s", x.(error).Error(), tb.Stack(4))
}
}
// Enable will allow connections to the service
func (updateStream *UpdateStreamImpl) Enable() {
defer logError()
updateStream.actionLock.Lock()
defer updateStream.actionLock.Unlock()
if updateStream.IsEnabled() {
return
}
updateStream.state.Set(usEnabled)
updateStream.streams.Init()
log.Infof("Enabling update stream, dbname: %s", updateStream.cp.DbName)
}
// Disable will disallow any connection to the service
func (updateStream *UpdateStreamImpl) Disable() {
defer logError()
updateStream.actionLock.Lock()
defer updateStream.actionLock.Unlock()
if !updateStream.IsEnabled() {
return
}
updateStream.state.Set(usDisabled)
updateStream.streams.Stop()
updateStream.stateWaitGroup.Wait()
log.Infof("Update Stream Disabled")
}
// IsEnabled returns true if UpdateStreamImpl is enabled
func (updateStream *UpdateStreamImpl) IsEnabled() bool {
return updateStream.state.Get() == usEnabled
}
// StreamKeyRange is part of the UpdateStream interface
func (updateStream *UpdateStreamImpl) StreamKeyRange(ctx context.Context, position string, keyRange *topodatapb.KeyRange, charset *binlogdatapb.Charset, callback func(trans *binlogdatapb.BinlogTransaction) error) (err error) {
pos, err := mysql.DecodePosition(position)
if err != nil {
return err
}
updateStream.actionLock.Lock()
if !updateStream.IsEnabled() {
updateStream.actionLock.Unlock()
log.Errorf("Unable to serve client request: Update stream service is not enabled")
return fmt.Errorf("update stream service is not enabled")
}
updateStream.stateWaitGroup.Add(1)
updateStream.actionLock.Unlock()
defer updateStream.stateWaitGroup.Done()
streamCount.Add("KeyRange", 1)
defer streamCount.Add("KeyRange", -1)
log.Infof("ServeUpdateStream starting @ %#v", pos)
// Calls cascade like this: binlog.Streamer->KeyRangeFilterFunc->func(*binlogdatapb.BinlogTransaction)->callback
f := KeyRangeFilterFunc(keyRange, func(trans *binlogdatapb.BinlogTransaction) error {
keyrangeStatements.Add(int64(len(trans.Statements)))
keyrangeTransactions.Add(1)
return callback(trans)
})
bls := NewStreamer(updateStream.cp, updateStream.se, charset, pos, 0, f)
bls.resolverFactory, err = newKeyspaceIDResolverFactory(ctx, updateStream.ts, updateStream.keyspace, updateStream.cell)
if err != nil {
return fmt.Errorf("newKeyspaceIDResolverFactory failed: %v", err)
}
streamCtx, cancel := context.WithCancel(ctx)
i := updateStream.streams.Add(cancel)
defer updateStream.streams.Delete(i)
return bls.Stream(streamCtx)
}
// StreamTables is part of the UpdateStream interface
func (updateStream *UpdateStreamImpl) StreamTables(ctx context.Context, position string, tables []string, charset *binlogdatapb.Charset, callback func(trans *binlogdatapb.BinlogTransaction) error) (err error) {
pos, err := mysql.DecodePosition(position)
if err != nil {
return err
}
updateStream.actionLock.Lock()
if !updateStream.IsEnabled() {
updateStream.actionLock.Unlock()
log.Errorf("Unable to serve client request: Update stream service is not enabled")
return fmt.Errorf("update stream service is not enabled")
}
updateStream.stateWaitGroup.Add(1)
updateStream.actionLock.Unlock()
defer updateStream.stateWaitGroup.Done()
streamCount.Add("Tables", 1)
defer streamCount.Add("Tables", -1)
log.Infof("ServeUpdateStream starting @ %#v", pos)
// Calls cascade like this: binlog.Streamer->TablesFilterFunc->func(*binlogdatapb.BinlogTransaction)->callback
f := TablesFilterFunc(tables, func(trans *binlogdatapb.BinlogTransaction) error {
tablesStatements.Add(int64(len(trans.Statements)))
tablesTransactions.Add(1)
return callback(trans)
})
bls := NewStreamer(updateStream.cp, updateStream.se, charset, pos, 0, f)
streamCtx, cancel := context.WithCancel(ctx)
i := updateStream.streams.Add(cancel)
defer updateStream.streams.Delete(i)
return bls.Stream(streamCtx)
}
// HandlePanic is part of the UpdateStream interface
func (updateStream *UpdateStreamImpl) HandlePanic(err *error) {
if x := recover(); x != nil {
log.Errorf("Uncaught panic:\n%v\n%s", x, tb.Stack(4))
*err = fmt.Errorf("uncaught panic: %v", x)
}
}