-
Notifications
You must be signed in to change notification settings - Fork 14
/
create.go
executable file
·1941 lines (1739 loc) · 68.7 KB
/
create.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
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright (C) 2022-2023 ApeCloud Co., Ltd
This file is part of KubeBlocks project
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package cluster
import (
"context"
"encoding/json"
"fmt"
"io"
"math"
"net/http"
"os"
"regexp"
"strconv"
"strings"
"github.com/apecloud/kubeblocks/pkg/controller/component"
"github.com/ghodss/yaml"
"github.com/robfig/cron/v3"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/cli-runtime/pkg/genericiooptions"
corev1ac "k8s.io/client-go/applyconfigurations/core/v1"
rbacv1ac "k8s.io/client-go/applyconfigurations/rbac/v1"
"k8s.io/client-go/dynamic"
"k8s.io/klog/v2"
cmdutil "k8s.io/kubectl/pkg/cmd/util"
utilcomp "k8s.io/kubectl/pkg/util/completion"
"k8s.io/kubectl/pkg/util/storage"
"k8s.io/kubectl/pkg/util/templates"
appsv1alpha1 "github.com/apecloud/kubeblocks/apis/apps/v1alpha1"
dpv1alpha1 "github.com/apecloud/kubeblocks/apis/dataprotection/v1alpha1"
"github.com/apecloud/kubeblocks/pkg/constant"
"github.com/apecloud/kubeblocks/pkg/dataprotection/restore"
dptypes "github.com/apecloud/kubeblocks/pkg/dataprotection/types"
"github.com/apecloud/kubeblocks/pkg/dataprotection/utils/boolptr"
viper "github.com/apecloud/kubeblocks/pkg/viperx"
"github.com/apecloud/kbcli/pkg/action"
"github.com/apecloud/kbcli/pkg/cluster"
classutil "github.com/apecloud/kbcli/pkg/cmd/class"
"github.com/apecloud/kbcli/pkg/printer"
"github.com/apecloud/kbcli/pkg/types"
"github.com/apecloud/kbcli/pkg/util"
)
var clusterCreateExample = templates.Examples(`
# Create a cluster with cluster definition apecloud-mysql and cluster version ac-mysql-8.0.30
kbcli cluster create mycluster --cluster-definition apecloud-mysql --cluster-version ac-mysql-8.0.30
# --cluster-definition is required, if --cluster-version is not specified, pick the most recently created version
kbcli cluster create mycluster --cluster-definition apecloud-mysql
# Output resource information in YAML format, without creation of resources.
kbcli cluster create mycluster --cluster-definition apecloud-mysql --dry-run -o yaml
# Output resource information in YAML format, the information will be sent to the server
# but the resources will not be actually created.
kbcli cluster create mycluster --cluster-definition apecloud-mysql --dry-run=server -o yaml
# Create a cluster and set termination policy DoNotTerminate that prevents the cluster from being deleted
kbcli cluster create mycluster --cluster-definition apecloud-mysql --termination-policy DoNotTerminate
# Delete resources such as statefulsets, deployments, services, pdb, but keep PVCs
# when deleting the cluster, use termination policy Halt
kbcli cluster create mycluster --cluster-definition apecloud-mysql --termination-policy Halt
# Delete resource such as statefulsets, deployments, services, pdb, and including
# PVCs when deleting the cluster, use termination policy Delete
kbcli cluster create mycluster --cluster-definition apecloud-mysql --termination-policy Delete
# Delete all resources including all snapshots and snapshot data when deleting
# the cluster, use termination policy WipeOut
kbcli cluster create mycluster --cluster-definition apecloud-mysql --termination-policy WipeOut
# Create a cluster and set cpu to 1 core, memory to 1Gi, storage size to 20Gi and replicas to 3
kbcli cluster create mycluster --cluster-definition apecloud-mysql --set cpu=1,memory=1Gi,storage=20Gi,replicas=3
# Create a cluster and set storageClass to csi-hostpath-sc, if storageClass is not specified,
# the default storage class will be used
kbcli cluster create mycluster --cluster-definition apecloud-mysql --set storageClass=csi-hostpath-sc
# Create a cluster with replicationSet workloadType and set switchPolicy to Noop
kbcli cluster create mycluster --cluster-definition postgresql --set switchPolicy=Noop
# Create a cluster with more than one component, use "--set type=component-name" to specify the component,
# if not specified, the main component will be used, run "kbcli cd list-components CLUSTER-DEFINITION-NAME"
# to show the components in the cluster definition
kbcli cluster create mycluster --cluster-definition redis --set type=redis,cpu=1 --set type=redis-sentinel,cpu=200m
# Create a cluster and use a URL to set cluster resource
kbcli cluster create mycluster --cluster-definition apecloud-mysql \
--set-file https://kubeblocks.io/yamls/apecloud-mysql.yaml
# Create a cluster and load cluster resource set from stdin
cat << EOF | kbcli cluster create mycluster --cluster-definition apecloud-mysql --set-file -
- name: my-test ...
# Create a cluster scattered by nodes
kbcli cluster create --cluster-definition apecloud-mysql --topology-keys kubernetes.io/hostname \
--pod-anti-affinity Required
# Create a cluster in specific labels nodes
kbcli cluster create --cluster-definition apecloud-mysql \
--node-labels '"topology.kubernetes.io/zone=us-east-1a","disktype=ssd,essd"'
# Create a Cluster with two tolerations
kbcli cluster create --cluster-definition apecloud-mysql --tolerations \ '"engineType=mongo:NoSchedule","diskType=ssd:NoSchedule"'
# Create a cluster, with each pod runs on their own dedicated node
kbcli cluster create --cluster-definition apecloud-mysql --tenancy=DedicatedNode
# Create a cluster with backup to restore data
kbcli cluster create --backup backup-default-mycluster-20230616190023
# Create a cluster with time to restore from point in time
kbcli cluster create --restore-to-time "Jun 16,2023 18:58:53 UTC+0800" --source-cluster mycluster
# Create a cluster with auto backup
kbcli cluster create --cluster-definition apecloud-mysql --backup-enabled
# Create a cluster with default component having multiple storage volumes
kbcli cluster create --cluster-definition oceanbase --pvc name=data-file,size=50Gi --pvc name=data-log,size=50Gi --pvc name=log,size=20Gi
# Create a cluster with specifying a component having multiple storage volumes
kbcli cluster create --cluster-definition pulsar --pvc type=bookies,name=ledgers,size=20Gi --pvc type=bookies,name=journal,size=20Gi
# Create a cluster with using a service reference to another KubeBlocks cluster
kbcli cluster create --cluster-definition pulsar --service-reference name=pulsarZookeeper,cluster=zookeeper,namespace=default
`)
const (
CueTemplateName = "cluster_template.cue"
monitorKey = "monitor"
apeCloudMysql = "apecloud-mysql"
defaultVolumeName = "data"
)
type setKey string
const (
keyType setKey = "type"
keyCPU setKey = "cpu"
keyClass setKey = "class"
keyMemory setKey = "memory"
keyReplicas setKey = "replicas"
keyStorage setKey = "storage"
keyStorageClass setKey = "storageClass"
keySwitchPolicy setKey = "switchPolicy"
keyCompNum setKey = "compNum"
keyUnknown setKey = "unknown"
keyMonitor setKey = "monitor"
)
var setKeyCfg = map[setKey]string{
keyCPU: types.CfgKeyClusterDefaultCPU,
keyMemory: types.CfgKeyClusterDefaultMemory,
keyStorage: types.CfgKeyClusterDefaultStorageSize,
keyReplicas: types.CfgKeyClusterDefaultReplicas,
}
// With the access of various databases, the simple way of specifying the capacity of storage by --set
// no longer meets the current demand, because many clusters' components are set up with multiple pvc, so we split the way of setting storage from `--set`.
type storageKey string
// map[string]map[storageKey]string `json:"-"`
const (
// storageKeyType is the key of CreateOptions.Storages, reference to a cluster component name
storageKeyType storageKey = "type"
// storageKeyName is the name of a pvc in volumeClaimTemplates, like "data" or "log"
storageKeyName storageKey = "name"
// storageKeyStorageClass is the storageClass of a pvc
storageKeyStorageClass storageKey = "storageClass"
// storageAccessMode is the storageAccessMode of a pvc, could be ReadWriteOnce,ReadOnlyMany,ReadWriteMany.
// more information in https://kubernetes.io/docs/concepts/storage/persistent-volumes/#access-modes
storageAccessMode storageKey = "mode"
// storageKeySize is the size of a pvc
storageKeySize storageKey = "size"
storageKeyUnknown storageKey = "unknown"
)
// set the components volume names, key is the component type.
var componentVolumes = map[string][]string{
"bookies": {"journal", "ledgers"},
// kafka controller
"controller": {"metadata"},
"kafka-broker": {"metadata", "data"},
"kafka-server": {"metadata", "data"},
}
// UpdatableFlags is the flags that cat be updated by update command
type UpdatableFlags struct {
// Options for cluster termination policy
TerminationPolicy string `json:"terminationPolicy"`
// Add-on switches for cluster observability
MonitoringInterval uint8 `json:"monitor"`
EnableAllLogs bool `json:"enableAllLogs"`
// Configuration and options for cluster affinity and tolerations
PodAntiAffinity string `json:"podAntiAffinity"`
// TopologyKeys if TopologyKeys is nil, add omitempty json tag, because CueLang can not covert null to list.
TopologyKeys []string `json:"topologyKeys,omitempty"`
NodeLabels map[string]string `json:"nodeLabels,omitempty"`
Tenancy string `json:"tenancy"`
TolerationsRaw []string `json:"-"`
// backup config
BackupEnabled bool `json:"-"`
BackupRetentionPeriod string `json:"-"`
BackupMethod string `json:"-"`
BackupCronExpression string `json:"-"`
BackupStartingDeadlineMinutes int64 `json:"-"`
BackupRepoName string `json:"-"`
BackupPITREnabled bool `json:"-"`
}
type CreateOptions struct {
// ClusterDefRef reference clusterDefinition
ClusterDefRef string `json:"clusterDefRef"`
ClusterVersionRef string `json:"clusterVersionRef"`
Tolerations []interface{} `json:"tolerations,omitempty"`
ComponentSpecs []map[string]interface{} `json:"componentSpecs"`
Annotations map[string]string `json:"annotations,omitempty"`
Labels map[string]string `json:"labels,omitempty"`
// create components exclusively configured in 'set'.
CreateOnlySet bool `json:"-"`
SetFile string `json:"-"`
Values []string `json:"-"`
RBACEnabled bool `json:"-"`
Storages []string `json:"-"`
ServiceRef []string `json:"-"`
LabelStrs []string `json:"-"`
AnnotationStrs []string `json:"-"`
CPUOversellRatio float64 `json:"-"`
MemoryOversellRatio float64 `json:"-"`
// backup name to restore in creation
Backup string `json:"backup,omitempty"`
RestoreTime string `json:"restoreTime,omitempty"`
VolumeRestorePolicy string `json:"-"`
ReadyRestoreAfterClusterRunning bool
// backup config
BackupConfig *appsv1alpha1.ClusterBackup `json:"backupConfig,omitempty"`
Cmd *cobra.Command `json:"-"`
UpdatableFlags
action.CreateOptions `json:"-"`
}
func NewCreateCmd(f cmdutil.Factory, streams genericiooptions.IOStreams) *cobra.Command {
o := NewCreateOptions(f, streams)
cmd := &cobra.Command{
Use: "create [NAME]",
Short: "Create a cluster.",
Example: clusterCreateExample,
Run: func(cmd *cobra.Command, args []string) {
o.Args = args
cmdutil.CheckErr(o.CreateOptions.Complete())
cmdutil.CheckErr(o.Complete())
cmdutil.CheckErr(o.Validate())
cmdutil.CheckErr(o.Run())
},
}
cmd.Flags().StringVar(&o.ClusterDefRef, "cluster-definition", "", "Specify cluster definition, run \"kbcli cd list\" to show all available cluster definitions")
cmd.Flags().StringVar(&o.ClusterVersionRef, "cluster-version", "", "Specify cluster version, run \"kbcli cv list\" to show all available cluster versions, use the latest version if not specified")
cmd.Flags().StringVarP(&o.SetFile, "set-file", "f", "", "Use yaml file, URL, or stdin to set the cluster resource")
cmd.Flags().StringArrayVar(&o.Values, "set", []string{}, "Set the cluster resource including cpu, memory, replicas and storage, each set corresponds to a component.(e.g. --set cpu=1,memory=1Gi,replicas=3,storage=20Gi or --set class=general-1c1g)")
cmd.Flags().BoolVar(&o.CreateOnlySet, "create-only-set", false, "Create components exclusively configured in 'set'")
cmd.Flags().StringArrayVar(&o.Storages, "pvc", []string{}, "Set the cluster detail persistent volume claim, each '--pvc' corresponds to a component, and will override the simple configurations about storage by --set (e.g. --pvc type=mysql,name=data,mode=ReadWriteOnce,size=20Gi --pvc type=mysql,name=log,mode=ReadWriteOnce,size=1Gi)")
cmd.Flags().StringArrayVar(&o.ServiceRef, "service-reference", []string{}, "Set the other KubeBlocks cluster dependencies, each '--service-reference' corresponds to a cluster service. (e.g --service-reference name=pulsarZookeeper,cluster=zookeeper,namespace=default)")
cmd.Flags().StringArrayVar(&o.AnnotationStrs, "annotation", []string{}, "Set annotations for cluster")
cmd.Flags().StringArrayVar(&o.LabelStrs, "label", []string{}, "Set labels for cluster resources")
cmd.Flags().Float64Var(&o.CPUOversellRatio, "cpu-oversell-ratio", 1, "Set oversell ratio of CPU, set to 10 means 10 times oversell")
cmd.Flags().Float64Var(&o.MemoryOversellRatio, "memory-oversell-ratio", 1, "Set oversell ratio of memory, set to 10 means 10 times oversell")
cmd.Flags().StringVar(&o.Backup, "backup", "", "Set a source backup to restore data")
cmd.Flags().StringVar(&o.RestoreTime, "restore-to-time", "", "Set a time for point in time recovery")
cmd.Flags().StringVar(&o.VolumeRestorePolicy, "volume-restore-policy", "Parallel", "the volume claim restore policy, supported values: [Serial, Parallel]")
cmd.Flags().BoolVar(&o.ReadyRestoreAfterClusterRunning, "do-ready-restore-after-cluster-running", false, "do ready restore after cluster running")
cmd.Flags().BoolVar(&o.RBACEnabled, "rbac-enabled", false, "Specify whether rbac resources will be created by kbcli, otherwise KubeBlocks server will try to create rbac resources")
cmd.PersistentFlags().BoolVar(&o.EditBeforeCreate, "edit", o.EditBeforeCreate, "Edit the API resource before creating")
cmd.PersistentFlags().StringVar(&o.DryRun, "dry-run", "none", `Must be "client", or "server". If with client strategy, only print the object that would be sent, and no data is actually sent. If with server strategy, submit the server-side request, but no data is persistent.`)
cmd.PersistentFlags().Lookup("dry-run").NoOptDefVal = "unchanged"
// add updatable flags
o.UpdatableFlags.addFlags(cmd)
// add print flags
printer.AddOutputFlagForCreate(cmd, &o.Format, true)
// register flag completion func
registerFlagCompletionFunc(cmd, f)
// add all subcommands for supported cluster type
cmd.AddCommand(buildCreateSubCmds(&o.CreateOptions)...)
o.Cmd = cmd
return cmd
}
func NewCreateOptions(f cmdutil.Factory, streams genericiooptions.IOStreams) *CreateOptions {
o := &CreateOptions{CreateOptions: action.CreateOptions{
Factory: f,
IOStreams: streams,
CueTemplateName: CueTemplateName,
GVR: types.ClusterGVR(),
}}
o.CreateOptions.Options = o
o.CreateOptions.PreCreate = o.PreCreate
o.CreateOptions.CreateDependencies = o.CreateDependencies
o.CreateOptions.CleanUpFn = o.CleanUp
return o
}
func getSourceClusterFromBackup(backup *dpv1alpha1.Backup) (*appsv1alpha1.Cluster, error) {
sourceCluster := &appsv1alpha1.Cluster{}
sourceClusterJSON := backup.Annotations[constant.ClusterSnapshotAnnotationKey]
if err := json.Unmarshal([]byte(sourceClusterJSON), sourceCluster); err != nil {
return nil, err
}
return sourceCluster, nil
}
func getBackupObjectFromRestoreArgs(o *CreateOptions, backup *dpv1alpha1.Backup) error {
if o.Backup == "" {
return nil
}
if err := util.GetK8SClientObject(o.Dynamic, backup, types.BackupGVR(), o.Namespace, o.Backup); err != nil {
return err
}
return nil
}
func fillClusterInfoFromBackup(o *CreateOptions, cls **appsv1alpha1.Cluster) error {
if o.Backup == "" {
return nil
}
backup := &dpv1alpha1.Backup{}
if err := getBackupObjectFromRestoreArgs(o, backup); err != nil {
return err
}
backupCluster, err := getSourceClusterFromBackup(backup)
if err != nil {
return err
}
curCluster := *cls
if curCluster == nil {
curCluster = backupCluster
}
// validate cluster spec
if o.ClusterDefRef != "" && o.ClusterDefRef != backupCluster.Spec.ClusterDefRef {
return fmt.Errorf("specified cluster definition does not match from backup(expect: %s, actual: %s),"+
" please check", backupCluster.Spec.ClusterDefRef, o.ClusterDefRef)
}
if o.ClusterVersionRef != "" && o.ClusterVersionRef != backupCluster.Spec.ClusterVersionRef {
return fmt.Errorf("specified cluster version does not match from backup(expect: %s, actual: %s),"+
" please check", backupCluster.Spec.ClusterVersionRef, o.ClusterVersionRef)
}
o.ClusterDefRef = curCluster.Spec.ClusterDefRef
o.ClusterVersionRef = curCluster.Spec.ClusterVersionRef
*cls = curCluster
return nil
}
func setBackup(o *CreateOptions, components []map[string]interface{}) error {
backupName := o.Backup
if len(backupName) == 0 || len(components) == 0 {
return nil
}
backup := &dpv1alpha1.Backup{}
if err := util.GetK8SClientObject(o.Dynamic, backup, types.BackupGVR(), o.Namespace, backupName); err != nil {
return err
}
if backup.Status.Phase != dpv1alpha1.BackupPhaseCompleted &&
backup.Labels[dptypes.BackupTypeLabelKey] != string(dpv1alpha1.BackupTypeContinuous) {
return fmt.Errorf(`backup "%s" is not completed`, backup.Name)
}
restoreTimeStr, err := restore.FormatRestoreTimeAndValidate(o.RestoreTime, backup)
if err != nil {
return err
}
var componentSpecs []appsv1alpha1.ClusterComponentSpec
for _, v := range components {
compSpec := appsv1alpha1.ClusterComponentSpec{}
_ = runtime.DefaultUnstructuredConverter.FromUnstructured(v, &compSpec)
componentSpecs = append(componentSpecs, compSpec)
}
restoreAnnotation, err := restore.GetRestoreFromBackupAnnotation(backup, componentSpecs, o.VolumeRestorePolicy,
restoreTimeStr, false, o.ReadyRestoreAfterClusterRunning)
if err != nil {
return err
}
if o.Annotations == nil {
o.Annotations = map[string]string{}
}
o.Annotations[constant.RestoreFromBackupAnnotationKey] = restoreAnnotation
return nil
}
func (o *CreateOptions) Validate() error {
if o.ClusterDefRef == "" {
return fmt.Errorf("a valid cluster definition is needed, use --cluster-definition to specify one, run \"kbcli clusterdefinition list\" to show all cluster definitions")
}
if o.TerminationPolicy == "" {
return fmt.Errorf("a valid termination policy is needed, use --termination-policy to specify one of: DoNotTerminate, Halt, Delete, WipeOut")
}
if err := o.validateClusterVersion(); err != nil {
return err
}
if len(o.Values) > 0 && len(o.SetFile) > 0 {
return fmt.Errorf("does not support --set and --set-file being specified at the same time")
}
matched, _ := regexp.MatchString(`^[a-z]([-a-z0-9]*[a-z0-9])?$`, o.Name)
if !matched {
return fmt.Errorf("cluster name must begin with a letter and can only contain lowercase letters, numbers, and '-'")
}
if len(o.Name) > 16 {
return fmt.Errorf("cluster name should be less than 16 characters")
}
return nil
}
func (o *CreateOptions) Complete() error {
var (
compByte []byte
cls *appsv1alpha1.Cluster
clusterCompSpecs []appsv1alpha1.ClusterComponentSpec
err error
)
if len(o.SetFile) > 0 {
if compByte, err = MultipleSourceComponents(o.SetFile, o.IOStreams.In); err != nil {
return err
}
if compByte, err = yaml.YAMLToJSON(compByte); err != nil {
return err
}
// compatible with old file format that only specifies the components
if err = json.Unmarshal(compByte, &cls); err != nil {
if clusterCompSpecs, err = parseClusterComponentSpec(compByte); err != nil {
return err
}
} else {
clusterCompSpecs = cls.Spec.ComponentSpecs
}
}
if err = fillClusterInfoFromBackup(o, &cls); err != nil {
return err
}
if nil != cls && cls.Spec.ComponentSpecs != nil {
clusterCompSpecs = cls.Spec.ComponentSpecs
}
// if name is not specified, generate a random cluster name
if o.Name == "" {
o.Name, err = generateClusterName(o.Dynamic, o.Namespace)
if err != nil {
return err
}
}
// build annotation
o.buildAnnotation(cls)
if len(o.AnnotationStrs) > 0 {
if o.Annotations == nil {
o.Annotations = make(map[string]string)
}
for _, annotationStr := range o.AnnotationStrs {
kv := strings.Split(annotationStr, "=")
if len(kv) != 2 {
return fmt.Errorf("label format error, should be key=value")
}
o.Annotations[kv[0]] = kv[1]
}
}
// build labels
if cls != nil && len(cls.Labels) > 0 {
o.Labels = cls.Labels
}
if len(o.LabelStrs) > 0 {
if o.Labels == nil {
o.Labels = make(map[string]string)
}
for _, labelStr := range o.LabelStrs {
kv := strings.Split(labelStr, "=")
if len(kv) != 2 {
return fmt.Errorf("label format error, should be key=value")
}
o.Labels[kv[0]] = kv[1]
}
}
// build cluster definition
if err := o.buildClusterDef(cls); err != nil {
return err
}
// build cluster version
o.buildClusterVersion(cls)
// build backup config
if err := o.buildBackupConfig(cls); err != nil {
return err
}
// build components
components, err := o.buildComponents(clusterCompSpecs)
if err != nil {
return err
}
if err = setBackup(o, components); err != nil {
return err
}
o.ComponentSpecs = components
// TolerationsRaw looks like `["key=engineType,value=mongo,operator=Equal,effect=NoSchedule"]` after parsing by cmd
tolerations, err := util.BuildTolerations(o.TolerationsRaw)
if err != nil {
return err
}
if len(tolerations) > 0 {
o.Tolerations = tolerations
}
// validate default storageClassName
return validateStorageClass(o.Dynamic, o.ComponentSpecs)
}
func (o *CreateOptions) CleanUp() error {
if o.Client == nil {
return nil
}
return deleteDependencies(o.Client, o.Namespace, o.Name)
}
// buildComponents builds components from file or set values
func (o *CreateOptions) buildComponents(clusterCompSpecs []appsv1alpha1.ClusterComponentSpec) ([]map[string]interface{}, error) {
var (
err error
cd *appsv1alpha1.ClusterDefinition
compSpecs []*appsv1alpha1.ClusterComponentSpec
storages map[string][]map[storageKey]string
)
cd, err = cluster.GetClusterDefByName(o.Dynamic, o.ClusterDefRef)
if err != nil {
return nil, err
}
clsMgr, resourceConstraintList, err := classutil.GetManager(o.Dynamic, o.ClusterDefRef)
if err != nil {
return nil, err
}
compSets, err := buildCompSetsMap(o.Values, cd)
if err != nil {
return nil, err
}
if len(o.Storages) != 0 {
storages, err = buildCompStorages(o.Storages, cd)
if err != nil {
return nil, err
}
}
overrideComponentBySets := func(comp, setComp *appsv1alpha1.ClusterComponentSpec, setValues map[setKey]string) {
for k := range setValues {
switch k {
case keyReplicas:
comp.Replicas = setComp.Replicas
case keyCPU:
comp.Resources.Requests[corev1.ResourceCPU] = setComp.Resources.Requests[corev1.ResourceCPU]
comp.Resources.Limits[corev1.ResourceCPU] = setComp.Resources.Limits[corev1.ResourceCPU]
case keyClass:
comp.ClassDefRef = setComp.ClassDefRef
case keyMemory:
comp.Resources.Requests[corev1.ResourceMemory] = setComp.Resources.Requests[corev1.ResourceMemory]
comp.Resources.Limits[corev1.ResourceMemory] = setComp.Resources.Limits[corev1.ResourceMemory]
case keyStorage:
if len(comp.VolumeClaimTemplates) > 0 && len(setComp.VolumeClaimTemplates) > 0 {
comp.VolumeClaimTemplates[0].Spec.Resources.Requests = setComp.VolumeClaimTemplates[0].Spec.Resources.Requests
}
case keyStorageClass:
if len(comp.VolumeClaimTemplates) > 0 && len(setComp.VolumeClaimTemplates) > 0 {
comp.VolumeClaimTemplates[0].Spec.StorageClassName = setComp.VolumeClaimTemplates[0].Spec.StorageClassName
}
case keySwitchPolicy:
comp.SwitchPolicy = setComp.SwitchPolicy
}
}
}
if clusterCompSpecs != nil {
setsCompSpecs, err := buildClusterComp(cd, compSets, clsMgr, o.MonitoringInterval, o.CreateOnlySet)
if err != nil {
return nil, err
}
setsCompSpecsMap := map[string]*appsv1alpha1.ClusterComponentSpec{}
for _, setComp := range setsCompSpecs {
setsCompSpecsMap[setComp.Name] = setComp
}
for index := range clusterCompSpecs {
comp := clusterCompSpecs[index]
overrideComponentBySets(&comp, setsCompSpecsMap[comp.Name], compSets[comp.Name])
compSpecs = append(compSpecs, &comp)
}
} else {
compSpecs, err = buildClusterComp(cd, compSets, clsMgr, o.MonitoringInterval, o.CreateOnlySet)
if err != nil {
return nil, err
}
}
if len(storages) != 0 {
compSpecs = rebuildCompStorage(storages, compSpecs)
}
// build service reference if --service-reference not empty
if len(o.ServiceRef) != 0 {
compSpecs, err = buildServiceRefs(o.ServiceRef, cd, compSpecs)
if err != nil {
return nil, err
}
}
var comps []map[string]interface{}
for _, compSpec := range compSpecs {
// validate component classes
if err = classutil.ValidateResources(clsMgr, resourceConstraintList, o.ClusterDefRef, compSpec); err != nil {
return nil, err
}
// cpu oversell
if o.CPUOversellRatio > 1 {
cpuRequest := compSpec.Resources.Requests[corev1.ResourceCPU]
cpuStr := fmt.Sprintf("%dm", int(cpuRequest.AsApproximateFloat64()/o.CPUOversellRatio*1000))
cpuRequest = resource.MustParse(cpuStr)
compSpec.Resources.Requests[corev1.ResourceCPU] = cpuRequest
}
// memory oversell
if o.MemoryOversellRatio > 1 {
memoryRequest := compSpec.Resources.Requests[corev1.ResourceMemory]
memoryStr := fmt.Sprintf("%dMi", int(memoryRequest.AsApproximateFloat64()/o.MemoryOversellRatio/math.Pow(2, 20)))
memoryRequest = resource.MustParse(memoryStr)
compSpec.Resources.Requests[corev1.ResourceMemory] = memoryRequest
}
// create component dependencies
if err = o.buildDependenciesFn(cd, compSpec); err != nil {
return nil, err
}
comp, err := runtime.DefaultUnstructuredConverter.ToUnstructured(compSpec)
if err != nil {
return nil, err
}
comps = append(comps, comp)
}
return comps, nil
}
const (
saNamePrefix = "kb-"
roleNamePrefix = "kb-"
roleBindingNamePrefix = "kb-"
clusterRolePrefix = "kb-"
clusterRoleBindingPrefix = "kb-"
)
var (
rbacAPIGroup = "rbac.authorization.k8s.io"
saKind = "ServiceAccount"
roleKind = "Role"
clusterRoleKind = "ClusterRole"
)
// buildDependenciesFn creates dependencies function for components, e.g. postgresql depends on
// a service account, a role and a rolebinding
func (o *CreateOptions) buildDependenciesFn(cd *appsv1alpha1.ClusterDefinition,
compSpec *appsv1alpha1.ClusterComponentSpec) error {
// set component service account name
compSpec.ServiceAccountName = saNamePrefix + o.Name
return nil
}
func (o *CreateOptions) CreateDependencies(dryRun []string) error {
if !o.RBACEnabled {
return nil
}
var (
ctx = context.TODO()
labels = buildResourceLabels(o.Name)
applyOptions = metav1.ApplyOptions{FieldManager: "kbcli", DryRun: dryRun}
)
klog.V(1).Infof("create dependencies for cluster %s", o.Name)
if err := o.createServiceAccount(ctx, labels, applyOptions); err != nil {
return err
}
if err := o.createRoleAndBinding(ctx, labels, applyOptions); err != nil {
return err
}
if err := o.createClusterRoleAndBinding(ctx, labels, applyOptions); err != nil {
return err
}
return nil
}
func (o *CreateOptions) createServiceAccount(ctx context.Context, labels map[string]string, opts metav1.ApplyOptions) error {
saName := saNamePrefix + o.Name
klog.V(1).Infof("create service account %s", saName)
sa := corev1ac.ServiceAccount(saName, o.Namespace).WithLabels(labels)
_, err := o.Client.CoreV1().ServiceAccounts(o.Namespace).Apply(ctx, sa, opts)
return err
}
func (o *CreateOptions) createRoleAndBinding(ctx context.Context, labels map[string]string, opts metav1.ApplyOptions) error {
var (
saName = saNamePrefix + o.Name
roleName = roleNamePrefix + o.Name
roleBindingName = roleBindingNamePrefix + o.Name
)
klog.V(1).Infof("create role %s", roleName)
role := rbacv1ac.Role(roleName, o.Namespace).WithRules([]*rbacv1ac.PolicyRuleApplyConfiguration{
{
APIGroups: []string{""},
Resources: []string{"events"},
Verbs: []string{"create"},
},
{
APIGroups: []string{"dataprotection.kubeblocks.io"},
Resources: []string{"backups/status"},
Verbs: []string{"get", "update", "patch"},
},
{
APIGroups: []string{"dataprotection.kubeblocks.io"},
Resources: []string{"backups"},
Verbs: []string{"create", "get", "list", "update", "patch"},
},
}...).WithLabels(labels)
// postgresql need more rules for patroni
if ok, err := o.isPostgresqlCluster(); err != nil {
return err
} else if ok {
rules := []rbacv1ac.PolicyRuleApplyConfiguration{
{
APIGroups: []string{""},
Resources: []string{"configmaps"},
Verbs: []string{"create", "get", "list", "patch", "update", "watch", "delete"},
},
{
APIGroups: []string{""},
Resources: []string{"endpoints"},
Verbs: []string{"create", "get", "list", "patch", "update", "watch", "delete"},
},
{
APIGroups: []string{""},
Resources: []string{"pods"},
Verbs: []string{"get", "list", "patch", "update", "watch"},
},
}
role.Rules = append(role.Rules, rules...)
}
if _, err := o.Client.RbacV1().Roles(o.Namespace).Apply(ctx, role, opts); err != nil {
return err
}
klog.V(1).Infof("create role binding %s", roleBindingName)
roleBinding := rbacv1ac.RoleBinding(roleBindingName, o.Namespace).WithLabels(labels).
WithSubjects([]*rbacv1ac.SubjectApplyConfiguration{
{
Kind: &saKind,
Name: &saName,
Namespace: &o.Namespace,
},
}...).
WithRoleRef(&rbacv1ac.RoleRefApplyConfiguration{
APIGroup: &rbacAPIGroup,
Kind: &roleKind,
Name: &roleName,
})
_, err := o.Client.RbacV1().RoleBindings(o.Namespace).Apply(ctx, roleBinding, opts)
return err
}
func (o *CreateOptions) createClusterRoleAndBinding(ctx context.Context, labels map[string]string, opts metav1.ApplyOptions) error {
var (
saName = saNamePrefix + o.Name
clusterRoleName = clusterRolePrefix + o.Name
clusterRoleBindingName = clusterRoleBindingPrefix + o.Name
)
klog.V(1).Infof("create cluster role %s", clusterRoleName)
clusterRole := rbacv1ac.ClusterRole(clusterRoleName).WithRules([]*rbacv1ac.PolicyRuleApplyConfiguration{
{
APIGroups: []string{""},
Resources: []string{"nodes", "nodes/stats"},
Verbs: []string{"get", "list"},
},
}...).WithLabels(labels)
if _, err := o.Client.RbacV1().ClusterRoles().Apply(ctx, clusterRole, opts); err != nil {
return err
}
klog.V(1).Infof("create cluster role binding %s", clusterRoleBindingName)
clusterRoleBinding := rbacv1ac.ClusterRoleBinding(clusterRoleBindingName).WithLabels(labels).
WithSubjects([]*rbacv1ac.SubjectApplyConfiguration{
{
Kind: &saKind,
Name: &saName,
Namespace: &o.Namespace,
},
}...).
WithRoleRef(&rbacv1ac.RoleRefApplyConfiguration{
APIGroup: &rbacAPIGroup,
Kind: &clusterRoleKind,
Name: &clusterRoleName,
})
_, err := o.Client.RbacV1().ClusterRoleBindings().Apply(ctx, clusterRoleBinding, opts)
return err
}
// MultipleSourceComponents gets component data from multiple source, such as stdin, URI and local file
func MultipleSourceComponents(fileName string, in io.Reader) ([]byte, error) {
var data io.Reader
switch {
case fileName == "-":
data = in
case strings.Index(fileName, "http://") == 0 || strings.Index(fileName, "https://") == 0:
resp, err := http.Get(fileName)
if err != nil {
return nil, err
}
defer resp.Body.Close()
data = resp.Body
default:
f, err := os.Open(fileName)
if err != nil {
return nil, err
}
defer f.Close()
data = f
}
return io.ReadAll(data)
}
func registerFlagCompletionFunc(cmd *cobra.Command, f cmdutil.Factory) {
util.CheckErr(cmd.RegisterFlagCompletionFunc(
"cluster-definition",
func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
return utilcomp.CompGetResource(f, util.GVRToString(types.ClusterDefGVR()), toComplete), cobra.ShellCompDirectiveNoFileComp
}))
util.CheckErr(cmd.RegisterFlagCompletionFunc(
"cluster-version",
func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
var clusterVersion []string
clusterDefinition, err := cmd.Flags().GetString("cluster-definition")
if clusterDefinition == "" || err != nil {
clusterVersion = utilcomp.CompGetResource(f, util.GVRToString(types.ClusterVersionGVR()), toComplete)
} else {
label := fmt.Sprintf("%s=%s", constant.ClusterDefLabelKey, clusterDefinition)
clusterVersion = util.CompGetResourceWithLabels(f, cmd, util.GVRToString(types.ClusterVersionGVR()), []string{label}, toComplete)
}
return clusterVersion, cobra.ShellCompDirectiveNoFileComp
}))
var formatsWithDesc = map[string]string{
"JSON": "Output result in JSON format",
"YAML": "Output result in YAML format",
}
util.CheckErr(cmd.RegisterFlagCompletionFunc("output",
func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
var names []string
for format, desc := range formatsWithDesc {
if strings.HasPrefix(format, toComplete) {
names = append(names, fmt.Sprintf("%s\t%s", format, desc))
}
}
return names, cobra.ShellCompDirectiveNoFileComp
}))
}
// PreCreate before saving yaml to k8s, makes changes on Unstructured yaml
func (o *CreateOptions) PreCreate(obj *unstructured.Unstructured) error {
c := &appsv1alpha1.Cluster{}
if err := runtime.DefaultUnstructuredConverter.FromUnstructured(obj.Object, c); err != nil {
return err
}
// get cluster definition from k8s
cd, err := cluster.GetClusterDefByName(o.Dynamic, c.Spec.ClusterDefRef)
if err != nil {
return err
}
if !o.EnableAllLogs {
setEnableAllLogs(c, cd)
}
if o.BackupConfig == nil {
// if backup config is not specified, set cluster's backup to nil
c.Spec.Backup = nil
}
data, e := runtime.DefaultUnstructuredConverter.ToUnstructured(c)
if e != nil {
return e
}
obj.SetUnstructuredContent(data)
return nil
}
func (o *CreateOptions) isPostgresqlCluster() (bool, error) {
cd, err := cluster.GetClusterDefByName(o.Dynamic, o.ClusterDefRef)
if err != nil {
return false, err
}
var compDef *appsv1alpha1.ClusterComponentDefinition
if cd.Spec.Type != "postgresql" {
return false, nil
}
// get cluster component definition
if len(o.ComponentSpecs) == 0 {
return false, fmt.Errorf("find no cluster component")
}
compSpec := o.ComponentSpecs[0]
for i, def := range cd.Spec.ComponentDefs {
compDefRef := compSpec["componentDefRef"]
if compDefRef != nil && def.Name == compDefRef.(string) {
compDef = &cd.Spec.ComponentDefs[i]
}
}
if compDef == nil {
return false, fmt.Errorf("failed to find component definition for component %v", compSpec["Name"])
}
// for postgresql, we need to create a service account, a role and a rolebinding
if compDef.CharacterType != "postgresql" {
return false, nil
}
return true, nil
}
// setEnableAllLog sets enable all logs, and ignore enabledLogs of component level.
func setEnableAllLogs(c *appsv1alpha1.Cluster, cd *appsv1alpha1.ClusterDefinition) {
for idx, comCluster := range c.Spec.ComponentSpecs {
for _, com := range cd.Spec.ComponentDefs {
if !strings.EqualFold(comCluster.ComponentDefRef, com.Name) {
continue
}