-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
Copy pathzone.go
852 lines (785 loc) · 28.6 KB
/
zone.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
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
// Copyright 2015 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 zonepb
import (
"bytes"
"fmt"
"strings"
"time"
"github.com/cockroachdb/cockroach/pkg/base"
"github.com/cockroachdb/cockroach/pkg/keys"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/sql/opt/cat"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/errors"
"github.com/gogo/protobuf/proto"
)
// Several ranges outside of the SQL keyspace are given special names so they
// can be targeted by zone configs.
const (
DefaultZoneName = "default"
LivenessZoneName = "liveness"
MetaZoneName = "meta"
SystemZoneName = "system"
TimeseriesZoneName = "timeseries"
TenantsZoneName = "tenants"
)
// NamedZones maps named zones to their pseudo-table ID that can be used to
// install an entry into the system.zones table.
var NamedZones = map[string]uint32{
DefaultZoneName: keys.RootNamespaceID,
LivenessZoneName: keys.LivenessRangesID,
MetaZoneName: keys.MetaRangesID,
SystemZoneName: keys.SystemRangesID,
TimeseriesZoneName: keys.TimeseriesRangesID,
TenantsZoneName: keys.TenantsRangesID,
}
// NamedZonesByID is the inverse of NamedZones: it maps pseudo-table IDs to
// their zone names.
var NamedZonesByID = func() map[uint32]string {
out := map[uint32]string{}
for name, id := range NamedZones {
out[id] = name
}
return out
}()
// ZoneSpecifierFromID creates a tree.ZoneSpecifier for the zone with the
// given ID.
func ZoneSpecifierFromID(
id uint32, resolveID func(id uint32) (parentID uint32, name string, err error),
) (tree.ZoneSpecifier, error) {
if name, ok := NamedZonesByID[id]; ok {
return tree.ZoneSpecifier{NamedZone: tree.UnrestrictedName(name)}, nil
}
parentID, name, err := resolveID(id)
if err != nil {
return tree.ZoneSpecifier{}, err
}
if parentID == keys.RootNamespaceID {
return tree.ZoneSpecifier{Database: tree.Name(name)}, nil
}
_, db, err := resolveID(parentID)
if err != nil {
return tree.ZoneSpecifier{}, err
}
return tree.ZoneSpecifier{
TableOrIndex: tree.TableIndexName{
Table: tree.MakeTableName(tree.Name(db), tree.Name(name)),
},
}, nil
}
// ResolveZoneSpecifier converts a zone specifier to the ID of most specific
// zone whose config applies.
func ResolveZoneSpecifier(
zs *tree.ZoneSpecifier,
resolveName func(parentID uint32, schemaID uint32, name string) (id uint32, err error),
) (uint32, error) {
// A zone specifier has one of 3 possible structures:
// - a predefined named zone;
// - a database name;
// - a table or index name.
if zs.NamedZone != "" {
if zs.NamedZone == DefaultZoneName {
return keys.RootNamespaceID, nil
}
if id, ok := NamedZones[string(zs.NamedZone)]; ok {
return id, nil
}
return 0, fmt.Errorf("%q is not a built-in zone", string(zs.NamedZone))
}
if zs.Database != "" {
return resolveName(keys.RootNamespaceID, keys.RootNamespaceID, string(zs.Database))
}
// Third case: a table or index name. We look up the table part here.
tn := &zs.TableOrIndex.Table
databaseID, err := resolveName(keys.RootNamespaceID, keys.RootNamespaceID, tn.Catalog())
if err != nil {
return 0, err
}
schemaID := uint32(keys.PublicSchemaID)
if tn.SchemaName != tree.PublicSchemaName {
schemaID, err = resolveName(databaseID, keys.RootNamespaceID, tn.Schema())
if err != nil {
return 0, err
}
}
tableID, err := resolveName(databaseID, schemaID, tn.Table())
if err != nil {
return 0, err
}
return tableID, err
}
func (c Constraint) String() string {
var str string
switch c.Type {
case Constraint_REQUIRED:
str += "+"
case Constraint_PROHIBITED:
str += "-"
}
if len(c.Key) > 0 {
str += c.Key + "="
}
str += c.Value
return str
}
// FromString populates the constraint from the constraint shorthand notation.
func (c *Constraint) FromString(short string) error {
if len(short) == 0 {
return fmt.Errorf("the empty string is not a valid constraint")
}
switch short[0] {
case '+':
c.Type = Constraint_REQUIRED
short = short[1:]
case '-':
c.Type = Constraint_PROHIBITED
short = short[1:]
default:
c.Type = Constraint_DEPRECATED_POSITIVE
}
parts := strings.Split(short, "=")
if len(parts) == 1 {
c.Value = parts[0]
} else if len(parts) == 2 {
c.Key = parts[0]
c.Value = parts[1]
} else {
return errors.Errorf("constraint needs to be in the form \"(key=)value\", not %q", short)
}
return nil
}
// NewZoneConfig is the zone configuration used when no custom
// config has been specified.
func NewZoneConfig() *ZoneConfig {
return &ZoneConfig{
InheritedConstraints: true,
InheritedVoterConstraints: true,
InheritedLeasePreferences: true,
}
}
// EmptyCompleteZoneConfig is the zone configuration where
// all fields are set but set to their respective zero values.
func EmptyCompleteZoneConfig() *ZoneConfig {
return &ZoneConfig{
NumReplicas: proto.Int32(0),
NumVoters: proto.Int32(0),
NumVotersConfiguredSeparately: false,
RangeMinBytes: proto.Int64(0),
RangeMaxBytes: proto.Int64(0),
GC: &GCPolicy{TTLSeconds: 0},
InheritedConstraints: true,
InheritedVoterConstraints: true,
InheritedLeasePreferences: true,
}
}
// DefaultZoneConfig is the default zone configuration used when no custom
// config has been specified.
func DefaultZoneConfig() ZoneConfig {
return ZoneConfig{
NumReplicas: proto.Int32(3),
RangeMinBytes: proto.Int64(128 << 20), // 128 MB
RangeMaxBytes: proto.Int64(512 << 20), // 512 MB
GC: &GCPolicy{
// Use 25 hours instead of the previous 24 to make users successful by
// default. Users desiring to take incremental backups every 24h may
// incorrectly assume that the previous default 24h was sufficient to do
// that. But the equation for incremental backups is:
// GC TTLSeconds >= (desired backup interval) + (time to perform incremental backup)
// We think most new users' incremental backups will complete within an
// hour, and larger clusters will have more experienced operators and will
// understand how to change these settings if needed.
TTLSeconds: 25 * 60 * 60,
},
}
}
// DefaultZoneConfigRef is the default zone configuration used when no custom
// config has been specified.
func DefaultZoneConfigRef() *ZoneConfig {
zoneConfig := DefaultZoneConfig()
return &zoneConfig
}
// DefaultSystemZoneConfig is the default zone configuration used when no custom
// config has been specified. The DefaultSystemZoneConfig is like the
// DefaultZoneConfig but has a replication factor of 5 instead of 3.
func DefaultSystemZoneConfig() ZoneConfig {
defaultSystemZoneConfig := DefaultZoneConfig()
defaultSystemZoneConfig.NumReplicas = proto.Int32(5)
return defaultSystemZoneConfig
}
// DefaultSystemZoneConfigRef is the default zone configuration used when no custom
// config has been specified.
func DefaultSystemZoneConfigRef() *ZoneConfig {
systemZoneConfig := DefaultSystemZoneConfig()
return &systemZoneConfig
}
// IsComplete returns whether all the fields are set.
func (z *ZoneConfig) IsComplete() bool {
return ((z.NumReplicas != nil) && (z.NumVoters != nil || !z.NumVotersConfiguredSeparately) &&
(z.RangeMinBytes != nil) && (z.RangeMaxBytes != nil) && (z.GC != nil) &&
(!z.InheritedVoterConstraints) && (!z.InheritedConstraints) &&
(!z.InheritedLeasePreferences))
}
// ValidateTandemFields returns an error if the ZoneConfig to be written
// specifies a configuration that could cause problems with the introduction
// of cascading zone configs.
func (z *ZoneConfig) ValidateTandemFields() error {
var numConstrainedRepls int32
for _, constraint := range z.Constraints {
numConstrainedRepls += constraint.NumReplicas
}
if numConstrainedRepls > 0 && z.NumReplicas == nil {
return fmt.Errorf("when per-replica constraints are set, num_replicas must be set as well")
}
var numConstrainedVoters int32
for _, constraint := range z.VoterConstraints {
numConstrainedVoters += constraint.NumReplicas
}
if numConstrainedVoters > 0 && z.NumVoters == nil {
return fmt.Errorf("when per-voter constraints are set, num_voters must be set as well")
}
if !z.NumVotersConfiguredSeparately && len(z.VoterConstraints) > 0 {
return fmt.Errorf("voter_constraints can not be set without explicitly setting num_voters as well")
}
if (z.RangeMinBytes != nil || z.RangeMaxBytes != nil) &&
(z.RangeMinBytes == nil || z.RangeMaxBytes == nil) {
return fmt.Errorf("range_min_bytes and range_max_bytes must be set together")
}
if z.NumVotersConfiguredSeparately {
if !z.InheritedLeasePreferences && z.InheritedVoterConstraints {
return fmt.Errorf("lease preferences can not be set unless the voter constraints are explicitly set as well")
}
} else if !z.InheritedLeasePreferences && z.InheritedConstraints {
return fmt.Errorf("lease preferences can not be set unless the constraints are explicitly set as well")
}
return nil
}
// Validate returns an error if the ZoneConfig specifies a known-dangerous or
// disallowed configuration.
func (z *ZoneConfig) Validate() error {
for _, s := range z.Subzones {
if err := s.Config.Validate(); err != nil {
return err
}
}
if z.NumReplicas != nil {
switch {
case *z.NumReplicas < 0:
return fmt.Errorf("at least one replica is required")
case *z.NumReplicas == 0:
if len(z.Subzones) > 0 {
// NumReplicas == 0 is allowed when this ZoneConfig is a subzone
// placeholder. See IsSubzonePlaceholder.
return nil
}
return fmt.Errorf("at least one replica is required")
case *z.NumReplicas == 2:
if !z.NumVotersConfiguredSeparately {
return fmt.Errorf("at least 3 replicas are required for multi-replica configurations")
}
}
}
if z.NumVotersConfiguredSeparately {
if z.NumVoters != nil {
switch {
case *z.NumVoters <= 0:
return fmt.Errorf("at least one voting replica is required")
case *z.NumVoters == 2:
return fmt.Errorf("at least 3 voting replicas are required for multi-replica configurations")
}
if z.NumReplicas != nil && *z.NumVoters > *z.NumReplicas {
return fmt.Errorf("num_voters cannot be greater than num_replicas")
}
}
} else {
if z.NumVoters != nil && *z.NumVoters > 0 {
// TODO(aayush): Remove panic before merging.
panic(fmt.Sprintf("programming error: cannot have positive value for `num_voters` (%d)"+
" when `num_voters_configured_separately` is false", *z.NumVoters))
}
}
if z.RangeMaxBytes != nil && *z.RangeMaxBytes < base.MinRangeMaxBytes {
return fmt.Errorf("RangeMaxBytes %d less than minimum allowed %d",
*z.RangeMaxBytes, base.MinRangeMaxBytes)
}
if z.RangeMinBytes != nil && *z.RangeMinBytes < 0 {
return fmt.Errorf("RangeMinBytes %d less than minimum allowed 0", *z.RangeMinBytes)
}
if z.RangeMinBytes != nil && z.RangeMaxBytes != nil && *z.RangeMinBytes >= *z.RangeMaxBytes {
return fmt.Errorf("RangeMinBytes %d is greater than or equal to RangeMaxBytes %d",
*z.RangeMinBytes, *z.RangeMaxBytes)
}
// Reserve the value 0 to potentially have some special meaning in the future,
// such as to disable GC.
if z.GC != nil && z.GC.TTLSeconds < 1 {
return fmt.Errorf("GC.TTLSeconds %d less than minimum allowed 1", z.GC.TTLSeconds)
}
for _, constraints := range z.Constraints {
for _, constraint := range constraints.Constraints {
if constraint.Type == Constraint_DEPRECATED_POSITIVE {
return fmt.Errorf("constraints must either be required (prefixed with a '+') or " +
"prohibited (prefixed with a '-')")
}
}
}
for _, constraints := range z.VoterConstraints {
for _, constraint := range constraints.Constraints {
if constraint.Type == Constraint_DEPRECATED_POSITIVE {
return fmt.Errorf("voter_constraints must be of type 'required' (prefixed with a '+')")
}
// TODO(aayush): Allowing these makes validating `voter_constraints`
// against `constraints` harder. Revisit this decision if need be.
if constraint.Type == Constraint_PROHIBITED {
return fmt.Errorf("voter_constraints cannot contain prohibitive constraints")
}
}
}
// We only need to further validate constraints if per-replica constraints
// are in use. The old style of constraints that apply to all replicas don't
// require validation.
if len(z.Constraints) > 1 || (len(z.Constraints) == 1 && z.Constraints[0].NumReplicas != 0) {
var numConstrainedRepls int64
for _, constraints := range z.Constraints {
if constraints.NumReplicas <= 0 {
return fmt.Errorf("constraints must apply to at least one replica")
}
numConstrainedRepls += int64(constraints.NumReplicas)
for _, constraint := range constraints.Constraints {
// TODO(a-robinson): Relax this constraint to allow prohibited replicas,
// as discussed on #23014.
if constraint.Type != Constraint_REQUIRED && z.NumReplicas != nil && constraints.NumReplicas != *z.NumReplicas {
return fmt.Errorf(
"only required constraints (prefixed with a '+') can be applied to a subset of replicas")
}
}
}
if z.NumReplicas != nil && numConstrainedRepls > int64(*z.NumReplicas) {
return fmt.Errorf("the number of replicas specified in constraints (%d) cannot be greater "+
"than the number of replicas configured for the zone (%d)",
numConstrainedRepls, *z.NumReplicas)
}
}
// If we have per replica constraints inside voter_constraints, make sure
// that the number of replicas adds up to less than the number of voters.
//
// NB: We intentionally allow the number of replicas constrained by
// `constraints` plus the number of voters constrained by `voter_constraints`
// to exceed num_voters.
// For instance, the following would be a valid zone configuration:
// num_replicas = 3
// num_voters = 3
// constraints = {"+region=A": 1, "+region=B": 1, "+region=C": 1}
// voter_constraints = {"+ssd": 3}
// In the current state of our zone config validation logic, allowing
// examples like the one shown above also allows the user walk themselves into
// unsatisfiable zone configurations like the following:
// num_replicas = 3
// num_voters = 3
// constraints = {"+region=A": 2. "+region=B": 1}
// voter_constraints = {"region=C": 2, "+region=D": 1}
//
// TODO(aayush): We could disallow examples like the one shown above by
// instead requiring that all the constraints inside `voter_constraints` must
// also be present in the `constraints` field. Revisit this decision if it
// makes things harder at the allocator level.
if len(z.VoterConstraints) > 1 || (len(z.VoterConstraints) == 1 && z.VoterConstraints[0].NumReplicas != 0) {
var numConstrainedRepls int64
for _, constraints := range z.VoterConstraints {
if constraints.NumReplicas <= 0 {
return fmt.Errorf("constraints must apply to at least one replica")
}
numConstrainedRepls += int64(constraints.NumReplicas)
}
if z.NumVotersConfiguredSeparately {
// NB: These nil checks are not required in production code but they are
// for testing as some tests run `Validate()` on incomplete zone configs.
if z.NumVoters != nil && numConstrainedRepls > int64(*z.NumVoters) {
return fmt.Errorf("the number of replicas specified in voter_constraints (%d) cannot be greater "+
"than the number of voters configured for the zone (%d)",
numConstrainedRepls, *z.NumVoters)
}
} else {
if z.NumReplicas != nil && numConstrainedRepls > int64(*z.NumReplicas) {
return fmt.Errorf("the number of replicas specified in constraints (%d) cannot be greater "+
"than the number of replicas configured for the zone (%d)",
numConstrainedRepls, *z.NumReplicas)
}
}
}
// Validate that `constraints` aren't incompatible with `voter_constraints`.
if err := validateVoterConstraintsCompatibility(z.VoterConstraints, z.Constraints); err != nil {
return err
}
for _, leasePref := range z.LeasePreferences {
if len(leasePref.Constraints) == 0 {
return fmt.Errorf("every lease preference must include at least one constraint")
}
for _, constraint := range leasePref.Constraints {
if constraint.Type == Constraint_DEPRECATED_POSITIVE {
return fmt.Errorf("lease preference constraints must either be required " +
"(prefixed with a '+') or prohibited (prefixed with a '-')")
}
}
}
return nil
}
// validateVoterConstraintsCompatibility cross-validates `voter_constraints`
// against `constraints` and ensures that nothing that is prohibited at the
// overall `constraints` level is required at the `voter_constraints` level,
// since this sort of incongruity will lead to an unsatisfiable zone
// configuration.
func validateVoterConstraintsCompatibility(
voterConstraints, overallConstraints []ConstraintsConjunction,
) error {
// We know that prohibitive constraints are not allowed under
// `voter_constraints`. Walk through overallConstraints to ensure that none of
// the prohibitive constraints conflict with the `required` constraints in
// voterConstraints.
for _, constraints := range overallConstraints {
for _, constraint := range constraints.Constraints {
if constraint.Type == Constraint_PROHIBITED {
for _, otherConstraints := range voterConstraints {
for _, otherConstraint := range otherConstraints.Constraints {
conflicting := otherConstraint.Value == constraint.Value && otherConstraint.Key == constraint.Key
if conflicting {
return fmt.Errorf("prohibitive constraint %s conflicts with voter_constraint %s", constraint, otherConstraint)
}
}
}
}
}
}
return nil
}
// InheritFromParent hydrates a zones missing fields from its parent.
func (z *ZoneConfig) InheritFromParent(parent *ZoneConfig) {
// Allow for subzonePlaceholders to inherit fields from parents if needed.
if z.NumReplicas == nil || (z.NumReplicas != nil && *z.NumReplicas == 0) {
if parent.NumReplicas != nil {
z.NumReplicas = proto.Int32(*parent.NumReplicas)
}
}
if z.NumVoters == nil || (z.NumVoters != nil && *z.NumVoters == 0) {
if parent.NumVoters != nil {
z.NumVoters = proto.Int32(*parent.NumVoters)
}
}
if z.RangeMinBytes == nil {
if parent.RangeMinBytes != nil {
z.RangeMinBytes = proto.Int64(*parent.RangeMinBytes)
}
}
if z.RangeMaxBytes == nil {
if parent.RangeMaxBytes != nil {
z.RangeMaxBytes = proto.Int64(*parent.RangeMaxBytes)
}
}
if z.GC == nil {
if parent.GC != nil {
tempGC := *parent.GC
z.GC = &tempGC
}
}
if z.InheritedConstraints {
if !parent.InheritedConstraints {
z.Constraints = parent.Constraints
z.InheritedConstraints = false
}
}
if z.InheritedVoterConstraints {
if !parent.InheritedVoterConstraints {
z.VoterConstraints = parent.VoterConstraints
z.InheritedVoterConstraints = false
}
}
if z.InheritedLeasePreferences {
if !parent.InheritedLeasePreferences {
z.LeasePreferences = parent.LeasePreferences
z.InheritedLeasePreferences = false
}
}
}
// CopyFromZone copies over the specified fields from the other zone.
func (z *ZoneConfig) CopyFromZone(other ZoneConfig, fieldList []tree.Name) {
for _, fieldName := range fieldList {
if fieldName == "num_replicas" {
z.NumReplicas = nil
if other.NumReplicas != nil {
z.NumReplicas = proto.Int32(*other.NumReplicas)
}
}
if fieldName == "num_voters" {
z.NumVoters = nil
if other.NumVoters != nil {
z.NumVoters = proto.Int32(*other.NumVoters)
z.NumVotersConfiguredSeparately = true
// TODO(aayush): Remove this panic once done with testing
if !other.NumVotersConfiguredSeparately {
panic(`NumVotersConfiguredSeparately was unexpectedly false when num_voters has an explicit value`)
}
}
}
if fieldName == "range_min_bytes" {
z.RangeMinBytes = nil
if other.RangeMinBytes != nil {
z.RangeMinBytes = proto.Int64(*other.RangeMinBytes)
}
}
if fieldName == "range_max_bytes" {
z.RangeMaxBytes = nil
if other.RangeMaxBytes != nil {
z.RangeMaxBytes = proto.Int64(*other.RangeMaxBytes)
}
}
if fieldName == "gc.ttlseconds" {
z.GC = nil
if other.GC != nil {
tempGC := *other.GC
z.GC = &tempGC
}
}
if fieldName == "constraints" {
z.Constraints = other.Constraints
z.InheritedConstraints = other.InheritedConstraints
}
if fieldName == "voter_constraints" {
z.VoterConstraints = other.VoterConstraints
z.InheritedVoterConstraints = other.InheritedVoterConstraints
}
if fieldName == "lease_preferences" {
z.LeasePreferences = other.LeasePreferences
z.InheritedLeasePreferences = other.InheritedLeasePreferences
}
}
}
// StoreSatisfiesConstraint checks whether a store satisfies the given constraint.
// If the constraint is of the PROHIBITED type, satisfying it means the store
// not matching the constraint's spec.
func StoreSatisfiesConstraint(store roachpb.StoreDescriptor, constraint Constraint) bool {
hasConstraint := StoreMatchesConstraint(store, constraint)
if (constraint.Type == Constraint_REQUIRED && !hasConstraint) ||
(constraint.Type == Constraint_PROHIBITED && hasConstraint) {
return false
}
return true
}
// StoreMatchesConstraint returns whether a store's attributes or node's
// locality match the constraint's spec. It notably ignores whether the
// constraint is required, prohibited, positive, or otherwise.
// Also see StoreSatisfiesConstraint().
func StoreMatchesConstraint(store roachpb.StoreDescriptor, c Constraint) bool {
if c.Key == "" {
for _, attrs := range []roachpb.Attributes{store.Attrs, store.Node.Attrs} {
for _, attr := range attrs.Attrs {
if attr == c.Value {
return true
}
}
}
return false
}
for _, tier := range store.Node.Locality.Tiers {
if c.Key == tier.Key && c.Value == tier.Value {
return true
}
}
return false
}
// DeleteTableConfig removes any configuration that applies to the table
// targeted by this ZoneConfig, leaving only its subzone configs, if any. After
// calling DeleteTableConfig, IsSubzonePlaceholder will return true.
//
// Only table zones can have subzones, so it does not make sense to call this
// method on non-table ZoneConfigs.
func (z *ZoneConfig) DeleteTableConfig() {
*z = ZoneConfig{
// Have to set NumReplicas to 0 so it is recognized as a placeholder.
NumReplicas: proto.Int32(0),
Subzones: z.Subzones,
SubzoneSpans: z.SubzoneSpans,
}
}
// IsSubzonePlaceholder returns whether the ZoneConfig exists only to store
// subzones. The configuration fields (e.g., RangeMinBytes) in a subzone
// placeholder should be ignored; instead, the configuration from the parent
// ZoneConfig applies.
func (z *ZoneConfig) IsSubzonePlaceholder() bool {
// A ZoneConfig with zero replicas is otherwise invalid, so we repurpose it to
// indicate that a ZoneConfig is a placeholder for subzones rather than
// introducing a dedicated IsPlaceholder flag.
// TODO(aayush): Decide whether its worth introducing a isPlaceholder flag to
// clean this up after num_voters is introduced.
return z.NumReplicas != nil && *z.NumReplicas == 0
}
// GetSubzone returns the most specific Subzone that applies to the specified
// index ID and partition, if any exists. The partition can be left unspecified
// to get the Subzone for an entire index, if it exists. indexID, however, must
// always be provided, even when looking for a partition's Subzone.
func (z *ZoneConfig) GetSubzone(indexID uint32, partition string) *Subzone {
for _, s := range z.Subzones {
if s.IndexID == indexID && s.PartitionName == partition {
copySubzone := s
return ©Subzone
}
}
if partition != "" {
return z.GetSubzone(indexID, "")
}
return nil
}
// GetSubzoneExact is similar to GetSubzone but does not find the most specific
// subzone that applies to a specified index and partition, as it finds either the
// exact config that applies, or returns nil.
func (z *ZoneConfig) GetSubzoneExact(indexID uint32, partition string) *Subzone {
for _, s := range z.Subzones {
if s.IndexID == indexID && s.PartitionName == partition {
copySubzone := s
return ©Subzone
}
}
return nil
}
// GetSubzoneForKeySuffix returns the ZoneConfig for the subzone that contains
// keySuffix, if it exists and its position in the subzones slice.
func (z ZoneConfig) GetSubzoneForKeySuffix(keySuffix []byte) (*Subzone, int32) {
// TODO(benesch): Use binary search instead.
for _, s := range z.SubzoneSpans {
// The span's Key is stored with the prefix removed, so we can compare
// directly to keySuffix. An unset EndKey implies Key.PrefixEnd().
if (s.Key.Compare(keySuffix) <= 0) &&
((s.EndKey == nil && bytes.HasPrefix(keySuffix, s.Key)) || s.EndKey.Compare(keySuffix) > 0) {
copySubzone := z.Subzones[s.SubzoneIndex]
return ©Subzone, s.SubzoneIndex
}
}
return nil, -1
}
// SetSubzone installs subzone into the ZoneConfig, overwriting any existing
// subzone with the same IndexID and PartitionName.
func (z *ZoneConfig) SetSubzone(subzone Subzone) {
for i, s := range z.Subzones {
if s.IndexID == subzone.IndexID && s.PartitionName == subzone.PartitionName {
z.Subzones[i] = subzone
return
}
}
z.Subzones = append(z.Subzones, subzone)
}
// DeleteSubzone removes the subzone with the specified index ID and partition.
// It returns whether it performed any work.
func (z *ZoneConfig) DeleteSubzone(indexID uint32, partition string) bool {
for i, s := range z.Subzones {
if s.IndexID == indexID && s.PartitionName == partition {
z.Subzones = append(z.Subzones[:i], z.Subzones[i+1:]...)
return true
}
}
return false
}
// DeleteIndexSubzones deletes all subzones that refer to the index with the
// specified ID. This includes subzones for partitions of the index as well as
// the index subzone itself.
func (z *ZoneConfig) DeleteIndexSubzones(indexID uint32) {
subzones := z.Subzones[:0]
for _, s := range z.Subzones {
if s.IndexID != indexID {
subzones = append(subzones, s)
}
}
z.Subzones = subzones
}
// SubzoneSplits returns the split points determined by a ZoneConfig's subzones.
func (z ZoneConfig) SubzoneSplits() []roachpb.RKey {
var out []roachpb.RKey
for _, span := range z.SubzoneSpans {
// TODO(benesch): avoid a split at the first partition's start key when it
// is the minimum possible value.
if len(out) == 0 || !out[len(out)-1].Equal(span.Key) {
// Only split at the start key when it differs from the last end key.
out = append(out, roachpb.RKey(span.Key))
}
endKey := span.EndKey
if len(endKey) == 0 {
endKey = span.Key.PrefixEnd()
}
out = append(out, roachpb.RKey(endKey))
// TODO(benesch): avoid a split at the last partition's end key when it is
// the maximum possible value.
}
return out
}
// ReplicaConstraintsCount is part of the cat.Zone interface.
//
// TODO(aayush): Go through the callers of the methods here and decide the right
// semantics.
func (z *ZoneConfig) ReplicaConstraintsCount() int {
return len(z.Constraints)
}
// ReplicaConstraints is part of the cat.Zone interface.
func (z *ZoneConfig) ReplicaConstraints(i int) cat.ReplicaConstraints {
return &z.Constraints[i]
}
// LeasePreferenceCount is part of the cat.Zone interface.
func (z *ZoneConfig) LeasePreferenceCount() int {
return len(z.LeasePreferences)
}
// LeasePreference is part of the cat.Zone interface.
func (z *ZoneConfig) LeasePreference(i int) cat.ConstraintSet {
return &z.LeasePreferences[i]
}
// ConstraintCount is part of the cat.LeasePreference interface.
func (l *LeasePreference) ConstraintCount() int {
return len(l.Constraints)
}
// Constraint is part of the cat.LeasePreference interface.
func (l *LeasePreference) Constraint(i int) cat.Constraint {
return &l.Constraints[i]
}
func (c ConstraintsConjunction) String() string {
var sb strings.Builder
for i, cons := range c.Constraints {
if i > 0 {
sb.WriteRune(',')
}
sb.WriteString(cons.String())
}
if c.NumReplicas != 0 {
fmt.Fprintf(&sb, ":%d", c.NumReplicas)
}
return sb.String()
}
// ReplicaCount is part of the cat.ReplicaConstraints interface.
func (c *ConstraintsConjunction) ReplicaCount() int32 {
return c.NumReplicas
}
// ConstraintCount is part of the cat.ReplicaConstraints interface.
func (c *ConstraintsConjunction) ConstraintCount() int {
return len(c.Constraints)
}
// Constraint is part of the cat.ReplicaConstraints interface.
func (c *ConstraintsConjunction) Constraint(i int) cat.Constraint {
return &c.Constraints[i]
}
// IsRequired is part of the cat.Constraint interface.
func (c *Constraint) IsRequired() bool {
return c.Type == Constraint_REQUIRED
}
// GetKey is part of the cat.Constraint interface.
func (c *Constraint) GetKey() string {
return c.Key
}
// GetValue is part of the cat.Constraint interface.
func (c *Constraint) GetValue() string {
return c.Value
}
// TTL returns the implies TTL as a time.Duration.
func (m *GCPolicy) TTL() time.Duration {
return time.Duration(m.TTLSeconds) * time.Second
}