-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
traffic_switcher.go
315 lines (260 loc) · 9.02 KB
/
traffic_switcher.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
/*
Copyright 2021 The Vitess Authors.
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 workflow
import (
"bytes"
"context"
"errors"
"fmt"
"hash/fnv"
"math"
"sort"
"strings"
"google.golang.org/protobuf/encoding/prototext"
"vitess.io/vitess/go/sqltypes"
"vitess.io/vitess/go/vt/logutil"
"vitess.io/vitess/go/vt/topo"
"vitess.io/vitess/go/vt/vtgate/evalengine"
"vitess.io/vitess/go/vt/vtgate/vindexes"
"vitess.io/vitess/go/vt/vttablet/tmclient"
binlogdatapb "vitess.io/vitess/go/vt/proto/binlogdata"
querypb "vitess.io/vitess/go/vt/proto/query"
topodatapb "vitess.io/vitess/go/vt/proto/topodata"
)
var (
// Frozen is the message value of frozen vreplication streams.
Frozen = "FROZEN"
)
var (
// ErrNoStreams occurs when no target streams are found for a workflow in a
// target keyspace.
ErrNoStreams = errors.New("no streams found")
)
// TrafficSwitchDirection specifies the switching direction.
type TrafficSwitchDirection int
// The following constants define the switching direction.
const (
DirectionForward = TrafficSwitchDirection(iota)
DirectionBackward
)
// TableRemovalType specifies the way the a table will be removed during a
// DropSource for a MoveTables workflow.
type TableRemovalType int
// The following consts define if DropSource will drop or rename the table.
const (
DropTable = TableRemovalType(iota)
RenameTable
)
var tableRemovalTypeStrs = [...]string{
"DROP TABLE",
"RENAME TABLE",
}
// String returns a string representation of a TableRemovalType
func (trt TableRemovalType) String() string {
if trt < DropTable || trt > RenameTable {
return "Unknown"
}
return tableRemovalTypeStrs[trt]
}
// ITrafficSwitcher is a temporary hack to allow us to move streamMigrater out
// of package wrangler without also needing to move trafficSwitcher in the same
// changeset.
//
// After moving TrafficSwitcher to this package, this type should be removed,
// and StreamMigrator should be updated to contain a field of type
// *TrafficSwitcher instead of ITrafficSwitcher.
type ITrafficSwitcher interface {
/* Functions that expose types and behavior contained in *wrangler.Wrangler */
TopoServer() *topo.Server
TabletManagerClient() tmclient.TabletManagerClient
Logger() logutil.Logger
// VReplicationExec here is used when we want the (*wrangler.Wrangler)
// implementation, which does a topo lookup on the tablet alias before
// calling the underlying TabletManagerClient RPC.
VReplicationExec(ctx context.Context, alias *topodatapb.TabletAlias, query string) (*querypb.QueryResult, error)
/* Functions that expose fields on the *wrangler.trafficSwitcher */
MigrationType() binlogdatapb.MigrationType
ReverseWorkflowName() string
SourceKeyspaceName() string
SourceKeyspaceSchema() *vindexes.KeyspaceSchema
WorkflowName() string
/* Functions that *wrangler.trafficSwitcher implements */
ForAllSources(f func(source *MigrationSource) error) error
ForAllTargets(f func(target *MigrationTarget) error) error
}
// TargetInfo contains the metadata for a set of targets involved in a workflow.
type TargetInfo struct {
Targets map[string]*MigrationTarget
Frozen bool
OptCells string
OptTabletTypes string
}
// MigrationSource contains the metadata for each migration source.
type MigrationSource struct {
si *topo.ShardInfo
primary *topo.TabletInfo
Position string
Journaled bool
}
// NewMigrationSource returns a MigrationSource for the given shard and primary.
//
// (TODO|@ajm188): do we always want to start with (position:"", journaled:false)?
func NewMigrationSource(si *topo.ShardInfo, primary *topo.TabletInfo) *MigrationSource {
return &MigrationSource{
si: si,
primary: primary,
}
}
// GetShard returns the *topo.ShardInfo for the migration source.
func (source *MigrationSource) GetShard() *topo.ShardInfo {
return source.si
}
// GetPrimary returns the *topo.TabletInfo for the primary tablet of the
// migration source.
func (source *MigrationSource) GetPrimary() *topo.TabletInfo {
return source.primary
}
// MigrationTarget contains the metadata for each migration target.
type MigrationTarget struct {
si *topo.ShardInfo
primary *topo.TabletInfo
Sources map[uint32]*binlogdatapb.BinlogSource
Position string
}
// GetShard returns the *topo.ShardInfo for the migration target.
func (target *MigrationTarget) GetShard() *topo.ShardInfo {
return target.si
}
// GetPrimary returns the *topo.TabletInfo for the primary tablet of the
// migration target.
func (target *MigrationTarget) GetPrimary() *topo.TabletInfo {
return target.primary
}
// BuildTargets collects MigrationTargets and other metadata (see TargetInfo)
// from a workflow in the target keyspace.
//
// It returns ErrNoStreams if there are no targets found for the workflow.
func BuildTargets(ctx context.Context, ts *topo.Server, tmc tmclient.TabletManagerClient, targetKeyspace string, workflow string) (*TargetInfo, error) {
targetShards, err := ts.GetShardNames(ctx, targetKeyspace)
if err != nil {
return nil, err
}
var (
frozen bool
optCells string
optTabletTypes string
targets = make(map[string]*MigrationTarget, len(targetShards))
)
// We check all shards in the target keyspace. Not all of them may have a
// stream. For example, if we're splitting -80 to [-40,40-80], only those
// two target shards will have vreplication streams, and the other shards in
// the target keyspace will not.
for _, targetShard := range targetShards {
si, err := ts.GetShard(ctx, targetKeyspace, targetShard)
if err != nil {
return nil, err
}
if si.PrimaryAlias == nil {
// This can happen if bad inputs are given.
return nil, fmt.Errorf("shard %v/%v doesn't have a primary set", targetKeyspace, targetShard)
}
primary, err := ts.GetTablet(ctx, si.PrimaryAlias)
if err != nil {
return nil, err
}
// NB: changing the whitespace of this query breaks tests for now.
// (TODO:@ajm188) extend FakeDBClient to be less whitespace-sensitive on
// expected queries.
query := fmt.Sprintf("select id, source, message, cell, tablet_types from _vt.vreplication where workflow=%s and db_name=%s", encodeString(workflow), encodeString(primary.DbName()))
p3qr, err := tmc.VReplicationExec(ctx, primary.Tablet, query)
if err != nil {
return nil, err
}
if len(p3qr.Rows) < 1 {
continue
}
target := &MigrationTarget{
si: si,
primary: primary,
Sources: make(map[uint32]*binlogdatapb.BinlogSource),
}
qr := sqltypes.Proto3ToResult(p3qr)
for _, row := range qr.Rows {
id, err := evalengine.ToInt64(row[0])
if err != nil {
return nil, err
}
var bls binlogdatapb.BinlogSource
rowBytes, err := row[1].ToBytes()
if err != nil {
return nil, err
}
if err := prototext.Unmarshal(rowBytes, &bls); err != nil {
return nil, err
}
if row[2].ToString() == Frozen {
frozen = true
}
target.Sources[uint32(id)] = &bls
optCells = row[3].ToString()
optTabletTypes = row[4].ToString()
}
targets[targetShard] = target
}
if len(targets) == 0 {
return nil, fmt.Errorf("%w in keyspace %s for %s", ErrNoStreams, targetKeyspace, workflow)
}
return &TargetInfo{
Targets: targets,
Frozen: frozen,
OptCells: optCells,
OptTabletTypes: optTabletTypes,
}, nil
}
// HashStreams produces a stable hash based on the target keyspace and migration
// targets.
func HashStreams(targetKeyspace string, targets map[string]*MigrationTarget) int64 {
var expanded []string
for shard, target := range targets {
for uid := range target.Sources {
expanded = append(expanded, fmt.Sprintf("%s:%d", shard, uid))
}
}
sort.Strings(expanded)
hasher := fnv.New64()
hasher.Write([]byte(targetKeyspace))
for _, s := range expanded {
hasher.Write([]byte(s))
}
// Convert to int64 after dropping the highest bit.
return int64(hasher.Sum64() & math.MaxInt64)
}
const reverseSuffix = "_reverse"
// ReverseWorkflowName returns the "reversed" name of a workflow. For a
// "forward" workflow, this is the workflow name with "_reversed" appended, and
// for a "reversed" workflow, this is the workflow name with the "_reversed"
// suffix removed.
func ReverseWorkflowName(workflow string) string {
if strings.HasSuffix(workflow, reverseSuffix) {
return workflow[:len(workflow)-len(reverseSuffix)]
}
return workflow + reverseSuffix
}
// Straight copy-paste of encodeString from wrangler/keyspace.go. I want to make
// this public, but it doesn't belong in package workflow. Maybe package sqltypes,
// or maybe package sqlescape?
func encodeString(in string) string {
buf := bytes.NewBuffer(nil)
sqltypes.NewVarChar(in).EncodeSQL(buf)
return buf.String()
}