/
config.go
633 lines (595 loc) · 20.9 KB
/
config.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
/*
Copyright 2022 The KubeVela Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package cli
import (
"bufio"
"bytes"
"context"
"errors"
"fmt"
"strings"
"github.com/spf13/cobra"
"helm.sh/helm/v3/pkg/strvals"
"k8s.io/kubectl/pkg/util/i18n"
"k8s.io/kubectl/pkg/util/templates"
"sigs.k8s.io/yaml"
workflowv1alpha1 "github.com/kubevela/workflow/api/v1alpha1"
"github.com/oam-dev/kubevela/apis/types"
velacmd "github.com/oam-dev/kubevela/pkg/cmd"
"github.com/oam-dev/kubevela/pkg/config"
pkgUtils "github.com/oam-dev/kubevela/pkg/utils"
"github.com/oam-dev/kubevela/pkg/utils/util"
"github.com/oam-dev/kubevela/references/docgen"
)
// ConfigCommandGroup commands for the config
func ConfigCommandGroup(f velacmd.Factory, order string, streams util.IOStreams) *cobra.Command {
cmd := &cobra.Command{
Use: "config",
Short: i18n.T("Manage the configs."),
Long: i18n.T("Manage the configs, such as the terraform provider, image registry, helm repository, etc."),
Annotations: map[string]string{
types.TagCommandType: types.TypePlatform,
types.TagCommandOrder: order,
},
}
cmd.AddCommand(NewListConfigCommand(f, streams))
cmd.AddCommand(NewCreateConfigCommand(f, streams))
cmd.AddCommand(NewDistributeConfigCommand(f, streams))
cmd.AddCommand(NewDeleteConfigCommand(f, streams))
return cmd
}
// TemplateCommandGroup commands for the template of the config
func TemplateCommandGroup(f velacmd.Factory, order string, streams util.IOStreams) *cobra.Command {
cmd := &cobra.Command{
Use: "config-template",
Aliases: []string{"ct"},
Short: i18n.T("Manage the template of config."),
Annotations: map[string]string{
types.TagCommandType: types.TypePlatform,
types.TagCommandOrder: order,
},
}
cmd.AddCommand(NewTemplateApplyCommand(f, streams))
cmd.AddCommand(NewTemplateListCommand(f, streams))
cmd.AddCommand(NewTemplateDeleteCommand(f, streams))
cmd.AddCommand(NewTemplateShowCommand(f, streams))
return cmd
}
// TemplateApplyCommandOptions the options of the command that apply the config template.
type TemplateApplyCommandOptions struct {
File string
Namespace string
Name string
}
// TemplateCommandOptions the options of the command that delete or show the config template.
type TemplateCommandOptions struct {
Namespace string
Name string
}
// TemplateListCommandOptions the options of the command that list the config templates.
type TemplateListCommandOptions struct {
Namespace string
AllNamespace bool
}
// NewTemplateApplyCommand command for creating and updating the config template
func NewTemplateApplyCommand(f velacmd.Factory, streams util.IOStreams) *cobra.Command {
var options TemplateApplyCommandOptions
cmd := &cobra.Command{
Use: "apply",
Short: i18n.T("Apply a config template."),
Annotations: map[string]string{
types.TagCommandType: types.TypeExtension,
},
Args: cobra.ExactArgs(0),
RunE: func(cmd *cobra.Command, args []string) error {
body, err := pkgUtils.ReadRemoteOrLocalPath(options.File, false)
if err != nil {
return err
}
inf := config.NewConfigFactory(f.Client())
template, err := inf.ParseTemplate(options.Name, body)
if err != nil {
return err
}
if err := inf.CreateOrUpdateConfigTemplate(context.Background(), options.Namespace, template); err != nil {
return err
}
streams.Infof("the config template %s applied successfully\n", template.Name)
return nil
},
}
cmd.Flags().StringVarP(&options.File, "file", "f", "", "specify the template file name")
cmd.Flags().StringVarP(&options.Name, "name", "", "", "specify the config template name")
cmd.Flags().StringVarP(&options.Namespace, "namespace", "n", types.DefaultKubeVelaNS, "specify the namespace of the template")
return cmd
}
// NewTemplateListCommand command for listing the config templates
func NewTemplateListCommand(f velacmd.Factory, streams util.IOStreams) *cobra.Command {
var options TemplateListCommandOptions
cmd := &cobra.Command{
Use: "list",
Short: i18n.T("List the config templates."),
Example: "vela config template list [-A]",
Annotations: map[string]string{
types.TagCommandType: types.TypeExtension,
},
Args: cobra.ExactArgs(0),
RunE: func(cmd *cobra.Command, args []string) error {
inf := config.NewConfigFactory(f.Client())
if options.AllNamespace {
options.Namespace = ""
}
templateList, err := inf.ListTemplates(context.Background(), options.Namespace, "")
if err != nil {
return err
}
table := newUITable()
header := []interface{}{"NAME", "ALIAS", "SCOPE", "SENSITIVE", "CREATED-TIME"}
if options.AllNamespace {
header = append([]interface{}{"NAMESPACE"}, header...)
}
table.AddRow(header...)
for _, t := range templateList {
row := []interface{}{t.Name, t.Alias, t.Scope, t.Sensitive, t.CreateTime}
if options.AllNamespace {
row = append([]interface{}{t.Namespace}, row...)
}
table.AddRow(row...)
}
if _, err := streams.Out.Write(table.Bytes()); err != nil {
return err
}
if _, err := streams.Out.Write([]byte("\n")); err != nil {
return err
}
return nil
},
}
cmd.Flags().StringVarP(&options.Namespace, "namespace", "n", types.DefaultKubeVelaNS, "specify the namespace of the template")
cmd.Flags().BoolVarP(&options.AllNamespace, "all-namespaces", "A", false, "If true, check the specified action in all namespaces.")
return cmd
}
// NewTemplateShowCommand command for show the properties document
func NewTemplateShowCommand(f velacmd.Factory, streams util.IOStreams) *cobra.Command {
var options TemplateCommandOptions
cmd := &cobra.Command{
Use: "show",
Short: i18n.T("Show the documents of the template properties"),
Example: "vela config-template show <name> [-n]",
Annotations: map[string]string{
types.TagCommandType: types.TypeExtension,
},
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
options.Name = args[0]
if options.Name == "" {
return fmt.Errorf("can not show the properties without the template")
}
inf := config.NewConfigFactory(f.Client())
template, err := inf.LoadTemplate(context.Background(), options.Name, options.Namespace)
if err != nil {
return err
}
doc, err := docgen.GenerateConsoleDocument(template.Schema.Title, template.Schema)
if err != nil {
return err
}
if _, err := streams.Out.Write([]byte(doc)); err != nil {
return err
}
return nil
},
}
cmd.Flags().StringVarP(&options.Namespace, "namespace", "n", types.DefaultKubeVelaNS, "specify the namespace of the template")
return cmd
}
// NewTemplateDeleteCommand command for deleting the config template
func NewTemplateDeleteCommand(f velacmd.Factory, streams util.IOStreams) *cobra.Command {
var options TemplateCommandOptions
cmd := &cobra.Command{
Use: "delete",
Short: i18n.T("Delete a config template."),
Example: fmt.Sprintf("vela config template delete <name> [-n %s]", types.DefaultKubeVelaNS),
Annotations: map[string]string{
types.TagCommandType: types.TypeCD,
},
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
if len(args) == 0 {
return fmt.Errorf("please must provides the template name")
}
options.Name = args[0]
userInput := &UserInput{
Writer: streams.Out,
Reader: bufio.NewReader(streams.In),
}
if !assumeYes {
userConfirmation := userInput.AskBool("Do you want to delete this template", &UserInputOptions{assumeYes})
if !userConfirmation {
return fmt.Errorf("stopping deleting")
}
}
inf := config.NewConfigFactory(f.Client())
if err := inf.DeleteTemplate(context.Background(), options.Namespace, options.Name); err != nil {
return err
}
streams.Infof("the config template %s deleted successfully\n", options.Name)
return nil
},
}
cmd.Flags().StringVarP(&options.Namespace, "namespace", "n", types.DefaultKubeVelaNS, "specify the namespace of the template")
return cmd
}
// DistributeConfigCommandOptions the options of the command that distribute the config.
type DistributeConfigCommandOptions struct {
Targets []string
Config string
Namespace string
Recalled bool
}
// CreateConfigCommandOptions the options of the command that create the config.
type CreateConfigCommandOptions struct {
Template string
Namespace string
Name string
File string
Properties map[string]interface{}
DryRun bool
Targets []string
Description string
Alias string
}
// Validate validate the options
func (i CreateConfigCommandOptions) Validate() error {
if i.Name == "" {
return fmt.Errorf("the config name must be specified")
}
if len(i.Targets) > 0 && i.DryRun {
return fmt.Errorf("can not set the distribution in dry-run mode")
}
return nil
}
func (i *CreateConfigCommandOptions) parseProperties(args []string) error {
if i.File != "" {
body, err := pkgUtils.ReadRemoteOrLocalPath(i.File, false)
if err != nil {
return err
}
var properties = map[string]interface{}{}
if err := yaml.Unmarshal(body, &properties); err != nil {
return err
}
i.Properties = properties
return nil
}
res := map[string]interface{}{}
for _, arg := range args {
if err := strvals.ParseInto(arg, res); err != nil {
return err
}
}
i.Properties = res
return nil
}
// ConfigListCommandOptions the options of the command that list configs.
type ConfigListCommandOptions struct {
Namespace string
Template string
AllNamespace bool
}
// NewListConfigCommand command for listing the config secrets
func NewListConfigCommand(f velacmd.Factory, streams util.IOStreams) *cobra.Command {
var options ConfigListCommandOptions
cmd := &cobra.Command{
Use: "list",
Short: i18n.T("List the configs."),
Annotations: map[string]string{
types.TagCommandType: types.TypeCD,
},
Args: cobra.ExactArgs(0),
RunE: func(cmd *cobra.Command, args []string) error {
name := options.Template
if strings.Contains(options.Template, "/") {
namespacedName := strings.SplitN(options.Template, "/", 2)
name = namespacedName[1]
}
if options.AllNamespace {
options.Namespace = ""
}
inf := config.NewConfigFactory(f.Client())
configs, err := inf.ListConfigs(context.Background(), options.Namespace, name, "", true)
if err != nil {
return err
}
table := newUITable()
header := []interface{}{"NAME", "ALIAS", "DISTRIBUTION", "TEMPLATE", "CREATED-TIME", "DESCRIPTION"}
if options.AllNamespace {
header = append([]interface{}{"NAMESPACE"}, header...)
}
table.AddRow(header...)
for _, t := range configs {
var targetShow = ""
for _, target := range t.Targets {
if targetShow != "" {
targetShow += " "
}
switch target.Status {
case string(workflowv1alpha1.WorkflowStepPhaseSucceeded):
targetShow += green.Sprintf("%s/%s", target.ClusterName, target.Namespace)
case string(workflowv1alpha1.WorkflowStepPhaseFailed):
targetShow += red.Sprintf("%s/%s", target.ClusterName, target.Namespace)
default:
targetShow += yellow.Sprintf("%s/%s", target.ClusterName, target.Namespace)
}
}
row := []interface{}{t.Name, t.Alias, targetShow, fmt.Sprintf("%s/%s", t.Template.Namespace, t.Template.Name), t.CreateTime, t.Description}
if options.AllNamespace {
row = append([]interface{}{t.Namespace}, row...)
}
table.AddRow(row...)
}
if _, err := streams.Out.Write(table.Bytes()); err != nil {
return err
}
if _, err := streams.Out.Write([]byte("\n")); err != nil {
return err
}
return nil
},
}
cmd.Flags().StringVarP(&options.Namespace, "namespace", "n", types.DefaultKubeVelaNS, "specify the namespace of the config")
cmd.Flags().StringVarP(&options.Template, "template", "t", "", "specify the template of the config")
cmd.Flags().BoolVarP(&options.AllNamespace, "all-namespaces", "A", false, "If true, check the specified action in all namespaces.")
return cmd
}
// NewCreateConfigCommand command for creating the config
func NewCreateConfigCommand(f velacmd.Factory, streams util.IOStreams) *cobra.Command {
var options CreateConfigCommandOptions
createConfigExample := templates.Examples(i18n.T(`
# Generate a config with the args
vela config create test-registry --template=image-registry registry=index.docker.io auth.username=test auth.password=test
# Generate a config with the file
vela config create test-config --template=image-registry -f config.yaml
# Generate a config without the template
vela config create test-vela -f config.yaml
`))
cmd := &cobra.Command{
Use: "create",
Aliases: []string{"c"},
Short: i18n.T("Create a config."),
Example: createConfigExample,
Annotations: map[string]string{
types.TagCommandType: types.TypeCD,
},
RunE: func(cmd *cobra.Command, args []string) error {
inf := config.NewConfigFactory(f.Client())
options.Name = args[0]
if err := options.Validate(); err != nil {
return err
}
name := options.Template
namespace := types.DefaultKubeVelaNS
if strings.Contains(options.Template, "/") {
namespacedName := strings.SplitN(options.Template, "/", 2)
namespace = namespacedName[0]
name = namespacedName[1]
}
if err := options.parseProperties(args[1:]); err != nil {
return err
}
configItem, err := inf.ParseConfig(context.Background(), config.NamespacedName{
Name: name,
Namespace: namespace,
}, config.Metadata{
NamespacedName: config.NamespacedName{
Name: options.Name,
Namespace: options.Namespace,
},
Properties: options.Properties,
Alias: options.Alias,
Description: options.Description,
})
if err != nil {
return err
}
if options.DryRun {
var outBuilder = bytes.NewBuffer(nil)
out, err := yaml.Marshal(configItem.Secret)
if err != nil {
return err
}
_, err = outBuilder.Write(out)
if err != nil {
return err
}
if configItem.OutputObjects != nil {
for k, object := range configItem.OutputObjects {
_, err = outBuilder.WriteString("# Object: \n ---" + k)
if err != nil {
return err
}
out, err := yaml.Marshal(object)
if err != nil {
return err
}
if _, err := outBuilder.Write(out); err != nil {
return err
}
}
}
_, err = streams.Out.Write(outBuilder.Bytes())
return err
}
if err := inf.CreateOrUpdateConfig(context.Background(), configItem, options.Namespace); err != nil {
return err
}
if len(options.Targets) > 0 {
ads := &config.CreateDistributionSpec{
Targets: []*config.ClusterTarget{},
Configs: []*config.NamespacedName{
&configItem.NamespacedName,
},
}
for _, t := range options.Targets {
ti := strings.Split(t, "/")
if len(ti) == 2 {
ads.Targets = append(ads.Targets, &config.ClusterTarget{
ClusterName: ti[0],
Namespace: ti[1],
})
} else {
ads.Targets = append(ads.Targets, &config.ClusterTarget{
ClusterName: types.ClusterLocalName,
Namespace: ti[0],
})
}
}
name := config.DefaultDistributionName(options.Name)
if err := inf.CreateOrUpdateDistribution(context.Background(), options.Namespace, name, ads); err != nil {
return err
}
}
streams.Infof("the config %s applied successfully\n", options.Name)
return nil
},
}
cmd.Flags().StringVarP(&options.Template, "template", "t", "", "specify the config template name and namespace")
cmd.Flags().StringVarP(&options.File, "file", "f", "", "specify the file name of the config properties")
cmd.Flags().StringArrayVarP(&options.Targets, "target", "", []string{}, "this config will be distributed if this flag is set")
cmd.Flags().BoolVarP(&options.DryRun, "dry-run", "", false, "Dry run to apply the config")
cmd.Flags().StringVarP(&options.Namespace, "namespace", "n", types.DefaultKubeVelaNS, "specify the namespace of the config")
cmd.Flags().StringVarP(&options.Description, "description", "", "", "specify the description of the config")
cmd.Flags().StringVarP(&options.Alias, "alias", "", "", "specify the alias of the config")
return cmd
}
// NewDistributeConfigCommand command for distributing the config
func NewDistributeConfigCommand(f velacmd.Factory, streams util.IOStreams) *cobra.Command {
var options DistributeConfigCommandOptions
distributionExample := templates.Examples(i18n.T(`
# distribute the config(test-registry) from the vela-system namespace to the default namespace in the local cluster.
vela config d test-registry -t default
# distribute the config(test-registry) from the vela-system namespace to the other clusters.
vela config d test-registry -t cluster1/default -t cluster2/default
# recall the config
vela config d test-registry --recall
`))
cmd := &cobra.Command{
Use: "distribute",
Aliases: []string{"d"},
Short: i18n.T("Distribute a config"),
Example: distributionExample,
Annotations: map[string]string{
types.TagCommandType: types.TypeCD,
},
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
inf := config.NewConfigFactory(f.Client())
options.Config = args[0]
name := config.DefaultDistributionName(options.Config)
if options.Recalled {
userInput := &UserInput{
Writer: streams.Out,
Reader: bufio.NewReader(streams.In),
}
if !assumeYes {
userConfirmation := userInput.AskBool("Do you want to recall this config", &UserInputOptions{assumeYes})
if !userConfirmation {
return fmt.Errorf("recalling stopped")
}
}
if err := inf.DeleteDistribution(context.Background(), options.Namespace, name); err != nil {
return err
}
streams.Infof("the distribution %s deleted successfully\n", name)
return nil
}
ads := &config.CreateDistributionSpec{
Targets: []*config.ClusterTarget{},
Configs: []*config.NamespacedName{
{
Name: options.Config,
Namespace: options.Namespace,
},
},
}
for _, t := range options.Targets {
ti := strings.Split(t, "/")
if len(ti) == 2 {
ads.Targets = append(ads.Targets, &config.ClusterTarget{
ClusterName: ti[0],
Namespace: ti[1],
})
} else {
ads.Targets = append(ads.Targets, &config.ClusterTarget{
ClusterName: types.ClusterLocalName,
Namespace: ti[0],
})
}
}
if err := inf.CreateOrUpdateDistribution(context.Background(), options.Namespace, name, ads); err != nil {
return err
}
streams.Infof("the distribution %s applied successfully\n", name)
return nil
},
}
cmd.Flags().StringArrayVarP(&options.Targets, "target", "t", []string{}, "specify the targets that want to distribute,the format is: <clusterName>/<namespace>")
cmd.Flags().StringVarP(&options.Namespace, "namespace", "n", types.DefaultKubeVelaNS, "specify the namespace of the distribution")
cmd.Flags().BoolVarP(&options.Recalled, "recall", "r", false, "this field means recalling the configs from all targets.")
return cmd
}
// ConfigDeleteCommandOptions the options of the command that delete the config.
type ConfigDeleteCommandOptions struct {
Namespace string
Name string
NotRecall bool
}
// NewDeleteConfigCommand command for deleting the config secret
func NewDeleteConfigCommand(f velacmd.Factory, streams util.IOStreams) *cobra.Command {
var options ConfigDeleteCommandOptions
cmd := &cobra.Command{
Use: "delete",
Short: i18n.T("Delete a config."),
Annotations: map[string]string{
types.TagCommandType: types.TypeCD,
},
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
options.Name = args[0]
inf := config.NewConfigFactory(f.Client())
userInput := &UserInput{
Writer: streams.Out,
Reader: bufio.NewReader(streams.In),
}
if !assumeYes {
userConfirmation := userInput.AskBool("Do you want to delete this config", &UserInputOptions{assumeYes})
if !userConfirmation {
return fmt.Errorf("deleting stopped")
}
}
if !options.NotRecall {
if err := inf.DeleteDistribution(context.Background(), options.Namespace, config.DefaultDistributionName(options.Name)); err != nil && !errors.Is(err, config.ErrNotFoundDistribution) {
return err
}
}
if err := inf.DeleteConfig(context.Background(), options.Namespace, options.Name); err != nil {
return err
}
streams.Infof("the config %s deleted successfully\n", options.Name)
return nil
},
}
cmd.Flags().StringVarP(&options.Namespace, "namespace", "n", types.DefaultKubeVelaNS, "specify the namespace of the config")
cmd.Flags().BoolVarP(&options.NotRecall, "not-recall", "", false, "means only deleting the config from the local and do not recall from targets.")
return cmd
}