-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
region_util.go
770 lines (717 loc) · 26.5 KB
/
region_util.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
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
// Copyright 2020 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package sql
import (
"context"
"sort"
"strings"
"github.com/cockroachdb/cockroach/pkg/config/zonepb"
"github.com/cockroachdb/cockroach/pkg/kv"
"github.com/cockroachdb/cockroach/pkg/sql/catalog"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/dbdesc"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/descpb"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/tabledesc"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgcode"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgerror"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/cockroach/pkg/sql/sessiondata"
"github.com/cockroachdb/errors"
"github.com/gogo/protobuf/proto"
)
const minNumRegionsForSurviveRegionGoal = 3
type liveClusterRegions map[descpb.RegionName]struct{}
func (s *liveClusterRegions) isActive(region descpb.RegionName) bool {
_, ok := (*s)[region]
return ok
}
func (s *liveClusterRegions) toStrings() []string {
ret := make([]string, 0, len(*s))
for region := range *s {
ret = append(ret, string(region))
}
sort.Slice(ret, func(i, j int) bool {
return ret[i] < ret[j]
})
return ret
}
// getLiveClusterRegions returns a set of live region names in the cluster.
// A region name is deemed active if there is at least one alive node
// in the cluster in with locality set to a given region.
func (p *planner) getLiveClusterRegions(ctx context.Context) (liveClusterRegions, error) {
rows, err := p.ExtendedEvalContext().ExecCfg.InternalExecutor.QueryEx(
ctx,
"get_live_cluster_regions",
p.txn,
sessiondata.InternalExecutorOverride{
User: p.SessionData().User(),
},
"SELECT region FROM [SHOW REGIONS FROM CLUSTER]",
)
if err != nil {
return nil, err
}
var ret liveClusterRegions = make(map[descpb.RegionName]struct{}, len(rows))
for _, row := range rows {
ret[descpb.RegionName(*row[0].(*tree.DString))] = struct{}{}
}
return ret, nil
}
// checkLiveClusterRegion checks whether a region can be added to a database
// based on whether the cluster regions are alive.
func checkLiveClusterRegion(liveClusterRegions liveClusterRegions, region descpb.RegionName) error {
if !liveClusterRegions.isActive(region) {
return errors.WithHintf(
pgerror.Newf(
pgcode.InvalidName,
"region %q does not exist",
region,
),
"valid regions: %s",
strings.Join(liveClusterRegions.toStrings(), ", "),
)
}
return nil
}
func makeRequiredConstraintForRegion(r descpb.RegionName) zonepb.Constraint {
return zonepb.Constraint{
Type: zonepb.Constraint_REQUIRED,
Key: "region",
Value: string(r),
}
}
// zoneConfigForMultiRegionDatabase generates a ZoneConfig stub for a
// multi-region database such that at least one replica (voting or non-voting)
// is constrained to each region defined within the given `regionConfig` and
// some voting replicas are constrained to the primary region of the database
// depending on its prescribed survivability goal.
//
// For instance, for a database with 4 regions: A (primary), B, C, D and region
// survivability. This method will generate a ZoneConfig object representing
// the following attributes:
// num_replicas = 5
// num_voters = 5
// constraints = '{"+region=A": 1,"+region=B": 1,"+region=C": 1,"+region=D": 1}'
// voter_constraints = '{"+region=A": 2}'
// lease_preferences = [["+region=A"]]
//
// See synthesizeVoterConstraints() for explanation on why `voter_constraints`
// are set the way they are.
func zoneConfigForMultiRegionDatabase(
regionConfig descpb.DatabaseDescriptor_RegionConfig,
) (*zonepb.ZoneConfig, error) {
numVoters, numReplicas := getNumVotersAndNumReplicas(regionConfig)
constraints := make([]zonepb.ConstraintsConjunction, len(regionConfig.Regions))
for i, region := range regionConfig.Regions {
// Constrain at least 1 (voting or non-voting) replica per region.
constraints[i] = zonepb.ConstraintsConjunction{
NumReplicas: 1,
Constraints: []zonepb.Constraint{makeRequiredConstraintForRegion(region.Name)},
}
}
voterConstraints, err := synthesizeVoterConstraints(regionConfig.PrimaryRegion, regionConfig)
if err != nil {
return nil, err
}
return &zonepb.ZoneConfig{
NumReplicas: &numReplicas,
NumVoters: &numVoters,
LeasePreferences: []zonepb.LeasePreference{
{Constraints: []zonepb.Constraint{makeRequiredConstraintForRegion(regionConfig.PrimaryRegion)}},
},
VoterConstraints: voterConstraints,
Constraints: constraints,
}, nil
}
// zoneConfigForMultiRegionPartition generates a ZoneConfig stub for a partition
// that belongs to a regional by row table in a multi-region database.
//
// At the table/partition level, the only attributes that are set are
// `num_voters`, `voter_constraints`, and `lease_preferences`. We expect that
// the attributes `num_replicas` and `constraints` will be inherited from the
// database level zone config.
func zoneConfigForMultiRegionPartition(
partitionRegion descpb.DatabaseDescriptor_RegionConfig_Region,
regionConfig descpb.DatabaseDescriptor_RegionConfig,
) (zonepb.ZoneConfig, error) {
numVoters, _ := getNumVotersAndNumReplicas(regionConfig)
zc := zonepb.NewZoneConfig()
voterConstraints, err := synthesizeVoterConstraints(partitionRegion.Name, regionConfig)
if err != nil {
return zonepb.ZoneConfig{}, err
}
zc.NumVoters = &numVoters
zc.InheritedVoterConstraints = false
zc.VoterConstraints = voterConstraints
zc.InheritedLeasePreferences = false
zc.LeasePreferences = []zonepb.LeasePreference{
{Constraints: []zonepb.Constraint{makeRequiredConstraintForRegion(partitionRegion.Name)}},
}
return *zc, err
}
// maxFailuresBeforeUnavailability returns the maximum number of individual
// failures that can be tolerated, among `numVoters` voting replicas, before a
// given range is unavailable.
func maxFailuresBeforeUnavailability(numVoters int32) int32 {
return ((numVoters + 1) / 2) - 1
}
// getNumVotersAndNumReplicas computes the number of voters and the total number
// of replicas needed for a given region config.
func getNumVotersAndNumReplicas(
regionConfig descpb.DatabaseDescriptor_RegionConfig,
) (numVoters, numReplicas int32) {
const numVotersForZoneSurvival = 3
// Under region survivability, we use 5 voting replicas to allow for a
// theoretical (2-2-1) voting replica configuration, where the primary region
// has 2 voting replicas and the next closest region has another 2. This
// allows for stable read/write latencies even under single node failures.
//
// TODO(aayush): Until we add allocator heuristics to coalesce voting replicas
// together based on their relative latencies to the leaseholder, we can't
// actually ensure that the region closest to the leaseholder has 2 voting
// replicas.
//
// Until the above TODO is addressed, the non-leaseholder voting replicas will
// be allowed to "float" around among the other regions in the database. They
// may or may not be placed geographically close to the leaseholder replica.
const numVotersForRegionSurvival = 5
numRegions := int32(len(regionConfig.Regions))
switch regionConfig.SurvivalGoal {
// NB: See mega-comment inside `synthesizeVoterConstraints()` for why these
// are set the way they are.
case descpb.SurvivalGoal_ZONE_FAILURE:
numVoters = numVotersForZoneSurvival
// <numVoters in the home region> + <1 replica for every other region>
numReplicas = (numVotersForZoneSurvival) + (numRegions - 1)
case descpb.SurvivalGoal_REGION_FAILURE:
// <(quorum - 1) voters in the home region> + <1 replica for every other
// region>
numVoters = numVotersForRegionSurvival
// We place the maximum concurrent replicas that can fail before a range
// outage in the home region, and ensure that there's at least one replica
// in all other regions.
numReplicas = maxFailuresBeforeUnavailability(numVotersForRegionSurvival) + (numRegions - 1)
if numReplicas < numVoters {
// NumReplicas cannot be less than NumVoters. If we have <= 4 regions, all
// replicas will be voting replicas.
numReplicas = numVoters
}
}
return numVoters, numReplicas
}
// synthesizeVoterConstraints generates a ConstraintsConjunction clause
// representing the `voter_constraints` field to be set for the primary region
// of a multi-region database or the home region of a table in such a database.
//
// Under zone survivability, we will constrain all voting replicas to be inside
// the primary/home region.
//
// Under region survivability, we will constrain exactly <quorum - 1> voting
// replicas in the primary/home region.
func synthesizeVoterConstraints(
region descpb.RegionName, regionConfig descpb.DatabaseDescriptor_RegionConfig,
) ([]zonepb.ConstraintsConjunction, error) {
numVoters, _ := getNumVotersAndNumReplicas(regionConfig)
switch regionConfig.SurvivalGoal {
case descpb.SurvivalGoal_ZONE_FAILURE:
return []zonepb.ConstraintsConjunction{
{
// We don't specify `NumReplicas` here to indicate that we want _all_
// voting replicas to be constrained to this one region.
//
// Constraining all voting replicas to be inside the primary/home region
// is necessary and sufficient to ensure zone survivability, even though
// it might appear that these zone configs don't seem to spell out the
// requirement of being resilient to zone failures. This is because, by
// default, the allocator (see kv/kvserver/allocator.go) will maximize
// survivability due to it's diversity heuristic (see
// Locality.DiversityScore()) by spreading the replicas of a range
// across nodes with the most mutual difference in their locality
// hierarchies.
//
// For instance, in a 2 region deployment, each with 3 AZs, this is
// expected to result in a configuration like the following:
//
// +---- Region A -----+ +---- Region B -----+
// | | | |
// | +------------+ | | +------------+ |
// | | VOTER | | | | | |
// | | | | | | | |
// | +------------+ | | +------------+ |
// | +------------+ | | +------------+ |
// | | VOTER | | | | | |
// | | | | | | NON-VOTER | |
// | +------------+ | | | | |
// | +------------+ | | +------------+ |
// | | | | | +------------+ |
// | | VOTER | | | | | |
// | | | | | | | |
// | +------------+ | | +------------+ |
// +-------------------+ +-------------------+
//
Constraints: []zonepb.Constraint{makeRequiredConstraintForRegion(region)},
},
}, nil
case descpb.SurvivalGoal_REGION_FAILURE:
return []zonepb.ConstraintsConjunction{
{
// We constrain <quorum - 1> voting replicas to the primary region and
// allow the rest to "float" around. This allows the allocator inside KV
// to make dynamic placement decisions for the voting replicas that lie
// outside the primary/home region.
//
// It might appear that constraining just <quorum - 1> voting replicas
// to the primary region leaves open the possibility of a majority
// quorum coalescing inside of some other region. However, similar to
// the case above, the diversity heuristic in the allocator prevents
// this from happening as it will spread the unconstrained replicas out
// across nodes with the most diverse locality hierarchies.
//
// For instance, in a 3 region deployment (minimum for a database with
// "region" survivability), each with 3 AZs, we'd expect to see a
// configuration like the following:
//
// +---- Region A ------+ +---- Region B -----+ +----- Region C -----+
// | | | | | |
// | +------------+ | | +------------+ | | +------------+ |
// | | VOTER | | | | VOTER | | | | | |
// | | | | | | | | | | | |
// | +------------+ | | +------------+ | | +------------+ |
// | +------------+ | | +------------+ | | +------------+ |
// | | | | | | VOTER | | | | VOTER | |
// | | | | | | | | | | | |
// | +------------+ | | +------------+ | | +------------+ |
// | +------------+ | | +------------+ | | +------------+ |
// | | VOTER | | | | | | | | | |
// | | | | | | | | | | | |
// | +------------+ | | +------------+ | | +------------+ |
// +--------------------+ +-------------------+ +--------------------+
//
NumReplicas: maxFailuresBeforeUnavailability(numVoters),
Constraints: []zonepb.Constraint{makeRequiredConstraintForRegion(region)},
},
}, nil
default:
return nil, errors.AssertionFailedf("unknown survival goal: %v", regionConfig.SurvivalGoal)
}
}
var multiRegionZoneConfigFields = []tree.Name{
"global_reads",
"num_replicas",
"num_voters",
"constraints",
"voter_constraints",
"lease_preferences",
}
// zoneConfigForMultiRegionTable generates a ZoneConfig stub for a
// regional-by-table or global table in a multi-region database.
//
// At the table/partition level, the only attributes that are set are
// `num_voters`, `voter_constraints`, and `lease_preferences`. We expect that
// the attributes `num_replicas` and `constraints` will be inherited from the
// database level zone config.
//
// This function can return a nil zonepb.ZoneConfig, meaning no table level zone
// configuration is required.
//
// Relevant multi-region configured fields (as defined in
// `multiRegionZoneConfigFields`) will be overwritten by the calling function
// into an existing ZoneConfig.
func zoneConfigForMultiRegionTable(
localityConfig descpb.TableDescriptor_LocalityConfig,
regionConfig descpb.DatabaseDescriptor_RegionConfig,
) (*zonepb.ZoneConfig, error) {
// We only care about NumVoters here at the table level. NumReplicas is set at
// the database level, not at the table/partition level.
numVoters, _ := getNumVotersAndNumReplicas(regionConfig)
ret := zonepb.NewZoneConfig()
switch l := localityConfig.Locality.(type) {
case *descpb.TableDescriptor_LocalityConfig_Global_:
// Enable non-blocking transactions.
ret.GlobalReads = proto.Bool(true)
// Inherit voter_constraints and lease preferences from the database. We do
// nothing here because `NewZoneConfig()` already marks those fields as
// 'inherited'.
case *descpb.TableDescriptor_LocalityConfig_RegionalByTable_:
// Use the same configuration as the database and return nil here.
if l.RegionalByTable.Region == nil {
return ret, nil
}
preferredRegion := *l.RegionalByTable.Region
voterConstraints, err := synthesizeVoterConstraints(preferredRegion, regionConfig)
if err != nil {
return nil, err
}
ret.NumVoters = &numVoters
ret.InheritedVoterConstraints = false
ret.VoterConstraints = voterConstraints
ret.InheritedLeasePreferences = false
ret.LeasePreferences = []zonepb.LeasePreference{
{Constraints: []zonepb.Constraint{makeRequiredConstraintForRegion(preferredRegion)}},
}
case *descpb.TableDescriptor_LocalityConfig_RegionalByRow_:
// We purposely do not set anything here at table level - this should be done at
// partition level instead.
return ret, nil
}
return ret, nil
}
// This removes the requirement to only call this function after writeSchemaChange
// is called on creation of tables, and potentially removes the need for ReadingOwnWrites
// for some subcommands.
// Requires some logic to "inherit" from parents.
func applyZoneConfigForMultiRegion(
ctx context.Context,
zc *zonepb.ZoneConfig,
targetID descpb.ID,
table catalog.TableDescriptor,
txn *kv.Txn,
execConfig *ExecutorConfig,
) error {
// TODO (multiregion): Much like applyZoneConfigForMultiRegionTable we need to
// merge the zone config that we're writing with anything previously existing
// in there.
if _, err := writeZoneConfig(
ctx,
txn,
targetID,
table,
zc,
execConfig,
true, /* hasNewSubzones */
); err != nil {
return err
}
return nil
}
// applyZoneConfigForMultiRegionTableOption is an option that can be passed into
// applyZoneConfigForMultiRegionTable.
type applyZoneConfigForMultiRegionTableOption func(
zoneConfig zonepb.ZoneConfig,
regionConfig descpb.DatabaseDescriptor_RegionConfig,
table catalog.TableDescriptor,
) (hasNewSubzones bool, newZoneConfig zonepb.ZoneConfig, err error)
// applyZoneConfigForMultiRegionTableOptionNewIndexes applies table zone configs
// for a newly added index which requires partitioning of individual indexes.
func applyZoneConfigForMultiRegionTableOptionNewIndexes(
indexIDs ...descpb.IndexID,
) applyZoneConfigForMultiRegionTableOption {
return func(
zoneConfig zonepb.ZoneConfig,
regionConfig descpb.DatabaseDescriptor_RegionConfig,
table catalog.TableDescriptor,
) (hasNewSubzones bool, newZoneConfig zonepb.ZoneConfig, err error) {
for _, indexID := range indexIDs {
for _, region := range regionConfig.Regions {
zc, err := zoneConfigForMultiRegionPartition(region, regionConfig)
if err != nil {
return false, zoneConfig, err
}
zoneConfig.SetSubzone(zonepb.Subzone{
IndexID: uint32(indexID),
PartitionName: string(region.Name),
Config: zc,
})
}
}
return true, zoneConfig, nil
}
}
// isPlaceholderZoneConfigForMultiRegion returns whether a given zone config
// should be marked as a placeholder config for a multi-region object.
// See zonepb.IsSubzonePlaceholder for why this is necessary.
func isPlaceholderZoneConfigForMultiRegion(zc zonepb.ZoneConfig) bool {
// Strip Subzones / SubzoneSpans, as these may contain items if migrating
// from one REGIONAL BY ROW table to another.
strippedZC := zc
strippedZC.Subzones, strippedZC.SubzoneSpans = nil, nil
return strippedZC.Equal(zonepb.NewZoneConfig())
}
// applyZoneConfigForMultiRegionTableOptionTableNewConfig applies table zone
// configs on the entire table with the given new locality config.
func applyZoneConfigForMultiRegionTableOptionTableNewConfig(
newConfig descpb.TableDescriptor_LocalityConfig,
) applyZoneConfigForMultiRegionTableOption {
return func(
zc zonepb.ZoneConfig,
regionConfig descpb.DatabaseDescriptor_RegionConfig,
table catalog.TableDescriptor,
) (bool, zonepb.ZoneConfig, error) {
localityZoneConfig, err := zoneConfigForMultiRegionTable(
newConfig,
regionConfig,
)
if err != nil {
return false, zonepb.ZoneConfig{}, err
}
zc.CopyFromZone(*localityZoneConfig, multiRegionZoneConfigFields)
return false, zc, nil
}
}
// ApplyZoneConfigForMultiRegionTableOptionTableAndIndexes applies table zone configs
// on the entire table as well as its indexes, replacing multi-region related zone
// configuration fields.
var ApplyZoneConfigForMultiRegionTableOptionTableAndIndexes = func(
zc zonepb.ZoneConfig,
regionConfig descpb.DatabaseDescriptor_RegionConfig,
table catalog.TableDescriptor,
) (bool, zonepb.ZoneConfig, error) {
localityConfig := *table.GetLocalityConfig()
localityZoneConfig, err := zoneConfigForMultiRegionTable(
localityConfig,
regionConfig,
)
if err != nil {
return false, zonepb.ZoneConfig{}, err
}
zc.CopyFromZone(*localityZoneConfig, multiRegionZoneConfigFields)
hasNewSubzones := table.IsLocalityRegionalByRow()
if hasNewSubzones {
for _, region := range regionConfig.Regions {
subzoneConfig, err := zoneConfigForMultiRegionPartition(region, regionConfig)
if err != nil {
return false, zc, err
}
for _, idx := range table.NonDropIndexes() {
zc.SetSubzone(zonepb.Subzone{
IndexID: uint32(idx.GetID()),
PartitionName: string(region.Name),
Config: subzoneConfig,
})
}
}
}
return hasNewSubzones, zc, nil
}
// ApplyZoneConfigForMultiRegionTable applies zone config settings based
// on the options provided.
func ApplyZoneConfigForMultiRegionTable(
ctx context.Context,
txn *kv.Txn,
execCfg *ExecutorConfig,
regionConfig descpb.DatabaseDescriptor_RegionConfig,
table catalog.TableDescriptor,
opts ...applyZoneConfigForMultiRegionTableOption,
) error {
tableID := table.GetID()
zoneRaw, err := getZoneConfigRaw(ctx, txn, execCfg.Codec, tableID)
if err != nil {
return err
}
var zoneConfig zonepb.ZoneConfig
if zoneRaw != nil {
zoneConfig = *zoneRaw
}
var hasNewSubzones bool
for _, opt := range opts {
newHasNewSubzones, newZoneConfig, err := opt(
zoneConfig,
regionConfig,
table,
)
if err != nil {
return err
}
hasNewSubzones = newHasNewSubzones || hasNewSubzones
zoneConfig = newZoneConfig
}
// Mark the NumReplicas as 0 if we have subzones but no other features
// in the zone config. This signifies a placeholder.
if len(zoneConfig.Subzones) > 0 && isPlaceholderZoneConfigForMultiRegion(zoneConfig) {
zoneConfig.NumReplicas = proto.Int32(0)
}
if !zoneConfig.Equal(zonepb.NewZoneConfig()) {
if err := zoneConfig.Validate(); err != nil {
return pgerror.Newf(
pgcode.CheckViolation,
"could not validate zone config: %v",
err,
)
}
if err := zoneConfig.ValidateTandemFields(); err != nil {
return pgerror.Newf(
pgcode.CheckViolation,
"could not validate zone config: %v",
err,
)
}
// If we have fields that are not the default value, write in a new zone configuration
// value.
if _, err = writeZoneConfig(
ctx,
txn,
tableID,
table,
&zoneConfig,
execCfg,
hasNewSubzones,
); err != nil {
return err
}
} else if zoneRaw != nil {
// Delete the zone configuration if it exists but the new zone config is blank.
if _, err = execCfg.InternalExecutor.Exec(
ctx,
"delete-zone",
txn,
"DELETE FROM system.zones WHERE id = $1",
tableID,
); err != nil {
return err
}
}
return nil
}
// ApplyZoneConfigFromDatabaseRegionConfig applies a zone configuration to the
// database using the information in the supplied RegionConfig.
func ApplyZoneConfigFromDatabaseRegionConfig(
ctx context.Context,
dbID descpb.ID,
regionConfig descpb.DatabaseDescriptor_RegionConfig,
txn *kv.Txn,
execConfig *ExecutorConfig,
) error {
// Build a zone config based on the RegionConfig information.
dbZoneConfig, err := zoneConfigForMultiRegionDatabase(regionConfig)
if err != nil {
return err
}
return applyZoneConfigForMultiRegion(
ctx,
dbZoneConfig,
dbID,
nil,
txn,
execConfig,
)
}
// forEachTableWithLocalityConfigInDatabase loops through each schema and table
// for a table with a LocalityConfig configured.
// NOTE: this function uses cached table and schema descriptors. As a result, it may
// not be safe to run within a schema change.
func (p *planner) forEachTableWithLocalityConfigInDatabase(
ctx context.Context,
desc *dbdesc.Mutable,
f func(ctx context.Context, schema string, tbName tree.TableName, tbDesc *tabledesc.Mutable) error,
) error {
// No work to be done if the database isn't a multi-region database.
if !desc.IsMultiRegion() {
return nil
}
lookupFlags := p.CommonLookupFlags(true /*required*/)
lookupFlags.AvoidCached = false
schemas, err := p.Descriptors().GetSchemasForDatabase(ctx, p.txn, desc.GetID())
if err != nil {
return err
}
tblLookupFlags := p.CommonLookupFlags(true /*required*/)
tblLookupFlags.AvoidCached = false
tblLookupFlags.Required = false
// Loop over all schemas, then loop over all tables.
for _, schema := range schemas {
tbNames, err := p.Descriptors().GetObjectNames(
ctx,
p.txn,
desc,
schema,
tree.DatabaseListFlags{
CommonLookupFlags: lookupFlags,
ExplicitPrefix: true,
},
)
if err != nil {
return err
}
for i := range tbNames {
found, tbDesc, err := p.Descriptors().GetMutableTableByName(
ctx, p.txn, &tbNames[i], tree.ObjectLookupFlags{CommonLookupFlags: tblLookupFlags},
)
if err != nil {
return err
}
// If we couldn't find the table, or it has no LocalityConfig, there's nothing
// to do here.
if !found || tbDesc.LocalityConfig == nil {
continue
}
if err := f(ctx, schema, tbNames[i], tbDesc); err != nil {
return err
}
}
}
return nil
}
// updateZoneConfigsForAllTables loops through all of the tables in the
// specified database and refreshes the zone configs for all tables.
func (p *planner) updateZoneConfigsForAllTables(ctx context.Context, desc *dbdesc.Mutable) error {
return p.forEachTableWithLocalityConfigInDatabase(
ctx,
desc,
func(ctx context.Context, schema string, tbName tree.TableName, tbDesc *tabledesc.Mutable) error {
return ApplyZoneConfigForMultiRegionTable(
ctx,
p.txn,
p.ExecCfg(),
*desc.RegionConfig,
tbDesc,
ApplyZoneConfigForMultiRegionTableOptionTableAndIndexes,
)
},
)
}
// initializeMultiRegionDatabase initializes a multi-region database by creating
// the multi-region enum and the database-level zone configuration.
func (p *planner) initializeMultiRegionDatabase(ctx context.Context, desc *dbdesc.Mutable) error {
// If the database is not a multi-region database, there's no work to be done.
if !desc.IsMultiRegion() {
return nil
}
// Create the multi-region enum.
regionLabels := make(tree.EnumValueList, 0, len(desc.RegionConfig.Regions))
for _, region := range desc.RegionConfig.Regions {
regionLabels = append(regionLabels, tree.EnumValue(region.Name))
}
if err := p.createEnumWithID(
p.RunParams(ctx),
desc.RegionConfig.RegionEnumID,
regionLabels,
desc,
tree.NewQualifiedTypeName(desc.Name, tree.PublicSchema, tree.RegionEnum),
enumTypeMultiRegion,
); err != nil {
return err
}
// Create the database-level zone configuration.
if err := ApplyZoneConfigFromDatabaseRegionConfig(
ctx,
desc.ID,
*desc.RegionConfig,
p.txn,
p.execCfg); err != nil {
return err
}
return nil
}
// partitionByForRegionalByRow constructs the tree.PartitionBy clause for
// REGIONAL BY ROW tables.
func partitionByForRegionalByRow(
regionConfig descpb.DatabaseDescriptor_RegionConfig, col tree.Name,
) *tree.PartitionBy {
listPartition := make([]tree.ListPartition, len(regionConfig.Regions))
for i, region := range regionConfig.Regions {
listPartition[i] = tree.ListPartition{
Name: tree.UnrestrictedName(region.Name),
Exprs: tree.Exprs{tree.NewStrVal(string(region.Name))},
}
}
return &tree.PartitionBy{
Fields: tree.NameList{col},
List: listPartition,
}
}