/
addon.go
1271 lines (1151 loc) · 40.6 KB
/
addon.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 2021 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 (
"context"
"encoding/json"
"fmt"
"os"
"path/filepath"
"sort"
"strings"
"time"
"github.com/fatih/color"
"github.com/getkin/kin-openapi/openapi3"
"github.com/gosuri/uitable"
"github.com/pkg/errors"
"github.com/spf13/cobra"
"helm.sh/helm/v3/pkg/strvals"
types2 "k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/discovery"
"k8s.io/client-go/rest"
"sigs.k8s.io/controller-runtime/pkg/client"
common2 "github.com/oam-dev/kubevela/apis/core.oam.dev/common"
"github.com/oam-dev/kubevela/apis/core.oam.dev/v1beta1"
"github.com/oam-dev/kubevela/apis/types"
pkgaddon "github.com/oam-dev/kubevela/pkg/addon"
"github.com/oam-dev/kubevela/pkg/oam"
addonutil "github.com/oam-dev/kubevela/pkg/utils/addon"
"github.com/oam-dev/kubevela/pkg/utils/apply"
"github.com/oam-dev/kubevela/pkg/utils/common"
cmdutil "github.com/oam-dev/kubevela/pkg/utils/util"
)
const (
statusEnabled = "enabled"
statusDisabled = "disabled"
statusSuspend = "suspend"
)
var enabledAddonColor = color.New(color.Bold, color.FgGreen)
var (
forceDisable bool
addonRegistry string
addonVersion string
addonClusters string
verboseStatus bool
skipValidate bool
overrideDefs bool
dryRun bool
yes2all bool
)
// NewAddonCommand create `addon` command
func NewAddonCommand(c common.Args, order string, ioStreams cmdutil.IOStreams) *cobra.Command {
cmd := &cobra.Command{
Use: "addon",
Short: "Manage addons for extension.",
Long: "Manage addons for extension.",
Annotations: map[string]string{
types.TagCommandOrder: order,
types.TagCommandType: types.TypeApp,
},
}
cmd.AddCommand(
NewAddonListCommand(c),
NewAddonEnableCommand(c, ioStreams),
NewAddonDisableCommand(c, ioStreams),
NewAddonStatusCommand(c, ioStreams),
NewAddonRegistryCommand(c, ioStreams),
NewAddonUpgradeCommand(c, ioStreams),
NewAddonPackageCommand(c),
NewAddonInitCommand(),
NewAddonPushCommand(c),
)
return cmd
}
// NewAddonListCommand create addon list command
func NewAddonListCommand(c common.Args) *cobra.Command {
cmd := &cobra.Command{
Use: "list",
Aliases: []string{"ls"},
Short: "List addons",
Long: "List addons in KubeVela",
Example: ` List addon by:
vela addon ls
List addons in a specific registry, useful to reveal addons with duplicated names:
vela addon ls --registry <registry-name>
`,
RunE: func(cmd *cobra.Command, args []string) error {
k8sClient, err := c.GetClient()
if err != nil {
return err
}
table, err := listAddons(context.Background(), k8sClient, addonRegistry)
if err != nil {
return err
}
fmt.Println(table.String())
return nil
},
}
cmd.Flags().StringVarP(&addonRegistry, "registry", "r", "", "specify the registry name to list")
return cmd
}
// NewAddonEnableCommand create addon enable command
func NewAddonEnableCommand(c common.Args, ioStream cmdutil.IOStreams) *cobra.Command {
ctx := context.Background()
cmd := &cobra.Command{
Use: "enable",
Aliases: []string{"install"},
Short: "enable an addon",
Long: "enable an addon in cluster.",
Example: ` Enable addon by:
vela addon enable <addon-name>
Enable addon with specify version:
vela addon enable <addon-name> --version <addon-version>
Enable addon for specific clusters, (local means control plane):
vela addon enable <addon-name> --clusters={local,cluster1,cluster2}
Enable addon locally:
vela addon enable <your-local-addon-path>
Enable addon with specified args (the args should be defined in addon's parameters):
vela addon enable <addon-name> <my-parameter-of-addon>=<my-value>
Enable addon with specified registry:
vela addon enable <registryName>/<addonName>
`,
RunE: func(cmd *cobra.Command, args []string) error {
var additionalInfo string
if len(args) < 1 {
return fmt.Errorf("must specify addon name")
}
addonArgs, err := parseAddonArgsToMap(args[1:])
if err != nil {
return err
}
clusterArgs := transClusters(addonClusters)
if len(clusterArgs) != 0 {
addonArgs[types.ClustersArg] = clusterArgs
}
config, err := c.GetConfig()
if err != nil {
return err
}
k8sClient, err := c.GetClient()
if err != nil {
return err
}
dc, err := c.GetDiscoveryClient()
if err != nil {
return err
}
addonOrDir := args[0]
var name = addonOrDir
// inject runtime info
addonArgs[pkgaddon.InstallerRuntimeOption] = map[string]interface{}{
"upgrade": false,
}
var addonName string
if file, err := os.Stat(addonOrDir); err == nil {
if !file.IsDir() {
return fmt.Errorf("%s is not addon dir", addonOrDir)
}
ioStream.Infof(color.New(color.FgYellow).Sprintf("enabling addon by local dir: %s \n", addonOrDir))
// args[0] is a local path install with local dir, use base dir name as addonName
abs, err := filepath.Abs(addonOrDir)
if err != nil {
return errors.Wrapf(err, "directory %s is invalid", addonOrDir)
}
addonName = filepath.Base(abs)
if !yes2all {
if err := checkUninstallFromClusters(ctx, k8sClient, addonName, addonArgs); err != nil {
return err
}
}
additionalInfo, err = enableAddonByLocal(ctx, addonName, addonOrDir, k8sClient, dc, config, addonArgs)
if err != nil {
return err
}
} else {
if filepath.IsAbs(addonOrDir) || strings.HasPrefix(addonOrDir, ".") || strings.HasSuffix(addonOrDir, "/") {
return fmt.Errorf("addon directory %s not found in local file system", addonOrDir)
}
_, addonName, err = splitSpecifyRegistry(name)
if err != nil {
return fmt.Errorf("failed to split addonName and addonRegistry: %w", err)
}
if !yes2all {
if err := checkUninstallFromClusters(ctx, k8sClient, addonName, addonArgs); err != nil {
return err
}
}
additionalInfo, err = enableAddon(ctx, k8sClient, dc, config, name, addonVersion, addonArgs)
if err != nil {
return err
}
}
if dryRun {
return nil
}
fmt.Printf("Addon %s enabled successfully.\n", addonName)
AdditionalEndpointPrinter(ctx, c, k8sClient, addonName, additionalInfo, false)
return nil
},
}
cmd.Flags().StringVarP(&addonVersion, "version", "v", "", "specify the addon version to enable")
cmd.Flags().StringVarP(&addonClusters, types.ClustersArg, "c", "", "specify the runtime-clusters to enable")
cmd.Flags().BoolVarP(&skipValidate, "skip-version-validating", "s", false, "skip validating system version requirement")
cmd.Flags().BoolVarP(&overrideDefs, "override-definitions", "", false, "override existing definitions if conflict with those contained in this addon")
cmd.Flags().BoolVarP(&dryRun, FlagDryRun, "", false, "render all yaml files out without real execute it")
cmd.Flags().BoolVarP(&yes2all, "yes", "y", false, "all checks will be skipped and the default answer is yes for all validation check.")
return cmd
}
// AdditionalEndpointPrinter will print endpoints
func AdditionalEndpointPrinter(ctx context.Context, c common.Args, _ client.Client, name, info string, _ bool) {
err := printAppEndpoints(ctx, addonutil.Addon2AppName(name), types.DefaultKubeVelaNS, Filter{}, c, true)
if err != nil {
fmt.Println("Get application endpoints error:", err)
return
}
if len(info) > 0 {
fmt.Println(info)
}
}
// NewAddonUpgradeCommand create addon upgrade command
func NewAddonUpgradeCommand(c common.Args, ioStream cmdutil.IOStreams) *cobra.Command {
ctx := context.Background()
cmd := &cobra.Command{
Use: "upgrade",
Short: "upgrade an addon",
Long: "upgrade an addon in cluster.",
Example: `
Upgrade addon by:
vela addon upgrade <addon-name>
Upgrade addon with specify version:
vela addon upgrade <addon-name> --version <addon-version>
Upgrade addon for specific clusters, (local means control plane):
vela addon upgrade <addon-name> --clusters={local,cluster1,cluster2}
Upgrade addon locally:
vela addon upgrade <your-local-addon-path>
Upgrade addon with specified args (the args should be defined in addon's parameters):
vela addon upgrade <addon-name> <my-parameter-of-addon>=<my-value>
The specified args will be merged with legacy args, what user specified in 'vela addon enable', and non-empty legacy arg will be overridden by
non-empty new arg
`,
RunE: func(cmd *cobra.Command, args []string) error {
if len(args) < 1 {
return fmt.Errorf("must specify addon name")
}
config, err := c.GetConfig()
if err != nil {
return err
}
k8sClient, err := c.GetClient()
if err != nil {
return err
}
dc, err := c.GetDiscoveryClient()
if err != nil {
return err
}
addonInputArgs, err := parseAddonArgsToMap(args[1:])
if err != nil {
return err
}
clusterArgs := transClusters(addonClusters)
if len(clusterArgs) != 0 {
addonInputArgs[types.ClustersArg] = clusterArgs
}
addonOrDir := args[0]
// inject runtime info
addonInputArgs[pkgaddon.InstallerRuntimeOption] = map[string]interface{}{
"upgrade": true,
}
var name, additionalInfo string
if file, err := os.Stat(addonOrDir); err == nil {
if !file.IsDir() {
return fmt.Errorf("%s is not addon dir", addonOrDir)
}
ioStream.Infof(color.New(color.FgYellow).Sprintf("enabling addon by local dir: %s \n", addonOrDir))
// args[0] is a local path install with local dir
abs, err := filepath.Abs(addonOrDir)
if err != nil {
return errors.Wrapf(err, "cannot open directory %s", addonOrDir)
}
name = filepath.Base(abs)
_, err = pkgaddon.FetchAddonRelatedApp(context.Background(), k8sClient, name)
if err != nil {
return errors.Wrapf(err, "cannot fetch addon related addon %s", name)
}
addonArgs, err := pkgaddon.MergeAddonInstallArgs(ctx, k8sClient, name, addonInputArgs)
if err != nil {
return err
}
additionalInfo, err = enableAddonByLocal(ctx, name, addonOrDir, k8sClient, dc, config, addonArgs)
if err != nil {
return err
}
} else {
if filepath.IsAbs(addonOrDir) || strings.HasPrefix(addonOrDir, ".") || strings.HasSuffix(addonOrDir, "/") {
return fmt.Errorf("addon directory %s not found in local", addonOrDir)
}
name = addonOrDir
_, err = pkgaddon.FetchAddonRelatedApp(context.Background(), k8sClient, addonOrDir)
if err != nil {
return errors.Wrapf(err, "cannot fetch addon related addon %s", addonOrDir)
}
addonArgs, err := pkgaddon.MergeAddonInstallArgs(ctx, k8sClient, name, addonInputArgs)
if err != nil {
return err
}
additionalInfo, err = enableAddon(ctx, k8sClient, dc, config, addonOrDir, addonVersion, addonArgs)
if err != nil {
return err
}
}
fmt.Printf("Addon %s enabled successfully.\n", name)
AdditionalEndpointPrinter(ctx, c, k8sClient, name, additionalInfo, true)
return nil
},
}
cmd.Flags().StringVarP(&addonVersion, "version", "v", "", "specify the addon version to upgrade")
cmd.Flags().StringVarP(&addonClusters, types.ClustersArg, "c", "", "specify the runtime-clusters to upgrade")
cmd.Flags().BoolVarP(&skipValidate, "skip-version-validating", "s", false, "skip validating system version requirement")
cmd.Flags().BoolVarP(&overrideDefs, "override-definitions", "", false, "override existing definitions if conflict with those contained in this addon")
return cmd
}
func parseAddonArgsToMap(args []string) (map[string]interface{}, error) {
res := map[string]interface{}{}
for _, arg := range args {
if err := strvals.ParseInto(arg, res); err != nil {
return nil, err
}
}
return res, nil
}
// NewAddonDisableCommand create addon disable command
func NewAddonDisableCommand(c common.Args, _ cmdutil.IOStreams) *cobra.Command {
cmd := &cobra.Command{
Use: "disable",
Aliases: []string{"uninstall"},
Short: "disable an addon",
Long: "disable an addon in cluster.",
Example: "vela addon disable <addon-name>",
RunE: func(cmd *cobra.Command, args []string) error {
if len(args) < 1 {
return fmt.Errorf("must specify addon name")
}
name := args[0]
k8sClient, err := c.GetClient()
if err != nil {
return err
}
config, err := c.GetConfig()
if err != nil {
return err
}
err = disableAddon(k8sClient, name, config, forceDisable)
if err != nil {
return err
}
fmt.Printf("Successfully disable addon:%s\n", name)
return nil
},
}
cmd.Flags().BoolVarP(&forceDisable, "force", "f", false, "skip checking if applications are still using this addon")
return cmd
}
// NewAddonStatusCommand create addon status command
func NewAddonStatusCommand(c common.Args, ioStream cmdutil.IOStreams) *cobra.Command {
cmd := &cobra.Command{
Use: "status",
Short: "get an addon's status.",
Long: "get an addon's status from cluster.",
Example: "vela addon status <addon-name>",
RunE: func(cmd *cobra.Command, args []string) error {
if len(args) < 1 {
return fmt.Errorf("must specify addon name")
}
name := args[0]
err := statusAddon(name, ioStream, cmd, c)
if err != nil {
return err
}
return nil
},
}
cmd.Flags().BoolVarP(&verboseStatus, "verbose", "v", false, "show addon descriptions and parameters in addition to status")
return cmd
}
// NewAddonInitCommand creates an addon scaffold
func NewAddonInitCommand() *cobra.Command {
var path string
initCmd := pkgaddon.InitCmd{}
cmd := &cobra.Command{
Use: "init",
Short: "create an addon scaffold",
Long: "Create an addon scaffold for quick starting.",
Example: ` Store the scaffold in a different directory:
vela addon init mongodb -p path/to/addon
Add a Helm component:
vela addon init mongodb --helm-repo https://marketplace.azurecr.io/helm/v1/repo --chart mongodb --chart-version 12.1.16
Add resources from URL using ref-objects component
vela addon init my-addon --url https://domain.com/resource.yaml
Use --no-samples options to skip creating sample files
vela addon init my-addon --no-sample
You can combine all the options together.`,
RunE: func(cmd *cobra.Command, args []string) error {
if len(args) < 1 {
return fmt.Errorf("an addon name is required")
}
addonName := args[0]
// Scaffold will be created in ./addonName, unless the user specifies a path
// validity of addon names will be checked later
addonPath := addonName
if len(path) > 0 {
addonPath = path
}
if addonName == "" || addonPath == "" {
return fmt.Errorf("addon name or path should not be empty")
}
initCmd.AddonName = addonName
initCmd.Path = addonPath
return initCmd.CreateScaffold()
},
}
f := cmd.Flags()
f.StringVar(&initCmd.HelmRepoURL, "helm-repo", "", "URL that points to a Helm repo")
f.StringVar(&initCmd.HelmChartName, "chart", "", "Helm Chart name")
f.StringVar(&initCmd.HelmChartVersion, "chart-version", "", "version of the Chart")
f.StringVarP(&path, "path", "p", "", "path to the addon directory (default is ./<addon-name>)")
f.StringArrayVarP(&initCmd.RefObjURLs, "url", "u", []string{}, "add URL resources using ref-object component")
f.BoolVarP(&initCmd.NoSamples, "no-samples", "", false, "do not generate sample files")
f.BoolVarP(&initCmd.Overwrite, "force", "f", false, "overwrite existing addon files")
return cmd
}
// NewAddonPushCommand pushes an addon dir/package to a ChartMuseum
func NewAddonPushCommand(c common.Args) *cobra.Command {
p := &pkgaddon.PushCmd{}
cmd := &cobra.Command{
Use: "push",
Short: "uploads an addon package to ChartMuseum",
Long: `Uploads an addon package to ChartMuseum.
Two arguments are needed <addon directory/package> and <name/URL of ChartMuseum>.
The first argument <addon directory/package> can be:
- your conventional addon directory (containing metadata.yaml). We will package it for you.
- packaged addon (.tgz) generated by 'vela addon package' command
The second argument <name/URL of ChartMuseum> can be:
- registry name (helm type). You can add your ChartMuseum registry using 'vela addon registry add'.
- ChartMuseum URL, e.g. http://localhost:8080`,
Example: `# Push the addon in directory <your-addon> to a ChartMuseum registry named <localcm>
$ vela addon push your-addon localcm
# Push packaged addon mongo-1.0.0.tgz to a ChartMuseum registry at http://localhost:8080
$ vela addon push mongo-1.0.0.tgz http://localhost:8080
# Force push, overwriting existing ones
$ vela addon push your-addon localcm -f
# If you already written your own Chart.yaml and don't want us to generate it for you:
$ vela addon push your-addon localcm --keep-chartmeta
# Note: when using .tgz packages, we will always keep the original Chart.yaml
# In addition to cli flags, you can also use environment variables
$ HELM_REPO_USERNAME=name HELM_REPO_PASSWORD=pswd vela addon push mongo-1.0.0.tgz http://localhost:8080`,
RunE: func(cmd *cobra.Command, args []string) error {
if len(args) != 2 {
return fmt.Errorf("two arguments are needed: addon directory/package, name/URL of Chart repository")
}
c, err := c.GetClient()
if err != nil {
return err
}
p.Client = c
p.Out = cmd.OutOrStdout()
p.ChartName = args[0]
p.RepoName = args[1]
p.SetFieldsFromEnv()
return p.Push(context.Background())
},
}
f := cmd.Flags()
f.StringVarP(&p.ChartVersion, "version", "v", "", "override chart version pre-push")
f.StringVarP(&p.AppVersion, "app-version", "a", "", "override app version pre-push")
f.StringVarP(&p.Username, "username", "u", "", "override HTTP basic auth username [$HELM_REPO_USERNAME]")
f.StringVarP(&p.Password, "password", "p", "", "override HTTP basic auth password [$HELM_REPO_PASSWORD]")
f.StringVarP(&p.AccessToken, "access-token", "", "", "send token in Authorization header [$HELM_REPO_ACCESS_TOKEN]")
f.StringVarP(&p.AuthHeader, "auth-header", "", "", "alternative header to use for token auth [$HELM_REPO_AUTH_HEADER]")
f.StringVarP(&p.ContextPath, "context-path", "", "", "ChartMuseum context path [$HELM_REPO_CONTEXT_PATH]")
f.StringVarP(&p.CaFile, "ca-file", "", "", "verify certificates of HTTPS-enabled servers using this CA bundle [$HELM_REPO_CA_FILE]")
f.StringVarP(&p.CertFile, "cert-file", "", "", "identify HTTPS client using this SSL certificate file [$HELM_REPO_CERT_FILE]")
f.StringVarP(&p.KeyFile, "key-file", "", "", "identify HTTPS client using this SSL key file [$HELM_REPO_KEY_FILE]")
f.BoolVarP(&p.InsecureSkipVerify, "insecure", "", false, "connect to server with an insecure way by skipping certificate verification [$HELM_REPO_INSECURE]")
f.BoolVarP(&p.ForceUpload, "force", "f", false, "force upload even if chart version exists")
f.BoolVarP(&p.UseHTTP, "use-http", "", false, "use HTTP")
f.BoolVarP(&p.KeepChartMetadata, "keep-chartmeta", "", false, "do not update Chart.yaml automatically according to addon metadata (only when addon dir provided)")
f.Int64VarP(&p.Timeout, "timeout", "t", 30, "The duration (in seconds) vela cli will wait to get response from ChartMuseum")
return cmd
}
func enableAddon(ctx context.Context, k8sClient client.Client, dc *discovery.DiscoveryClient, config *rest.Config, name string, version string, args map[string]interface{}) (string, error) {
var err error
var additionalInfo string
registryDS := pkgaddon.NewRegistryDataStore(k8sClient)
registries, err := registryDS.ListRegistries(ctx)
if err != nil {
return "", err
}
registryName, addonName, err := splitSpecifyRegistry(name)
if err != nil {
return "", err
}
if len(registryName) != 0 {
foundRegistry := false
for _, registry := range registries {
if registry.Name == registryName {
foundRegistry = true
}
}
if !foundRegistry {
return "", fmt.Errorf("specified registry %s not exist", registryName)
}
}
for i, registry := range registries {
opts := addonOptions()
if len(registryName) != 0 && registryName != registry.Name {
continue
}
additionalInfo, err = pkgaddon.EnableAddon(ctx, addonName, version, k8sClient, dc, apply.NewAPIApplicator(k8sClient), config, registry, args, nil, pkgaddon.FilterDependencyRegistries(i, registries), opts...)
if errors.Is(err, pkgaddon.ErrNotExist) || errors.Is(err, pkgaddon.ErrFetch) {
continue
}
if unMatchErr := new(pkgaddon.VersionUnMatchError); errors.As(err, unMatchErr) {
// Get available version of the addon
availableVersion, err := unMatchErr.GetAvailableVersion()
if err != nil {
return "", err
}
input := NewUserInput()
if input.AskBool(unMatchErr.Error(), &UserInputOptions{AssumeYes: false}) {
return pkgaddon.EnableAddon(ctx, addonName, availableVersion, k8sClient, dc, apply.NewAPIApplicator(k8sClient), config, registry, args, nil, pkgaddon.FilterDependencyRegistries(i, registries))
}
// The user does not agree to use the version provided by us
return "", fmt.Errorf("you can try another version by command: \"vela addon enable %s --version <version> \" ", addonName)
}
if err != nil {
return "", err
}
if err = waitApplicationRunning(k8sClient, addonName); err != nil {
return "", err
}
return additionalInfo, nil
}
if len(registryName) != 0 {
return "", fmt.Errorf("addon: %s not found in registry %s", addonName, registryName)
}
return "", fmt.Errorf("addon: %s not found in all candidate registries", addonName)
}
func addonOptions() []pkgaddon.InstallOption {
var opts []pkgaddon.InstallOption
if skipValidate || yes2all {
opts = append(opts, pkgaddon.SkipValidateVersion)
}
if overrideDefs || yes2all {
opts = append(opts, pkgaddon.OverrideDefinitions)
}
if dryRun {
opts = append(opts, pkgaddon.DryRunAddon)
}
return opts
}
// enableAddonByLocal enable addon in local dir and return the addon name
func enableAddonByLocal(ctx context.Context, name string, dir string, k8sClient client.Client, dc *discovery.DiscoveryClient, config *rest.Config, args map[string]interface{}) (string, error) {
opts := addonOptions()
info, err := pkgaddon.EnableAddonByLocalDir(ctx, name, dir, k8sClient, dc, apply.NewAPIApplicator(k8sClient), config, args, opts...)
if err != nil {
return "", err
}
if err = waitApplicationRunning(k8sClient, name); err != nil {
return "", err
}
return info, nil
}
func disableAddon(client client.Client, name string, config *rest.Config, force bool) error {
if err := pkgaddon.DisableAddon(context.Background(), client, name, config, force); err != nil {
return err
}
return nil
}
func statusAddon(name string, ioStreams cmdutil.IOStreams, cmd *cobra.Command, c common.Args) error {
k8sClient, err := c.GetClient()
if err != nil {
return err
}
statusString, status, err := generateAddonInfo(k8sClient, name)
if err != nil {
return err
}
fmt.Print(statusString)
if status.AddonPhase != statusEnabled && status.AddonPhase != statusDisabled {
fmt.Printf("diagnose addon info from application %s", addonutil.Addon2AppName(name))
err := printAppStatus(context.Background(), k8sClient, ioStreams, addonutil.Addon2AppName(name), types.DefaultKubeVelaNS, cmd, c, false)
if err != nil {
return err
}
}
return nil
}
func addonNotExist(err error) bool {
if errors.Is(err, pkgaddon.ErrNotExist) || errors.Is(err, pkgaddon.ErrRegistryNotExist) {
return true
}
if strings.Contains(err.Error(), "not found") {
return true
}
return false
}
// generateAddonInfo will get addon status, description, version, dependencies (and whether they are installed),
// and parameters (and their current values).
// The first return value is the formatted string for printing.
// The second return value is just for diagnostic purposes, as it is needed in statusAddon to print diagnostic info.
func generateAddonInfo(c client.Client, name string) (string, pkgaddon.Status, error) {
var res string
var phase string
var installed bool
var addonPackage *pkgaddon.WholeAddonPackage
// Check current addon status
status, err := pkgaddon.GetAddonStatus(context.Background(), c, name)
if err != nil {
return res, status, err
}
// Get addon install package
if verboseStatus || status.AddonPhase == statusDisabled {
// We need the metadata to get descriptions about parameters
addonPackages, err := pkgaddon.FindAddonPackagesDetailFromRegistry(context.Background(), c, []string{name}, nil)
// If the state of addon is not disabled, we don't check the error, because it could be installed from local.
if status.AddonPhase == statusDisabled && err != nil {
if addonNotExist(err) {
return "", pkgaddon.Status{}, fmt.Errorf("addon '%s' not found in cluster or any registry", name)
}
return "", pkgaddon.Status{}, err
}
if len(addonPackages) != 0 {
addonPackage = addonPackages[0]
if status.InstalledRegistry != "" {
for _, ap := range addonPackages {
if ap.RegistryName == status.InstalledRegistry {
addonPackage = ap
break
}
}
}
}
}
switch status.AddonPhase {
case statusEnabled:
installed = true
c := color.New(color.FgGreen)
phase = c.Sprintf("%s", status.AddonPhase)
case statusSuspend:
installed = true
c := color.New(color.FgRed)
phase = c.Sprintf("%s", status.AddonPhase)
case statusDisabled:
c := color.New(color.Faint)
phase = c.Sprintf("%s", status.AddonPhase)
// If the addon is
// 1. disabled,
// 2. does not exist in the registry,
// 3. verbose is on (when off, it is not possible to know whether the addon is in registry or not),
// means the addon does not exist at all.
// So, no need to go further, we return error message saying that we can't find it.
if addonPackage == nil && verboseStatus {
return res, pkgaddon.Status{}, fmt.Errorf("addon %s is not found in registries nor locally installed", name)
}
default:
c := color.New(color.Faint)
phase = c.Sprintf("%s", status.AddonPhase)
}
// Addon name
res += color.New(color.Bold).Sprintf("%s", name)
res += fmt.Sprintf(": %s ", phase)
if installed {
res += fmt.Sprintf("(%s)", status.InstalledVersion)
}
res += "\n"
// Description
// Skip this if addon is installed from local sources.
// Description is fetched from the Internet, which is not useful for local sources.
if status.InstalledRegistry != pkgaddon.LocalAddonRegistryName && addonPackage != nil {
res += fmt.Sprintln(addonPackage.Description)
}
// Installed Clusters
if len(status.Clusters) != 0 {
res += color.New(color.FgHiBlue).Sprint("==> ") + color.New(color.Bold).Sprintln("Installed Clusters")
var ic []string
for c := range status.Clusters {
ic = append(ic, c)
}
sort.Strings(ic)
res += fmt.Sprintln(ic)
}
// Registry name
registryName := status.InstalledRegistry
// Disabled addons will have empty InstalledRegistry, so if the addon exists in the registry, we use the registry name.
if registryName == "" && addonPackage != nil {
registryName = addonPackage.RegistryName
}
if registryName != "" {
res += color.New(color.FgHiBlue).Sprint("==> ") + color.New(color.Bold).Sprintln("Registry Name")
res += fmt.Sprintln(registryName)
}
// If the addon is installed from local sources, or does not exist at all, stop here!
// The following information is fetched from the Internet, which is not useful for local sources.
if registryName == pkgaddon.LocalAddonRegistryName || registryName == "" || addonPackage == nil {
return res, status, nil
}
// Available Versions
res += color.New(color.FgHiBlue).Sprint("==> ") + color.New(color.Bold).Sprintln("Available Versions")
res += genAvailableVersionInfo(addonPackage.AvailableVersions, status.InstalledVersion, 8)
res += "\n"
// Dependencies
dependenciesString, allInstalled := generateDependencyString(c, addonPackage.Dependencies)
res += color.New(color.FgHiBlue).Sprint("==> ") + color.New(color.Bold).Sprint("Dependencies ")
if allInstalled {
res += color.GreenString("✔")
} else {
res += color.RedString("✘")
}
res += "\n"
res += dependenciesString
res += "\n"
// Parameters
parameterString := generateParameterString(status, addonPackage)
if len(parameterString) != 0 {
res += color.New(color.FgHiBlue).Sprint("==> ") + color.New(color.Bold).Sprintln("Parameters")
res += parameterString
}
return res, status, nil
}
func generateParameterString(status pkgaddon.Status, addonPackage *pkgaddon.WholeAddonPackage) string {
ret := ""
if addonPackage.APISchema == nil {
return ret
}
ret = printSchema(addonPackage.APISchema, status.Parameters, 0)
return ret
}
func convertInterface2StringList(l []interface{}) []string {
var strl []string
for _, s := range l {
str, ok := s.(string)
if !ok {
continue
}
strl = append(strl, str)
}
return strl
}
// printSchema prints the parameters in an addon recursively to a string
// Deeper the parameter is nested, more the indentations.
func printSchema(ref *openapi3.Schema, currentParams map[string]interface{}, indent int) string {
ret := ""
if ref == nil {
return ret
}
addIndent := func(n int) string {
r := ""
for i := 0; i < n; i++ {
r += "\t"
}
return r
}
// Required parameters
required := make(map[string]bool)
for _, k := range ref.Required {
required[k] = true
}
for propKey, propValue := range ref.Properties {
desc := propValue.Value.Description
defaultValue := propValue.Value.Default
if defaultValue == nil {
defaultValue = ""
}
required := required[propKey]
// Extra indentation on nested objects
addedIndent := addIndent(indent)
var currentValue string
thisParam, hasParam := currentParams[propKey]
if hasParam {
currentValue = fmt.Sprintf("%#v", thisParam)
switch thisParam.(type) {
case int:
case int64:
case int32:
case float32:
case float64:
case string:
case bool:
default:
if js, err := json.MarshalIndent(thisParam, "", " "); err == nil {
currentValue = strings.ReplaceAll(string(js), "\n", "\n\t "+addedIndent)
}
}
}
// Header: addon: description
ret += addedIndent
ret += color.New(color.FgCyan).Sprintf("-> ")
ret += color.New(color.Bold).Sprint(propKey) + ": "
ret += fmt.Sprintf("%s\n", desc)
// Show current value
if currentValue != "" {
ret += addedIndent
ret += "\tcurrent value: " + color.New(color.FgGreen).Sprintf("%s\n", currentValue)
}
// Show required or not
if required {
ret += addedIndent
ret += "\trequired: "
ret += color.GreenString("✔\n")
}
// Show Enum options
if len(propValue.Value.Enum) > 0 {
ret += addedIndent
ret += "\toptions: \"" + strings.Join(convertInterface2StringList(propValue.Value.Enum), "\", \"") + "\"\n"
}
// Show default value
if defaultValue != "" && currentValue == "" {
ret += addedIndent
ret += "\tdefault: " + fmt.Sprintf("%#v\n", defaultValue)
}
// Object type param, we will get inside the object.
// To show what's inside nested objects.
if propValue.Value.Type == "object" {
nestedParam := make(map[string]interface{})
if hasParam {
nestedParam = currentParams[propKey].(map[string]interface{})
}
ret += printSchema(propValue.Value, nestedParam, indent+1)
}
}
return ret
}
func generateDependencyString(c client.Client, dependencies []*pkgaddon.Dependency) (string, bool) {
if len(dependencies) == 0 {
return "[]", true
}
ret := "["
allDependenciesInstalled := true
for idx, d := range dependencies {
name := d.Name
// Checks if the dependency is enabled, and mark it
status, err := pkgaddon.GetAddonStatus(context.Background(), c, name)
if err != nil {
continue
}
var enabledString string
switch status.AddonPhase {
case statusEnabled:
enabledString = color.GreenString("✔")
case statusSuspend:
enabledString = color.RedString("✔")
default:
enabledString = color.RedString("✘")
allDependenciesInstalled = false
}
ret += fmt.Sprintf("%s %s", name, enabledString)
if idx != len(dependencies)-1 {
ret += ", "
}
}
ret += "]"
return ret, allDependenciesInstalled
}
func listAddons(ctx context.Context, clt client.Client, registry string) (*uitable.Table, error) {
var addons []*pkgaddon.UIData
var err error
registryDS := pkgaddon.NewRegistryDataStore(clt)
registries, err := registryDS.ListRegistries(ctx)
if err != nil {
return nil, err
}
for _, r := range registries {
if registry != "" && r.Name != registry {
continue
}
var addonList []*pkgaddon.UIData
var err error
if !pkgaddon.IsVersionRegistry(r) {
meta, err := r.ListAddonMeta()
if err != nil {
continue
}
addonList, err = r.ListUIData(meta, pkgaddon.CLIMetaOptions)
if err != nil {
continue
}
} else {
versionedRegistry := pkgaddon.BuildVersionedRegistry(r.Name, r.Helm.URL, &common.HTTPOption{
Username: r.Helm.Username,
Password: r.Helm.Password,
InsecureSkipTLS: r.Helm.InsecureSkipTLS,
})
addonList, err = versionedRegistry.ListAddon()