generated from cybozu-go/neco-template
/
mysqlcluster_types.go
797 lines (658 loc) · 28.3 KB
/
mysqlcluster_types.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
package v1beta2
import (
"context"
"encoding/json"
"errors"
"fmt"
"github.com/cybozu-go/moco/pkg/constants"
"github.com/robfig/cron/v3"
corev1 "k8s.io/api/core/v1"
storagev1 "k8s.io/api/storage/v1"
"k8s.io/apimachinery/pkg/api/equality"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/validation/field"
corev1ac "k8s.io/client-go/applyconfigurations/core/v1"
"sigs.k8s.io/controller-runtime/pkg/client"
)
// EDIT THIS FILE! THIS IS SCAFFOLDING FOR YOU TO OWN!
// NOTE: json tags are required. Any new fields you add must have json tags for the fields to be serialized.
// MySQLClusterSpec defines the desired state of MySQLCluster
type MySQLClusterSpec struct {
// INSERT ADDITIONAL SPEC FIELDS - desired state of cluster
// Important: Run "make" to regenerate code after modifying this file
// Replicas is the number of instances. Available values are positive odd numbers.
// +kubebuilder:default=1
// +optional
Replicas int32 `json:"replicas,omitempty"`
// PodTemplate is a `Pod` template for MySQL server container.
PodTemplate PodTemplateSpec `json:"podTemplate"`
// VolumeClaimTemplates is a list of `PersistentVolumeClaim` templates for MySQL server container.
// A claim named "mysql-data" must be included in the list.
// +kubebuilder:validation:MinItems=1
VolumeClaimTemplates []PersistentVolumeClaim `json:"volumeClaimTemplates"`
// PrimaryServiceTemplate is a `Service` template for primary.
// +optional
PrimaryServiceTemplate *ServiceTemplate `json:"primaryServiceTemplate,omitempty"`
// ReplicaServiceTemplate is a `Service` template for replica.
// +optional
ReplicaServiceTemplate *ServiceTemplate `json:"replicaServiceTemplate,omitempty"`
// MySQLConfigMapName is a `ConfigMap` name of MySQL config.
// +nullable
// +optional
MySQLConfigMapName *string `json:"mysqlConfigMapName,omitempty"`
// ReplicationSourceSecretName is a `Secret` name which contains replication source info.
// If this field is given, the `MySQLCluster` works as an intermediate primary.
// +nullable
// +optional
ReplicationSourceSecretName *string `json:"replicationSourceSecretName,omitempty"`
// Collectors is the list of collector flag names of mysqld_exporter.
// If this field is not empty, MOCO adds mysqld_exporter as a sidecar to collect
// and export mysqld metrics in Prometheus format.
//
// See https://github.com/prometheus/mysqld_exporter/blob/master/README.md#collector-flags for flag names.
//
// Example: ["engine_innodb_status", "info_schema.innodb_metrics"]
// +optional
Collectors []string `json:"collectors,omitempty"`
// ServerIDBase, if set, will become the base number of server-id of each MySQL
// instance of this cluster. For example, if this is 100, the server-ids will be
// 100, 101, 102, and so on.
// If the field is not given or zero, MOCO automatically sets a random positive integer.
// +optional
ServerIDBase int32 `json:"serverIDBase,omitempty"`
// MaxDelaySeconds configures the readiness probe of mysqld container.
// For a replica mysqld instance, if it is delayed to apply transactions over this threshold,
// the mysqld instance will be marked as non-ready.
// The default is 60 seconds.
// Setting this field to 0 disables the delay check in the probe.
// +kubebuilder:validation:Minimum=0
// +kubebuilder:default=60
// +optional
MaxDelaySeconds int `json:"maxDelaySeconds,omitempty"`
// StartupWaitSeconds is the maximum duration to wait for `mysqld` container to start working.
// The default is 3600 seconds.
// +kubebuilder:validation:Minimum=0
// +kubebuilder:default=3600
// +optional
StartupWaitSeconds int32 `json:"startupWaitSeconds,omitempty"`
// LogRotationSchedule specifies the schedule to rotate MySQL logs.
// If not set, the default is to rotate logs every 5 minutes.
// See https://pkg.go.dev/github.com/robfig/cron/v3#hdr-CRON_Expression_Format for the field format.
// +optional
LogRotationSchedule string `json:"logRotationSchedule,omitempty"`
// The name of BackupPolicy custom resource in the same namespace.
// If this is set, MOCO creates a CronJob to take backup of this MySQL cluster periodically.
// +nullable
// +optional
BackupPolicyName *string `json:"backupPolicyName"`
// Restore is the specification to perform Point-in-Time-Recovery from existing cluster.
// If this field is not null, MOCO restores the data as specified and create a new
// cluster with the data. This field is not editable.
// +optional
Restore *RestoreSpec `json:"restore,omitempty"`
// DisableSlowQueryLogContainer controls whether to add a sidecar container named "slow-log"
// to output slow logs as the containers output.
// If set to true, the sidecar container is not added. The default is false.
// +optional
DisableSlowQueryLogContainer bool `json:"disableSlowQueryLogContainer,omitempty"`
}
func (s MySQLClusterSpec) validateCreate() field.ErrorList {
var allErrs field.ErrorList
p := field.NewPath("spec")
pp := p.Child("volumeClaimTemplates")
ok := false
for _, vc := range s.VolumeClaimTemplates {
if vc.Name == constants.MySQLDataVolumeName {
ok = true
break
}
}
if !ok {
allErrs = append(allErrs, field.Required(pp, fmt.Sprintf("required volume claim template %s is missing", constants.MySQLDataVolumeName)))
}
for _, vc := range s.VolumeClaimTemplates {
if vc.Spec.Resources == nil || vc.Spec.Resources.Requests == nil || vc.Spec.Resources.Requests.Storage() == nil {
allErrs = append(allErrs, field.Required(pp, fmt.Sprintf("required volume claim template %s storage requests is missing", vc.Name)))
}
}
pp = p.Child("serverIDBase")
if s.ServerIDBase <= 0 {
allErrs = append(allErrs, field.Invalid(pp, s.ServerIDBase, "serverIDBase must be a positive integer"))
}
pp = p.Child("logRotationSchedule")
if s.LogRotationSchedule != "" {
_, err := cron.ParseStandard(s.LogRotationSchedule)
if err != nil {
allErrs = append(allErrs, field.Invalid(pp, s.LogRotationSchedule, err.Error()))
}
}
pp = p.Child("replicas")
if s.Replicas%2 == 0 {
allErrs = append(allErrs, field.Invalid(pp, s.Replicas, "replicas must be a positive odd number"))
}
if s.Replicas <= 0 {
allErrs = append(allErrs, field.Invalid(pp, s.Replicas, "replicas must be a positive integer"))
}
p = p.Child("podTemplate", "spec")
pp = p.Child("containers")
mysqldIndex := -1
for i, container := range s.PodTemplate.Spec.Containers {
if container.Name == nil {
allErrs = append(allErrs, field.Forbidden(pp.Index(i), "container name is required"))
continue
}
if *container.Name == constants.MysqldContainerName {
mysqldIndex = i
}
if *container.Name == constants.AgentContainerName {
allErrs = append(allErrs, field.Forbidden(pp.Index(i), "reserved container name"))
}
if *container.Name == constants.SlowQueryLogAgentContainerName && !s.DisableSlowQueryLogContainer {
allErrs = append(allErrs, field.Forbidden(pp.Index(i), "reserved container name"))
}
if *container.Name == constants.ExporterContainerName && len(s.Collectors) > 0 {
allErrs = append(allErrs, field.Forbidden(pp.Index(i), "reserved container name"))
}
}
if mysqldIndex == -1 {
allErrs = append(allErrs, field.Required(pp, fmt.Sprintf("required container %s is missing", constants.MysqldContainerName)))
} else {
pp := p.Child("containers").Index(mysqldIndex).Child("ports")
for i, port := range s.PodTemplate.Spec.Containers[mysqldIndex].Ports {
if port.ContainerPort != nil {
switch *port.ContainerPort {
case constants.MySQLPort, constants.MySQLXPort, constants.MySQLAdminPort, constants.MySQLHealthPort:
allErrs = append(allErrs, field.Invalid(pp.Index(i), port.ContainerPort, "reserved port"))
}
}
if port.Name != nil {
switch *port.Name {
case constants.MySQLPortName, constants.MySQLXPortName, constants.MySQLAdminPortName, constants.MySQLHealthPortName:
allErrs = append(allErrs, field.Invalid(pp.Index(i), port.Name, "reserved port name"))
}
}
}
}
pp = p.Child("initContainers")
for i, container := range s.PodTemplate.Spec.InitContainers {
if container.Name == nil {
allErrs = append(allErrs, field.Forbidden(pp.Index(i), "init container name is required"))
continue
}
switch *container.Name {
case constants.InitContainerName:
allErrs = append(allErrs, field.Invalid(pp.Index(i), container.Name, "reserved init container name"))
}
}
pp = p.Child("volumes")
for i, vol := range s.PodTemplate.Spec.Volumes {
if vol.Name == nil {
continue
}
switch *vol.Name {
case constants.TmpVolumeName, constants.RunVolumeName, constants.VarLogVolumeName,
constants.MySQLConfVolumeName, constants.MySQLInitConfVolumeName,
constants.MySQLConfSecretVolumeName, constants.SlowQueryLogAgentConfigVolumeName:
allErrs = append(allErrs, field.Invalid(pp.Index(i), vol.Name, "reserved volume name"))
}
}
return allErrs
}
func (s MySQLClusterSpec) validateUpdate(ctx context.Context, apiReader client.Reader, old MySQLClusterSpec) field.ErrorList {
var allErrs field.ErrorList
p := field.NewPath("spec")
if s.Replicas < old.Replicas {
p := p.Child("replicas")
allErrs = append(allErrs, field.Forbidden(p, "decreasing replicas is not supported yet"))
}
if s.ReplicationSourceSecretName != nil {
p := p.Child("replicationSourceSecretName")
if old.ReplicationSourceSecretName == nil {
allErrs = append(allErrs, field.Forbidden(p, "replication can be initiated only with new clusters"))
} else if *s.ReplicationSourceSecretName != *old.ReplicationSourceSecretName {
allErrs = append(allErrs, field.Forbidden(p, "replication source secret name cannot be modified"))
}
}
if !equality.Semantic.DeepEqual(s.Restore, old.Restore) {
p := p.Child("restore")
allErrs = append(allErrs, field.Forbidden(p, "not editable"))
}
oldPVCSet := make(map[string]PersistentVolumeClaim)
for _, oldPVC := range old.VolumeClaimTemplates {
oldPVCSet[oldPVC.Name] = oldPVC
}
volumeExpansionTargetIndices := make([]int, 0)
for i, pvc := range s.VolumeClaimTemplates {
if old, ok := oldPVCSet[pvc.Name]; ok {
newSize := pvc.StorageSize()
oldSize := old.StorageSize()
switch cmp := newSize.Cmp(oldSize); {
case cmp == -1:
p := p.Child("volumeClaimTemplates").Index(i).
Child("spec").Child("resources").Child("requests").Key("storage")
allErrs = append(allErrs, field.Forbidden(p, "storage size cannot be reduced"))
case cmp == 1:
volumeExpansionTargetIndices = append(volumeExpansionTargetIndices, i)
case cmp == 0:
// noop
}
}
}
if len(volumeExpansionTargetIndices) > 0 {
allErrs = append(allErrs, s.validateVolumeExpansionSupported(ctx, apiReader, volumeExpansionTargetIndices)...)
}
return append(allErrs, s.validateCreate()...)
}
func (s MySQLClusterSpec) validateVolumeExpansionSupported(ctx context.Context, apiReader client.Reader, targetIndices []int) field.ErrorList {
var allErrs field.ErrorList
p := field.NewPath("spec").Child("volumeClaimTemplates")
for _, idx := range targetIndices {
pvc := s.VolumeClaimTemplates[idx]
if pvc.Spec.StorageClassName != nil {
var sc storagev1.StorageClass
if err := apiReader.Get(ctx, types.NamespacedName{Name: *pvc.Spec.StorageClassName}, &sc); err != nil {
p := p.Index(idx).Child("spec").Child("storageClassName")
allErrs = append(allErrs, field.InternalError(p, fmt.Errorf("failed to get storage class %s: %w", *pvc.Spec.StorageClassName, err)))
} else {
if !isVolumeExpansionSupported(&sc) {
p := p.Index(idx).Child("spec").Child("storageClassName")
allErrs = append(allErrs, field.Forbidden(p, fmt.Sprintf("storage class %q is not allowed to expand volume", *pvc.Spec.StorageClassName)))
}
}
} else {
sc, err := getDefaultStorageClass(ctx, apiReader)
if err != nil {
p := p.Index(idx)
allErrs = append(allErrs, field.InternalError(p, fmt.Errorf("failed to get storage class: %w", err)))
} else {
if !isVolumeExpansionSupported(sc) {
p := p.Index(idx)
allErrs = append(allErrs, field.Forbidden(p, fmt.Sprintf("default storage class %q is not allowed to expand volume", sc.Name)))
}
}
}
}
return allErrs
}
func isVolumeExpansionSupported(sc *storagev1.StorageClass) bool {
if sc.AllowVolumeExpansion == nil {
return false
}
return *sc.AllowVolumeExpansion
}
func getDefaultStorageClass(ctx context.Context, client client.Reader) (*storagev1.StorageClass, error) {
var scs storagev1.StorageClassList
if err := client.List(ctx, &scs); err != nil {
return nil, err
}
for _, sc := range scs.Items {
if isDefaultStorageClass(&sc) {
return &sc, nil
}
}
return nil, errors.New("not found default storage class")
}
func isDefaultStorageClass(sc *storagev1.StorageClass) bool {
if len(sc.Annotations) == 0 {
return false
}
// refs: https://github.com/kubernetes/kubernetes/blob/v1.24.2/pkg/apis/storage/v1beta1/util/helpers.go
if sc.Annotations["storageclass.kubernetes.io/is-default-class"] == "true" ||
sc.Annotations["storageclass.beta.kubernetes.io/is-default-class"] == "true" {
return true
}
return false
}
// ObjectMeta is metadata of objects.
// This is partially copied from metav1.ObjectMeta.
type ObjectMeta struct {
// Name is the name of the object.
// +optional
Name string `json:"name,omitempty"`
// Labels is a map of string keys and values.
// +optional
Labels map[string]string `json:"labels,omitempty"`
// Annotations is a map of string keys and values.
// +optional
Annotations map[string]string `json:"annotations,omitempty"`
}
// PodSpecApplyConfiguration is the type defined to implement the DeepCopy method.
type PodSpecApplyConfiguration corev1ac.PodSpecApplyConfiguration
// DeepCopy is copying the receiver, creating a new PodSpecApplyConfiguration.
func (in *PodSpecApplyConfiguration) DeepCopy() *PodSpecApplyConfiguration {
out := new(PodSpecApplyConfiguration)
bytes, err := json.Marshal(in)
if err != nil {
panic("Failed to marshal")
}
err = json.Unmarshal(bytes, out)
if err != nil {
panic("Failed to unmarshal")
}
return out
}
// PodTemplateSpec describes the data a pod should have when created from a template.
// This is slightly modified from corev1.PodTemplateSpec.
type PodTemplateSpec struct {
// Standard object's metadata. The name in this metadata is ignored.
// +optional
ObjectMeta `json:"metadata,omitempty"`
// Specification of the desired behavior of the pod.
// The name of the MySQL server container in this spec must be `mysqld`.
Spec PodSpecApplyConfiguration `json:"spec"`
// OverwriteContainers overwrites the container definitions provided by default by the system.
// +optional
OverwriteContainers []OverwriteContainer `json:"overwriteContainers,omitempty"`
}
// OverwriteableContainerName is the name of the container.
// +kubebuilder:validation:Enum=agent;moco-init;slow-log;mysqld-exporter
type OverwriteableContainerName string
// String implements the fmt.Stringer interface.
func (c OverwriteableContainerName) String() string {
return string(c)
}
const (
AgentContainerName OverwriteableContainerName = constants.AgentContainerName
InitContainerName OverwriteableContainerName = constants.InitContainerName
SlowQueryLogAgentContainerName OverwriteableContainerName = constants.SlowQueryLogAgentContainerName
ExporterContainerName OverwriteableContainerName = constants.ExporterContainerName
)
// OverwriteContainer defines the container spec used for overwriting.
type OverwriteContainer struct {
// Name of the container to overwrite.
// +kubebuilder:validation:Required
Name OverwriteableContainerName `json:"name"`
// Resources is the container resource to be overwritten.
// +optional
Resources *ResourceRequirementsApplyConfiguration `json:"resources,omitempty"`
}
// ResourceRequirementsApplyConfiguration is the type defined to implement the DeepCopy method.
type ResourceRequirementsApplyConfiguration corev1ac.ResourceRequirementsApplyConfiguration
// DeepCopy is copying the receiver, creating a new OverwriteContainer.
func (in *ResourceRequirementsApplyConfiguration) DeepCopy() *ResourceRequirementsApplyConfiguration {
out := new(ResourceRequirementsApplyConfiguration)
bytes, err := json.Marshal(in)
if err != nil {
panic("Failed to marshal")
}
err = json.Unmarshal(bytes, out)
if err != nil {
panic("Failed to unmarshal")
}
return out
}
// PersistentVolumeClaimSpecApplyConfiguration is the type defined to implement the DeepCopy method.
type PersistentVolumeClaimSpecApplyConfiguration corev1ac.PersistentVolumeClaimSpecApplyConfiguration
// DeepCopy is copying the receiver, creating a new PersistentVolumeClaimSpecApplyConfiguration.
func (in *PersistentVolumeClaimSpecApplyConfiguration) DeepCopy() *PersistentVolumeClaimSpecApplyConfiguration {
out := new(PersistentVolumeClaimSpecApplyConfiguration)
bytes, err := json.Marshal(in)
if err != nil {
panic("Failed to marshal")
}
err = json.Unmarshal(bytes, out)
if err != nil {
panic("Failed to unmarshal")
}
return out
}
// PersistentVolumeClaim is a user's request for and claim to a persistent volume.
// This is slightly modified from corev1.PersistentVolumeClaim.
type PersistentVolumeClaim struct {
// Standard object's metadata.
ObjectMeta `json:"metadata"`
// Spec defines the desired characteristics of a volume requested by a pod author.
Spec PersistentVolumeClaimSpecApplyConfiguration `json:"spec"`
}
func (in PersistentVolumeClaim) StorageSize() resource.Quantity {
if in.Spec.Resources != nil && in.Spec.Resources.Requests != nil {
requests := *in.Spec.Resources.Requests
return requests[corev1.ResourceStorage]
}
return resource.Quantity{}
}
// ToCoreV1 converts the PersistentVolumeClaim to a PersistentVolumeClaimApplyConfiguration.
func (in PersistentVolumeClaim) ToCoreV1() *corev1ac.PersistentVolumeClaimApplyConfiguration {
// If you use this, the namespace will not be nil and will not match for "equality.Semantic.DeepEqual".
// claim := corev1ac.PersistentVolumeClaim(in.Name, "").
claim := &corev1ac.PersistentVolumeClaimApplyConfiguration{}
claim.WithName(in.Name).
WithLabels(in.Labels).
WithAnnotations(in.Annotations).
WithStatus(corev1ac.PersistentVolumeClaimStatus())
spec := corev1ac.PersistentVolumeClaimSpecApplyConfiguration(*in.Spec.DeepCopy())
claim.WithSpec(&spec)
if claim.Spec.VolumeMode == nil {
claim.Spec.WithVolumeMode(corev1.PersistentVolumeFilesystem)
}
claim.Status.WithPhase(corev1.ClaimPending)
return claim
}
// ServiceSpecApplyConfiguration is the type defined to implement the DeepCopy method.
type ServiceSpecApplyConfiguration corev1ac.ServiceSpecApplyConfiguration
// DeepCopy is copying the receiver, creating a new ServiceSpecApplyConfiguration.
func (in *ServiceSpecApplyConfiguration) DeepCopy() *ServiceSpecApplyConfiguration {
out := new(ServiceSpecApplyConfiguration)
bytes, err := json.Marshal(in)
if err != nil {
panic("Failed to marshal")
}
err = json.Unmarshal(bytes, out)
if err != nil {
panic("Failed to unmarshal")
}
return out
}
// ServiceTemplate defines the desired spec and annotations of Service
type ServiceTemplate struct {
// Standard object's metadata. Only `annotations` and `labels` are valid.
// +optional
ObjectMeta `json:"metadata,omitempty"`
// Spec is the ServiceSpec
// +optional
Spec *ServiceSpecApplyConfiguration `json:"spec,omitempty"`
}
// RestoreSpec represents a set of parameters for Point-in-Time Recovery.
type RestoreSpec struct {
// SourceName is the name of the source `MySQLCluster`.
// +kubebuilder:validation:MinLength=1
SourceName string `json:"sourceName"`
// SourceNamespace is the namespace of the source `MySQLCluster`.
// +kubebuilder:validation:MinLength=1
SourceNamespace string `json:"sourceNamespace"`
// RestorePoint is the target date and time to restore data.
// The format is RFC3339. e.g. "2006-01-02T15:04:05Z"
RestorePoint metav1.Time `json:"restorePoint"`
// Specifies parameters for restore Pod.
JobConfig `json:"jobConfig"`
}
// MySQLClusterStatus defines the observed state of MySQLCluster
type MySQLClusterStatus struct {
// INSERT ADDITIONAL STATUS FIELD - define observed state of cluster
// Important: Run "make" to regenerate code after modifying this file
// Conditions is an array of conditions.
// +optional
Conditions []MySQLClusterCondition `json:"conditions,omitempty"`
// CurrentPrimaryIndex is the index of the current primary Pod in StatefulSet.
// Initially, this is zero.
CurrentPrimaryIndex int `json:"currentPrimaryIndex"`
// SyncedReplicas is the number of synced instances including the primary.
// +optional
SyncedReplicas int `json:"syncedReplicas,omitempty"`
// ErrantReplicas is the number of instances that have errant transactions.
// +optional
ErrantReplicas int `json:"errantReplicas,omitempty"`
// ErrantReplicaList is the list of indices of errant replicas.
// +optional
ErrantReplicaList []int `json:"errantReplicaList,omitempty"`
// Backup is the status of the last successful backup.
// +optional
Backup BackupStatus `json:"backup"`
// RestoredTime is the time when the cluster data is restored.
// +optional
RestoredTime *metav1.Time `json:"restoredTime,omitempty"`
// Cloned indicates if the initial cloning from an external source has been completed.
// +optional
Cloned bool `json:"cloned,omitempty"`
// ReconcileInfo represents version information for reconciler.
// +optional
ReconcileInfo ReconcileInfo `json:"reconcileInfo"`
}
// MySQLClusterCondition defines the condition of MySQLCluster.
type MySQLClusterCondition struct {
// Type is the type of the condition.
Type MySQLClusterConditionType `json:"type"`
// Status is the status of the condition.
Status corev1.ConditionStatus `json:"status"`
// Reason is a one-word CamelCase reason for the condition's last transition.
// +optional
Reason string `json:"reason,omitempty"`
// Message is a human-readable message indicating details about last transition.
// +optional
Message string `json:"message,omitempty"`
// LastTransitionTime is the last time the condition transits from one status to another.
LastTransitionTime metav1.Time `json:"lastTransitionTime"`
}
// MySQLClusterConditionType is the type of MySQLCluster condition.
// +kubebuilder:validation:Enum=Initialized;Available;Healthy
type MySQLClusterConditionType string
// Valid values for MySQLClusterConditionType
const (
ConditionInitialized MySQLClusterConditionType = "Initialized"
ConditionAvailable MySQLClusterConditionType = "Available"
ConditionHealthy MySQLClusterConditionType = "Healthy"
)
// BackupStatus represents the status of the last successful backup.
type BackupStatus struct {
// The time of the backup. This is used to generate object keys of backup files in a bucket.
// +nullable
Time metav1.Time `json:"time"`
// Elapsed is the time spent on the backup.
Elapsed metav1.Duration `json:"elapsed"`
// SourceIndex is the ordinal of the backup source instance.
SourceIndex int `json:"sourceIndex"`
// SourceUUID is the `server_uuid` of the backup source instance.
SourceUUID string `json:"sourceUUID"`
// BinlogFilename is the binlog filename that the backup source instance was writing to
// at the backup.
BinlogFilename string `json:"binlogFilename"`
// GTIDSet is the GTID set of the full dump of database.
GTIDSet string `json:"gtidSet"`
// DumpSize is the size in bytes of a full dump of database stored in an object storage bucket.
DumpSize int64 `json:"dumpSize"`
// BinlogSize is the size in bytes of a tarball of binlog files stored in an object storage bucket.
BinlogSize int64 `json:"binlogSize"`
// WorkDirUsage is the max usage in bytes of the woking directory.
WorkDirUsage int64 `json:"workDirUsage"`
// Warnings are list of warnings from the last backup, if any.
// +nullable
Warnings []string `json:"warnings"`
}
// ReconcileInfo is the type to record the last reconciliation information.
type ReconcileInfo struct {
// Generation is the `metadata.generation` value of the last reconciliation.
// See also https://kubernetes.io/docs/tasks/extend-kubernetes/custom-resources/custom-resource-definitions/#status-subresource
// +optional
Generation int64 `json:"generation,omitempty"`
// ReconcileVersion is the version of the operator reconciler.
// +optional
ReconcileVersion int `json:"reconcileVersion"`
}
// +kubebuilder:object:root=true
// +kubebuilder:subresource:status
// +kubebuilder:printcolumn:name="Available",type="string",JSONPath=".status.conditions[?(@.type=='Available')].status"
// +kubebuilder:printcolumn:name="Healthy",type="string",JSONPath=".status.conditions[?(@.type=='Healthy')].status"
// +kubebuilder:printcolumn:name="Primary",type="integer",JSONPath=".status.currentPrimaryIndex"
// +kubebuilder:printcolumn:name="Synced replicas",type="integer",JSONPath=".status.syncedReplicas"
// +kubebuilder:printcolumn:name="Errant replicas",type="integer",JSONPath=".status.errantReplicas"
// +kubebuilder:printcolumn:name="Last backup",type="string",JSONPath=".status.backup.time"
// MySQLCluster is the Schema for the mysqlclusters API
type MySQLCluster struct {
metav1.TypeMeta `json:",inline"`
metav1.ObjectMeta `json:"metadata,omitempty"`
Spec MySQLClusterSpec `json:"spec,omitempty"`
Status MySQLClusterStatus `json:"status,omitempty"`
}
// PrefixedName returns "moco-<<metadata.name>>"
func (r *MySQLCluster) PrefixedName() string {
return "moco-" + r.Name
}
// PodName returns PrefixedName() + "-" + index
func (r *MySQLCluster) PodName(index int) string {
return fmt.Sprintf("%s-%d", r.PrefixedName(), index)
}
// UserSecretName returns the name of the Secret for users.
// This Secret is placed in the same namespace as r.
func (r *MySQLCluster) UserSecretName() string {
return "moco-" + r.Name
}
// MyCnfSecretName returns the name of the Secret for users.
// The contents are formatted for mysql commands (as my.cnf).
func (r *MySQLCluster) MyCnfSecretName() string {
return "moco-my-cnf-" + r.Name
}
// ControllerSecretName returns the name of the Secret for MOCO controller.
// This Secret is placed in the namespace of the controller.
func (r *MySQLCluster) ControllerSecretName() string {
return fmt.Sprintf("mysql-%s.%s", r.Namespace, r.Name)
}
// HeadlessServiceName returns the name of Service for StatefulSet.
func (r *MySQLCluster) HeadlessServiceName() string {
return r.PrefixedName()
}
// PrimaryServiceName returns the name of Service for the primary mysqld instance.
func (r *MySQLCluster) PrimaryServiceName() string {
return r.PrefixedName() + "-primary"
}
// ReplicaServiceName returns the name of Service for replica mysqld instances.
func (r *MySQLCluster) ReplicaServiceName() string {
return r.PrefixedName() + "-replica"
}
// PodHostname returns the hostname of a Pod with the given index.
func (r *MySQLCluster) PodHostname(index int) string {
return fmt.Sprintf("%s.%s.%s.svc", r.PodName(index), r.HeadlessServiceName(), r.Namespace)
}
// SlowQueryLogAgentConfigMapName returns the name of the slow query log agent config name.
func (r *MySQLCluster) SlowQueryLogAgentConfigMapName() string {
return fmt.Sprintf("moco-slow-log-agent-config-%s", r.Name)
}
// CertificateName returns the name of Certificate issued for moco-agent gRPC server.
// The Certificate will be created in the namespace of the controller.
//
// This is also the Secret name created from the Certificate.
func (r *MySQLCluster) CertificateName() string {
return fmt.Sprintf("moco-agent-%s.%s", r.Namespace, r.Name)
}
// GRPCSecretName returns the name of Secret of TLS server certificate for moco-agent.
// The Secret will be created in the MySQLCluster namespace.
func (r *MySQLCluster) GRPCSecretName() string {
return fmt.Sprintf("%s-grpc", r.PrefixedName())
}
// BackupCronJobName returns the name of CronJob for backup.
func (r *MySQLCluster) BackupCronJobName() string {
return fmt.Sprintf("moco-backup-%s", r.Name)
}
// BackupRoleName returns the name of Role/RoleBinding for backup.
func (r *MySQLCluster) BackupRoleName() string {
return fmt.Sprintf("moco-backup-%s", r.Name)
}
// RestoreJobName returns the name of Job for restoration.
func (r *MySQLCluster) RestoreJobName() string {
return fmt.Sprintf("moco-restore-%s", r.Name)
}
// RestoreRoleName returns the name of Role/RoleBinding for restoration.
func (r *MySQLCluster) RestoreRoleName() string {
return fmt.Sprintf("moco-restore-%s", r.Name)
}
//+kubebuilder:object:root=true
// MySQLClusterList contains a list of MySQLCluster
type MySQLClusterList struct {
metav1.TypeMeta `json:",inline"`
metav1.ListMeta `json:"metadata,omitempty"`
Items []MySQLCluster `json:"items"`
}
func init() {
SchemeBuilder.Register(&MySQLCluster{}, &MySQLClusterList{})
}