-
Notifications
You must be signed in to change notification settings - Fork 2k
/
srv_keyspace.go
702 lines (622 loc) · 19.7 KB
/
srv_keyspace.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
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
/*
Copyright 2019 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 topo
import (
"bytes"
"encoding/hex"
"fmt"
"path"
"sync"
"github.com/golang/protobuf/proto"
"golang.org/x/net/context"
"vitess.io/vitess/go/vt/vterrors"
"vitess.io/vitess/go/vt/concurrency"
"vitess.io/vitess/go/vt/key"
"vitess.io/vitess/go/vt/topo/topoproto"
topodatapb "vitess.io/vitess/go/vt/proto/topodata"
)
// This file contains the utility methods to manage SrvKeyspace objects.
func srvKeyspaceFileName(keyspace string) string {
return path.Join(KeyspacesPath, keyspace, SrvKeyspaceFile)
}
// WatchSrvKeyspaceData is returned / streamed by WatchSrvKeyspace.
// The WatchSrvKeyspace API guarantees exactly one of Value or Err will be set.
type WatchSrvKeyspaceData struct {
Value *topodatapb.SrvKeyspace
Err error
}
// WatchSrvKeyspace will set a watch on the SrvKeyspace object.
// It has the same contract as Conn.Watch, but it also unpacks the
// contents into a SrvKeyspace object.
func (ts *Server) WatchSrvKeyspace(ctx context.Context, cell, keyspace string) (*WatchSrvKeyspaceData, <-chan *WatchSrvKeyspaceData, CancelFunc) {
conn, err := ts.ConnForCell(ctx, cell)
if err != nil {
return &WatchSrvKeyspaceData{Err: err}, nil, nil
}
filePath := srvKeyspaceFileName(keyspace)
current, wdChannel, cancel := conn.Watch(ctx, filePath)
if current.Err != nil {
return &WatchSrvKeyspaceData{Err: current.Err}, nil, nil
}
value := &topodatapb.SrvKeyspace{}
if err := proto.Unmarshal(current.Contents, value); err != nil {
// Cancel the watch, drain channel.
cancel()
for range wdChannel {
}
return &WatchSrvKeyspaceData{Err: vterrors.Wrapf(err, "error unpacking initial SrvKeyspace object")}, nil, nil
}
changes := make(chan *WatchSrvKeyspaceData, 10)
// The background routine reads any event from the watch channel,
// translates it, and sends it to the caller.
// If cancel() is called, the underlying Watch() code will
// send an ErrInterrupted and then close the channel. We'll
// just propagate that back to our caller.
go func() {
defer close(changes)
for wd := range wdChannel {
if wd.Err != nil {
// Last error value, we're done.
// wdChannel will be closed right after
// this, no need to do anything.
changes <- &WatchSrvKeyspaceData{Err: wd.Err}
return
}
value := &topodatapb.SrvKeyspace{}
if err := proto.Unmarshal(wd.Contents, value); err != nil {
cancel()
for range wdChannel {
}
changes <- &WatchSrvKeyspaceData{Err: vterrors.Wrapf(err, "error unpacking SrvKeyspace object")}
return
}
changes <- &WatchSrvKeyspaceData{Value: value}
}
}()
return &WatchSrvKeyspaceData{Value: value}, changes, cancel
}
// GetSrvKeyspaceNames returns the SrvKeyspace objects for a cell.
func (ts *Server) GetSrvKeyspaceNames(ctx context.Context, cell string) ([]string, error) {
conn, err := ts.ConnForCell(ctx, cell)
if err != nil {
return nil, err
}
children, err := conn.ListDir(ctx, KeyspacesPath, false /*full*/)
switch {
case err == nil:
return DirEntriesToStringArray(children), nil
case IsErrType(err, NoNode):
return nil, nil
default:
return nil, err
}
}
// GetShardServingCells returns cells where this shard is serving
func (ts *Server) GetShardServingCells(ctx context.Context, si *ShardInfo) (servingCells []string, err error) {
cells, err := ts.GetCellInfoNames(ctx)
if err != nil {
return nil, err
}
wg := sync.WaitGroup{}
rec := concurrency.AllErrorRecorder{}
servingCells = make([]string, 0)
var mu sync.Mutex
for _, cell := range cells {
wg.Add(1)
go func(cell, keyspace string) {
defer wg.Done()
srvKeyspace, err := ts.GetSrvKeyspace(ctx, cell, si.keyspace)
switch {
case err == nil:
for _, partition := range srvKeyspace.GetPartitions() {
for _, shardReference := range partition.ShardReferences {
if shardReference.GetName() == si.ShardName() {
func() {
mu.Lock()
defer mu.Unlock()
// Check that this cell hasn't been added already
for _, servingCell := range servingCells {
if servingCell == cell {
return
}
}
servingCells = append(servingCells, cell)
}()
}
}
}
case IsErrType(err, NoNode):
// NOOP
return
default:
rec.RecordError(err)
return
}
}(cell, si.Keyspace())
}
wg.Wait()
if rec.HasErrors() {
return nil, NewError(PartialResult, rec.Error().Error())
}
return servingCells, nil
}
// GetShardServingTypes returns served types for given shard across all cells
func (ts *Server) GetShardServingTypes(ctx context.Context, si *ShardInfo) (servingTypes []topodatapb.TabletType, err error) {
cells, err := ts.GetCellInfoNames(ctx)
if err != nil {
return nil, err
}
wg := sync.WaitGroup{}
rec := concurrency.AllErrorRecorder{}
servingTypes = make([]topodatapb.TabletType, 0)
var mu sync.Mutex
for _, cell := range cells {
wg.Add(1)
go func(cell, keyspace string) {
defer wg.Done()
srvKeyspace, err := ts.GetSrvKeyspace(ctx, cell, si.keyspace)
switch {
case err == nil:
func() {
mu.Lock()
defer mu.Unlock()
for _, partition := range srvKeyspace.GetPartitions() {
partitionAlreadyAdded := false
for _, servingType := range servingTypes {
if servingType == partition.ServedType {
partitionAlreadyAdded = true
break
}
}
if !partitionAlreadyAdded {
for _, shardReference := range partition.ShardReferences {
if shardReference.GetName() == si.ShardName() {
servingTypes = append(servingTypes, partition.ServedType)
break
}
}
}
}
}()
case IsErrType(err, NoNode):
// NOOP
return
default:
rec.RecordError(err)
return
}
}(cell, si.Keyspace())
}
wg.Wait()
if rec.HasErrors() {
return nil, NewError(PartialResult, rec.Error().Error())
}
return servingTypes, nil
}
// AddSrvKeyspacePartitions adds partitions to srvKeyspace
func (ts *Server) AddSrvKeyspacePartitions(ctx context.Context, keyspace string, shards []*ShardInfo, tabletType topodatapb.TabletType, cells []string) (err error) {
if err = CheckKeyspaceLocked(ctx, keyspace); err != nil {
return err
}
// The caller intents to update all cells in this case
if len(cells) == 0 {
cells, err = ts.GetCellInfoNames(ctx)
if err != nil {
return err
}
}
wg := sync.WaitGroup{}
rec := concurrency.AllErrorRecorder{}
for _, cell := range cells {
wg.Add(1)
go func(cell string) {
defer wg.Done()
srvKeyspace, err := ts.GetSrvKeyspace(ctx, cell, keyspace)
switch {
case err == nil:
partitionFound := false
for _, partition := range srvKeyspace.GetPartitions() {
if partition.GetServedType() != tabletType {
continue
}
partitionFound = true
for _, si := range shards {
found := false
for _, shardReference := range partition.GetShardReferences() {
if key.KeyRangeEqual(shardReference.GetKeyRange(), si.GetKeyRange()) {
found = true
}
}
if !found {
shardReference := &topodatapb.ShardReference{
Name: si.ShardName(),
KeyRange: si.KeyRange,
}
partition.ShardReferences = append(partition.GetShardReferences(), shardReference)
}
}
}
// Partition does not exist at all, we need to create it
if !partitionFound {
partition := &topodatapb.SrvKeyspace_KeyspacePartition{
ServedType: tabletType,
}
shardReferences := make([]*topodatapb.ShardReference, 0)
for _, si := range shards {
shardReference := &topodatapb.ShardReference{
Name: si.ShardName(),
KeyRange: si.KeyRange,
}
shardReferences = append(shardReferences, shardReference)
}
partition.ShardReferences = shardReferences
srvKeyspace.Partitions = append(srvKeyspace.GetPartitions(), partition)
}
err = ts.UpdateSrvKeyspace(ctx, cell, keyspace, srvKeyspace)
if err != nil {
rec.RecordError(err)
return
}
case IsErrType(err, NoNode):
// NOOP
default:
rec.RecordError(err)
return
}
}(cell)
}
wg.Wait()
if rec.HasErrors() {
return NewError(PartialResult, rec.Error().Error())
}
return nil
}
// DeleteSrvKeyspacePartitions deletes shards from srvKeyspace partitions
func (ts *Server) DeleteSrvKeyspacePartitions(ctx context.Context, keyspace string, shards []*ShardInfo, tabletType topodatapb.TabletType, cells []string) (err error) {
if err = CheckKeyspaceLocked(ctx, keyspace); err != nil {
return err
}
// The caller intents to update all cells in this case
if len(cells) == 0 {
cells, err = ts.GetCellInfoNames(ctx)
if err != nil {
return err
}
}
wg := sync.WaitGroup{}
rec := concurrency.AllErrorRecorder{}
for _, cell := range cells {
wg.Add(1)
go func(cell string) {
defer wg.Done()
srvKeyspace, err := ts.GetSrvKeyspace(ctx, cell, keyspace)
switch {
case err == nil:
for _, partition := range srvKeyspace.GetPartitions() {
if partition.GetServedType() != tabletType {
continue
}
for _, si := range shards {
found := false
for _, shardReference := range partition.GetShardReferences() {
// Use shard name rather than key range so it works
// for both range-based and non-range-based shards.
if shardReference.GetName() == si.ShardName() {
found = true
}
}
if found {
shardReferences := make([]*topodatapb.ShardReference, 0)
for _, shardReference := range partition.GetShardReferences() {
// Use shard name rather than key range so it works
// for both range-based and non-range-based shards.
if shardReference.GetName() != si.ShardName() {
shardReferences = append(shardReferences, shardReference)
}
}
partition.ShardReferences = shardReferences
}
}
}
err = ts.UpdateSrvKeyspace(ctx, cell, keyspace, srvKeyspace)
if err != nil {
rec.RecordError(err)
return
}
case IsErrType(err, NoNode):
// NOOP
default:
rec.RecordError(err)
return
}
}(cell)
}
wg.Wait()
if rec.HasErrors() {
return NewError(PartialResult, rec.Error().Error())
}
return nil
}
// UpdateDisableQueryService will make sure the disableQueryService is
// set appropriately in tablet controls in srvKeyspace.
func (ts *Server) UpdateDisableQueryService(ctx context.Context, keyspace string, shards []*ShardInfo, tabletType topodatapb.TabletType, cells []string, disableQueryService bool) (err error) {
if err = CheckKeyspaceLocked(ctx, keyspace); err != nil {
return err
}
// The caller intents to update all cells in this case
if len(cells) == 0 {
cells, err = ts.GetCellInfoNames(ctx)
if err != nil {
return err
}
}
for _, shard := range shards {
for _, tc := range shard.TabletControls {
if len(tc.BlacklistedTables) > 0 {
return fmt.Errorf("cannot safely alter DisableQueryService as BlacklistedTables is set for shard %v", shard)
}
}
}
if !disableQueryService {
for _, si := range shards {
tc := si.GetTabletControl(tabletType)
if tc == nil {
continue
}
if tc.Frozen {
return fmt.Errorf("migrate has gone past the point of no return, cannot re-enable serving for %v/%v", si.keyspace, si.shardName)
}
}
}
wg := sync.WaitGroup{}
rec := concurrency.AllErrorRecorder{}
for _, cell := range cells {
wg.Add(1)
go func(cell string) {
defer wg.Done()
srvKeyspace, err := ts.GetSrvKeyspace(ctx, cell, keyspace)
switch {
case err == nil:
for _, partition := range srvKeyspace.GetPartitions() {
if partition.GetServedType() != tabletType {
continue
}
for _, si := range shards {
found := false
for _, tabletControl := range partition.GetShardTabletControls() {
if key.KeyRangeEqual(tabletControl.GetKeyRange(), si.GetKeyRange()) {
found = true
tabletControl.QueryServiceDisabled = disableQueryService
}
}
if !found {
shardTabletControl := &topodatapb.ShardTabletControl{
Name: si.ShardName(),
KeyRange: si.KeyRange,
QueryServiceDisabled: disableQueryService,
}
partition.ShardTabletControls = append(partition.GetShardTabletControls(), shardTabletControl)
}
}
}
err = ts.UpdateSrvKeyspace(ctx, cell, keyspace, srvKeyspace)
if err != nil {
rec.RecordError(err)
return
}
case IsErrType(err, NoNode):
// NOOP
default:
rec.RecordError(err)
return
}
}(cell)
}
wg.Wait()
if rec.HasErrors() {
return NewError(PartialResult, rec.Error().Error())
}
return nil
}
// MigrateServedType removes/adds shards from srvKeyspace when migrating a served type.
func (ts *Server) MigrateServedType(ctx context.Context, keyspace string, shardsToAdd, shardsToRemove []*ShardInfo, tabletType topodatapb.TabletType, cells []string) (err error) {
if err = CheckKeyspaceLocked(ctx, keyspace); err != nil {
return err
}
// The caller intents to update all cells in this case
if len(cells) == 0 {
cells, err = ts.GetCellInfoNames(ctx)
if err != nil {
return err
}
}
wg := sync.WaitGroup{}
rec := concurrency.AllErrorRecorder{}
for _, cell := range cells {
wg.Add(1)
go func(cell, keyspace string) {
defer wg.Done()
srvKeyspace, err := ts.GetSrvKeyspace(ctx, cell, keyspace)
switch {
case err == nil:
for _, partition := range srvKeyspace.GetPartitions() {
// We are finishing the migration, cleaning up tablet controls from the srvKeyspace
if tabletType == topodatapb.TabletType_MASTER {
partition.ShardTabletControls = nil
}
if partition.GetServedType() != tabletType {
continue
}
shardReferences := make([]*topodatapb.ShardReference, 0)
for _, shardReference := range partition.GetShardReferences() {
inShardsToRemove := false
for _, si := range shardsToRemove {
if key.KeyRangeEqual(shardReference.GetKeyRange(), si.GetKeyRange()) {
inShardsToRemove = true
break
}
}
if !inShardsToRemove {
shardReferences = append(shardReferences, shardReference)
}
}
for _, si := range shardsToAdd {
alreadyAdded := false
for _, shardReference := range partition.GetShardReferences() {
if key.KeyRangeEqual(shardReference.GetKeyRange(), si.GetKeyRange()) {
alreadyAdded = true
break
}
}
if !alreadyAdded {
shardReference := &topodatapb.ShardReference{
Name: si.ShardName(),
KeyRange: si.KeyRange,
}
shardReferences = append(shardReferences, shardReference)
}
}
partition.ShardReferences = shardReferences
}
if err := OrderAndCheckPartitions(cell, srvKeyspace); err != nil {
rec.RecordError(err)
return
}
err = ts.UpdateSrvKeyspace(ctx, cell, keyspace, srvKeyspace)
if err != nil {
rec.RecordError(err)
return
}
case IsErrType(err, NoNode):
// Assuming this cell is not active, nothing to do.
default:
if err != nil {
rec.RecordError(err)
return
}
}
}(cell, keyspace)
}
wg.Wait()
if rec.HasErrors() {
return NewError(PartialResult, rec.Error().Error())
}
return nil
}
// UpdateSrvKeyspace saves a new SrvKeyspace. It is a blind write.
func (ts *Server) UpdateSrvKeyspace(ctx context.Context, cell, keyspace string, srvKeyspace *topodatapb.SrvKeyspace) error {
conn, err := ts.ConnForCell(ctx, cell)
if err != nil {
return err
}
nodePath := srvKeyspaceFileName(keyspace)
data, err := proto.Marshal(srvKeyspace)
if err != nil {
return err
}
_, err = conn.Update(ctx, nodePath, data, nil)
return err
}
// DeleteSrvKeyspace deletes a SrvKeyspace.
func (ts *Server) DeleteSrvKeyspace(ctx context.Context, cell, keyspace string) error {
conn, err := ts.ConnForCell(ctx, cell)
if err != nil {
return err
}
nodePath := srvKeyspaceFileName(keyspace)
return conn.Delete(ctx, nodePath, nil)
}
// GetSrvKeyspaceAllCells returns the SrvKeyspace for all cells
func (ts *Server) GetSrvKeyspaceAllCells(ctx context.Context, keyspace string) ([]*topodatapb.SrvKeyspace, error) {
cells, err := ts.GetCellInfoNames(ctx)
if err != nil {
return nil, err
}
srvKeyspaces := make([]*topodatapb.SrvKeyspace, len(cells))
for _, cell := range cells {
srvKeyspace, err := ts.GetSrvKeyspace(ctx, cell, keyspace)
switch {
case err == nil:
srvKeyspaces = append(srvKeyspaces, srvKeyspace)
case IsErrType(err, NoNode):
// NOOP
default:
return srvKeyspaces, err
}
}
return srvKeyspaces, nil
}
// GetSrvKeyspace returns the SrvKeyspace for a cell/keyspace.
func (ts *Server) GetSrvKeyspace(ctx context.Context, cell, keyspace string) (*topodatapb.SrvKeyspace, error) {
conn, err := ts.ConnForCell(ctx, cell)
if err != nil {
return nil, err
}
nodePath := srvKeyspaceFileName(keyspace)
data, _, err := conn.Get(ctx, nodePath)
if err != nil {
return nil, err
}
srvKeyspace := &topodatapb.SrvKeyspace{}
if err := proto.Unmarshal(data, srvKeyspace); err != nil {
return nil, vterrors.Wrapf(err, "SrvKeyspace unmarshal failed: %v", data)
}
return srvKeyspace, nil
}
// OrderAndCheckPartitions will re-order the partition list, and check
// it's correct.
func OrderAndCheckPartitions(cell string, srvKeyspace *topodatapb.SrvKeyspace) error {
// now check them all
for _, partition := range srvKeyspace.Partitions {
tabletType := partition.ServedType
topoproto.ShardReferenceArray(partition.ShardReferences).Sort()
// check the first Start is MinKey, the last End is MaxKey,
// and the values in between match: End[i] == Start[i+1]
first := partition.ShardReferences[0]
if first.KeyRange != nil && len(first.KeyRange.Start) != 0 {
return fmt.Errorf("keyspace partition for %v in cell %v does not start with min key", tabletType, cell)
}
last := partition.ShardReferences[len(partition.ShardReferences)-1]
if last.KeyRange != nil && len(last.KeyRange.End) != 0 {
return fmt.Errorf("keyspace partition for %v in cell %v does not end with max key", tabletType, cell)
}
for i := range partition.ShardReferences[0 : len(partition.ShardReferences)-1] {
currShard := partition.ShardReferences[i]
nextShard := partition.ShardReferences[i+1]
currHasKeyRange := currShard.KeyRange != nil
nextHasKeyRange := nextShard.KeyRange != nil
if currHasKeyRange != nextHasKeyRange {
return fmt.Errorf("shards with inconsistent KeyRanges for %v in cell %v. shards: %v, %v", tabletType, cell, currShard, nextShard)
}
if !currHasKeyRange {
// this is the custom sharding case, all KeyRanges must be nil
continue
}
if !bytes.Equal(currShard.KeyRange.End, nextShard.KeyRange.Start) {
return fmt.Errorf("non-contiguous KeyRange values for %v in cell %v at shard %v to %v: %v != %v", tabletType, cell, i, i+1, hex.EncodeToString(currShard.KeyRange.End), hex.EncodeToString(nextShard.KeyRange.Start))
}
}
}
return nil
}
// ShardIsServing returns true if this shard is found in any of the partitions in the srvKeyspace
func ShardIsServing(srvKeyspace *topodatapb.SrvKeyspace, shard *topodatapb.Shard) bool {
for _, partition := range srvKeyspace.GetPartitions() {
for _, shardReference := range partition.GetShardReferences() {
if key.KeyRangeEqual(shardReference.GetKeyRange(), shard.GetKeyRange()) {
return true
}
}
}
return false
}