-
Notifications
You must be signed in to change notification settings - Fork 874
/
factory.go
884 lines (805 loc) · 28.9 KB
/
factory.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
/*
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 config
import (
"context"
"encoding/json"
"errors"
"fmt"
"strings"
"time"
"github.com/getkin/kin-openapi/openapi3"
v1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime"
pkgtypes "k8s.io/apimachinery/pkg/types"
"k8s.io/klog/v2"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/yaml"
workflowv1alpha1 "github.com/kubevela/workflow/api/v1alpha1"
"github.com/oam-dev/kubevela/apis/core.oam.dev/common"
"github.com/oam-dev/kubevela/apis/core.oam.dev/v1alpha1"
"github.com/oam-dev/kubevela/apis/core.oam.dev/v1beta1"
"github.com/oam-dev/kubevela/apis/types"
"github.com/oam-dev/kubevela/pkg/apiserver/domain/model"
"github.com/oam-dev/kubevela/pkg/apiserver/utils"
icontext "github.com/oam-dev/kubevela/pkg/config/context"
"github.com/oam-dev/kubevela/pkg/config/writer"
"github.com/oam-dev/kubevela/pkg/cue"
"github.com/oam-dev/kubevela/pkg/cue/script"
"github.com/oam-dev/kubevela/pkg/oam"
"github.com/oam-dev/kubevela/pkg/utils/apply"
)
// SaveInputPropertiesKey define the key name for saving the input properties in the secret.
const SaveInputPropertiesKey = "input-properties"
// SaveObjectReferenceKey define the key name for saving the outputs objects reference metadata in the secret.
const SaveObjectReferenceKey = "objects-reference"
// SaveExpandedWriterKey define the key name for saving the expanded writer config
const SaveExpandedWriterKey = "expanded-writer"
// SaveSchemaKey define the key name for saving the API schema
const SaveSchemaKey = "schema"
// SaveTemplateKey define the key name for saving the config-template
const SaveTemplateKey = "template"
// TemplateConfigMapNamePrefix the prefix of the configmap name.
const TemplateConfigMapNamePrefix = "config-template-"
// ErrSensitiveConfig means this config can not be read directly.
var ErrSensitiveConfig = errors.New("the config is sensitive")
// ErrNoConfigOrTarget means the config or the target is empty.
var ErrNoConfigOrTarget = errors.New("you must specify the config name and destination to distribute")
// ErrNotFoundDistribution means the app of the distribution is not exist.
var ErrNotFoundDistribution = errors.New("the distribution is not found")
// ErrConfigExist means the config is exist.
var ErrConfigExist = errors.New("the config is exist")
// ErrConfigNotFound means the config is not exist
var ErrConfigNotFound = errors.New("the config is not exist")
// ErrTemplateNotFound means the template is not exist
var ErrTemplateNotFound = errors.New("the template is not exist")
// NamespacedName the namespace and name model
type NamespacedName struct {
Name string `json:"name"`
Namespace string `json:"namespace"`
}
// Template This is the spec of the config template, parse from the cue script.
type Template struct {
NamespacedName
Alias string `json:"alias,omitempty"`
Description string `json:"description,omitempty"`
// Scope defines the usage scope of the configuration template. Provides two options: System or Namespace
// System: The system users could use this template, and the config secret will save in the vela-system namespace.
// Namespace: The config secret will save in the target namespace, such as this namespace belonging to one project.
Scope string `json:"scope"`
// Sensitive means this config config can not be read from the API or the workflow step, only support the safe way, such as Secret.
Sensitive bool `json:"sensitive"`
CreateTime time.Time `json:"createTime"`
Template script.CUE `json:"template"`
ExpandedWriter writer.ExpandedWriterConfig `json:"expandedWriter"`
Schema *openapi3.Schema `json:"schema"`
ConfigMap *v1.ConfigMap `json:"-"`
}
// Metadata users should provide this model.
type Metadata struct {
NamespacedName
Alias string `json:"alias,omitempty"`
Description string `json:"description,omitempty"`
Properties map[string]interface{} `json:"properties"`
}
// Config this is the config model, generated from the template and properties.
type Config struct {
Metadata
CreateTime time.Time
Template Template `json:"template"`
// Secret this is default output way.
Secret *v1.Secret `json:"secret"`
// ExpandedWriterData
ExpandedWriterData *writer.ExpandedWriterData `json:"expandedWriterData"`
// OutputObjects this means users could define other objects.
// This field assign value only on config render stage.
OutputObjects map[string]*unstructured.Unstructured
// ObjectReferences correspond OutputObjects
ObjectReferences []v1.ObjectReference
Targets []*ClusterTargetStatus
}
// ClusterTargetStatus merge the status of the distribution
type ClusterTargetStatus struct {
ClusterTarget
Status string `json:"status"`
Application NamespacedName `json:"application"`
Message string `json:"message"`
}
// ClusterTarget kubernetes delivery target
type ClusterTarget struct {
ClusterName string `json:"clusterName"`
Namespace string `json:"namespace"`
}
// Distribution the config distribution model
type Distribution struct {
Name string `json:"name"`
Namespace string `json:"namespace"`
CreatedTime time.Time `json:"createdTime"`
Configs []*NamespacedName `json:"configs"`
Targets []*ClusterTarget `json:"targets"`
Application pkgtypes.NamespacedName `json:"application"`
Status common.AppStatus `json:"status"`
}
// CreateDistributionSpec the spec of the distribution
type CreateDistributionSpec struct {
Configs []*NamespacedName
Targets []*ClusterTarget
}
// Factory handle the config
type Factory interface {
ParseTemplate(defaultName string, content []byte) (*Template, error)
ParseConfig(ctx context.Context, template NamespacedName, meta Metadata) (*Config, error)
LoadTemplate(ctx context.Context, name, ns string) (*Template, error)
CreateOrUpdateConfigTemplate(ctx context.Context, ns string, it *Template) error
DeleteTemplate(ctx context.Context, ns, name string) error
ListTemplates(ctx context.Context, ns, scope string) ([]*Template, error)
ReadConfig(ctx context.Context, namespace, name string) (map[string]interface{}, error)
GetConfig(ctx context.Context, namespace, name string, withStatus bool) (*Config, error)
ListConfigs(ctx context.Context, namespace, template, scope string, withStatus bool) ([]*Config, error)
DeleteConfig(ctx context.Context, namespace, name string) error
CreateOrUpdateConfig(ctx context.Context, i *Config, ns string) error
CreateOrUpdateDistribution(ctx context.Context, ns, name string, ads *CreateDistributionSpec) error
ListDistributions(ctx context.Context, ns string) ([]*Distribution, error)
DeleteDistribution(ctx context.Context, ns, name string) error
MergeDistributionStatus(ctx context.Context, config *Config, namespace string) error
}
// NewConfigFactory create a config factory instance
func NewConfigFactory(cli client.Client) Factory {
return &kubeConfigFactory{cli: cli, apiApply: apply.NewAPIApplicator(cli)}
}
type kubeConfigFactory struct {
cli client.Client
apiApply *apply.APIApplicator
}
// ParseTemplate parse a config template instance form the cue script
func (k *kubeConfigFactory) ParseTemplate(defaultName string, content []byte) (*Template, error) {
cueScript := script.BuildCUEScriptWithDefaultContext(icontext.DefaultContext, content)
value, err := cueScript.ParseToTemplateValue()
if err != nil {
return nil, fmt.Errorf("the cue script is invalid:%w", err)
}
name, err := value.GetString("metadata", "name")
if err != nil {
if defaultName == "" {
return nil, fmt.Errorf("fail to get the name from the template metadata: %w", err)
}
}
if defaultName != "" {
name = defaultName
}
templateValue, err := value.LookupValue("template")
if err != nil {
return nil, err
}
schema, err := cueScript.ParsePropertiesToSchema("template")
if err != nil {
return nil, fmt.Errorf("the properties of the cue script is invalid:%w", err)
}
alias, err := value.GetString("metadata", "alias")
if err != nil && !IsFieldNotExist(err) {
klog.Warningf("fail to get the alias from the template metadata: %s", err.Error())
}
scope, err := value.GetString("metadata", "scope")
if err != nil && !IsFieldNotExist(err) {
klog.Warningf("fail to get the scope from the template metadata: %s", err.Error())
}
sensitive, err := value.GetBool("metadata", "sensitive")
if err != nil && !IsFieldNotExist(err) {
klog.Warningf("fail to get the sensitive from the template metadata: %s", err.Error())
}
template := &Template{
NamespacedName: NamespacedName{
Name: name,
},
Alias: alias,
Scope: scope,
Sensitive: sensitive,
Template: cueScript,
Schema: schema,
ExpandedWriter: writer.ParseExpandedWriterConfig(templateValue),
}
var configmap v1.ConfigMap
configmap.Name = TemplateConfigMapNamePrefix + template.Name
configmap.Data = map[string]string{
SaveTemplateKey: string(template.Template),
}
if template.Schema != nil {
data, err := yaml.Marshal(template.Schema)
if err != nil {
return nil, err
}
configmap.Data[SaveSchemaKey] = string(data)
}
data, err := yaml.Marshal(template.ExpandedWriter)
if err != nil {
return nil, err
}
configmap.Data[SaveExpandedWriterKey] = string(data)
configmap.Labels = map[string]string{
types.LabelConfigCatalog: types.VelaCoreConfig,
types.LabelConfigScope: template.Scope,
}
configmap.Annotations = map[string]string{
types.AnnotationConfigDescription: template.Description,
types.AnnotationConfigAlias: template.Alias,
types.AnnotationConfigSensitive: fmt.Sprintf("%t", template.Sensitive),
}
template.ConfigMap = &configmap
return template, nil
}
// IsFieldNotExist check whether the error type is the field not found
func IsFieldNotExist(err error) bool {
return strings.Contains(err.Error(), "not exist")
}
// CreateOrUpdateConfigTemplate parse and update the config template
func (k *kubeConfigFactory) CreateOrUpdateConfigTemplate(ctx context.Context, ns string, it *Template) error {
if ns != "" {
it.ConfigMap.Namespace = ns
}
return k.apiApply.Apply(ctx, it.ConfigMap, apply.DisableUpdateAnnotation(), apply.Quiet())
}
func convertConfigMap2Template(cm v1.ConfigMap) (*Template, error) {
if cm.Labels == nil || cm.Annotations == nil {
return nil, fmt.Errorf("this configmap is not a valid config-template")
}
it := &Template{
NamespacedName: NamespacedName{
Name: strings.Replace(cm.Name, TemplateConfigMapNamePrefix, "", 1),
Namespace: cm.Namespace,
},
Alias: cm.Annotations[types.AnnotationConfigAlias],
Description: cm.Annotations[types.AnnotationConfigDescription],
Sensitive: cm.Annotations[types.AnnotationConfigSensitive] == "true",
Scope: cm.Labels[types.LabelConfigScope],
CreateTime: cm.CreationTimestamp.Time,
Template: script.CUE(cm.Data[SaveTemplateKey]),
}
if cm.Data[SaveSchemaKey] != "" {
var schema openapi3.Schema
err := yaml.Unmarshal([]byte(cm.Data[SaveSchemaKey]), &schema)
if err != nil {
return nil, fmt.Errorf("fail to parse the schema: %w", err)
}
it.Schema = &schema
}
if cm.Data[SaveExpandedWriterKey] != "" {
var config writer.ExpandedWriterConfig
err := yaml.Unmarshal([]byte(cm.Data[SaveExpandedWriterKey]), &config)
if err != nil {
return nil, fmt.Errorf("fail to parse the schema: %w", err)
}
it.ExpandedWriter = config
}
return it, nil
}
// DeleteTemplate delete the config template
func (k *kubeConfigFactory) DeleteTemplate(ctx context.Context, ns, name string) error {
var configmap v1.ConfigMap
if err := k.cli.Get(ctx, pkgtypes.NamespacedName{Namespace: ns, Name: TemplateConfigMapNamePrefix + name}, &configmap); err != nil {
if apierrors.IsNotFound(err) {
return fmt.Errorf("the config template %s not found", name)
}
return fmt.Errorf("fail to delete the config template %s:%w", name, err)
}
return k.cli.Delete(ctx, &configmap)
}
// ListTemplates list the config templates
func (k *kubeConfigFactory) ListTemplates(ctx context.Context, ns, scope string) ([]*Template, error) {
var list = &v1.ConfigMapList{}
selector, err := labels.Parse(fmt.Sprintf("%s=%s", types.LabelConfigCatalog, types.VelaCoreConfig))
if err != nil {
return nil, err
}
if err := k.cli.List(ctx, list,
client.MatchingLabelsSelector{Selector: selector},
client.InNamespace(ns)); err != nil {
return nil, err
}
var templates []*Template
for _, item := range list.Items {
it, err := convertConfigMap2Template(item)
if err != nil {
klog.Warningf("fail to parse the configmap %s:%s", item.Name, err.Error())
}
if it != nil {
if scope == "" || it.Scope == scope {
templates = append(templates, it)
}
}
}
return templates, nil
}
// LoadTemplate load the template
func (k *kubeConfigFactory) LoadTemplate(ctx context.Context, name, ns string) (*Template, error) {
var cm v1.ConfigMap
if err := k.cli.Get(ctx, pkgtypes.NamespacedName{Namespace: ns, Name: TemplateConfigMapNamePrefix + name}, &cm); err != nil {
if apierrors.IsNotFound(err) {
return nil, ErrTemplateNotFound
}
return nil, err
}
return convertConfigMap2Template(cm)
}
// ParseConfig merge the properties to template and build a config instance
// If the templateName is empty, means creating a secret without the template.
func (k *kubeConfigFactory) ParseConfig(ctx context.Context,
template NamespacedName, meta Metadata,
) (*Config, error) {
var secret v1.Secret
config := &Config{
Metadata: meta,
Secret: &secret,
}
if template.Name != "" {
template, err := k.LoadTemplate(ctx, template.Name, template.Namespace)
if err != nil {
return nil, err
}
contextValue := icontext.ConfigRenderContext{
Name: meta.Name,
Namespace: meta.Namespace,
}
// Render the output secret
output, err := template.Template.RunAndOutput(contextValue, meta.Properties)
if err != nil && !cue.IsFieldNotExist(err) {
return nil, err
}
if output != nil {
if err := output.UnmarshalTo(&secret); err != nil {
return nil, fmt.Errorf("the output format must be secret")
}
}
if secret.Type == "" {
secret.Type = v1.SecretType(fmt.Sprintf("%s/%s", "", template.Name))
}
if secret.Labels == nil {
secret.Labels = map[string]string{}
}
secret.Labels[types.LabelConfigCatalog] = types.VelaCoreConfig
secret.Labels[types.LabelConfigType] = template.Name
secret.Labels[types.LabelConfigType] = template.Name
secret.Labels[types.LabelConfigScope] = template.Scope
if secret.Annotations == nil {
secret.Annotations = map[string]string{}
}
secret.Annotations[types.AnnotationConfigSensitive] = fmt.Sprintf("%t", template.Sensitive)
secret.Annotations[types.AnnotationConfigTemplateNamespace] = template.Namespace
config.Template = *template
// Render the expanded writer configuration
data, err := writer.RenderForExpandedWriter(template.ExpandedWriter, config.Template.Template, contextValue, meta.Properties)
if err != nil {
return nil, fmt.Errorf("fail to render the content for the expanded writer:%w ", err)
}
config.ExpandedWriterData = data
// Render the outputs objects
outputs, err := template.Template.RunAndOutput(contextValue, meta.Properties, "template", "outputs")
if err != nil && !cue.IsFieldNotExist(err) {
return nil, err
}
if outputs != nil {
var objects = map[string]interface{}{}
if err := outputs.UnmarshalTo(&objects); err != nil {
return nil, fmt.Errorf("the outputs is invalid %w", err)
}
var objectReferences []v1.ObjectReference
config.OutputObjects = make(map[string]*unstructured.Unstructured)
for k := range objects {
if ob, ok := objects[k].(map[string]interface{}); ok {
obj := &unstructured.Unstructured{Object: ob}
config.OutputObjects[k] = obj
objectReferences = append(objectReferences, v1.ObjectReference{
Kind: obj.GetKind(),
Namespace: obj.GetNamespace(),
Name: obj.GetName(),
APIVersion: obj.GetAPIVersion(),
})
}
}
objectReferenceJSON, err := json.Marshal(objectReferences)
if err != nil {
return nil, err
}
if secret.Data == nil {
secret.Data = map[string][]byte{}
}
secret.Data[SaveObjectReferenceKey] = objectReferenceJSON
}
} else {
secret.Labels = map[string]string{
types.LabelConfigCatalog: types.VelaCoreConfig,
types.LabelConfigType: "",
}
secret.Annotations = map[string]string{}
}
secret.Namespace = meta.Namespace
if secret.Name == "" {
secret.Name = meta.Name
}
secret.Annotations[types.AnnotationConfigAlias] = meta.Alias
secret.Annotations[types.AnnotationConfigDescription] = meta.Description
pp, err := json.Marshal(meta.Properties)
if err != nil {
return nil, err
}
if secret.Data == nil {
secret.Data = map[string][]byte{}
}
secret.Data[SaveInputPropertiesKey] = pp
return config, nil
}
// ReadConfig read the config secret
func (k *kubeConfigFactory) ReadConfig(ctx context.Context, namespace, name string) (map[string]interface{}, error) {
var secret v1.Secret
if err := k.cli.Get(ctx, pkgtypes.NamespacedName{Namespace: namespace, Name: name}, &secret); err != nil {
return nil, err
}
if secret.Annotations[types.AnnotationConfigSensitive] == "true" {
return nil, ErrSensitiveConfig
}
properties := secret.Data[SaveInputPropertiesKey]
var input = map[string]interface{}{}
if err := json.Unmarshal(properties, &input); err != nil {
return nil, err
}
return input, nil
}
func (k *kubeConfigFactory) GetConfig(ctx context.Context, namespace, name string, withStatus bool) (*Config, error) {
var secret v1.Secret
if err := k.cli.Get(ctx, pkgtypes.NamespacedName{Namespace: namespace, Name: name}, &secret); err != nil {
if apierrors.IsNotFound(err) {
return nil, ErrConfigNotFound
}
return nil, err
}
if secret.Annotations[types.AnnotationConfigSensitive] == "true" {
return nil, ErrSensitiveConfig
}
item, err := convertSecret2Config(&secret)
if err != nil {
return nil, err
}
if withStatus {
if err := k.MergeDistributionStatus(ctx, item, item.Namespace); err != nil && !errors.Is(err, ErrNotFoundDistribution) {
klog.Warningf("fail to merge the status %s:%s", item.Name, err.Error())
}
}
return item, nil
}
// CreateOrUpdateConfig create or update the config.
// Write the expand config to the target server.
func (k *kubeConfigFactory) CreateOrUpdateConfig(ctx context.Context, i *Config, ns string) error {
var secret v1.Secret
if err := k.cli.Get(ctx, pkgtypes.NamespacedName{Namespace: i.Namespace, Name: i.Name}, &secret); err == nil {
if secret.Labels[types.LabelConfigType] != i.Template.Name {
return ErrConfigExist
}
}
if err := k.apiApply.Apply(ctx, i.Secret, apply.Quiet()); err != nil {
return fmt.Errorf("fail to apply the secret: %w", err)
}
for key, obj := range i.OutputObjects {
if err := k.apiApply.Apply(ctx, obj, apply.Quiet()); err != nil {
return fmt.Errorf("fail to apply the object %s: %w", key, err)
}
}
readConfig := func(ctx context.Context, namespace, name string) (map[string]interface{}, error) {
return k.ReadConfig(ctx, namespace, name)
}
if i.ExpandedWriterData != nil {
if errs := writer.Write(ctx, i.ExpandedWriterData, readConfig); len(errs) > 0 {
return errs[0]
}
}
return nil
}
func (k *kubeConfigFactory) ListConfigs(ctx context.Context, namespace, template, scope string, withStatus bool) ([]*Config, error) {
var list = &v1.SecretList{}
requirement := fmt.Sprintf("%s=%s", types.LabelConfigCatalog, types.VelaCoreConfig)
if template != "" {
requirement = fmt.Sprintf("%s,%s=%s", requirement, types.LabelConfigType, template)
}
if scope != "" {
requirement = fmt.Sprintf("%s,%s=%s", requirement, types.LabelConfigScope, scope)
}
selector, err := labels.Parse(requirement)
if err != nil {
return nil, err
}
if err := k.cli.List(ctx, list,
client.MatchingLabelsSelector{Selector: selector},
client.InNamespace(namespace)); err != nil {
return nil, err
}
var configs []*Config
for i := range list.Items {
item := list.Items[i]
it, err := convertSecret2Config(&item)
if err != nil {
klog.Warningf("fail to parse the secret %s:%s", item.Name, err.Error())
}
if it != nil {
if withStatus {
if err := k.MergeDistributionStatus(ctx, it, it.Namespace); err != nil && !errors.Is(err, ErrNotFoundDistribution) {
klog.Warningf("fail to merge the status %s:%s", item.Name, err.Error())
}
}
configs = append(configs, it)
}
}
return configs, nil
}
func (k *kubeConfigFactory) DeleteConfig(ctx context.Context, namespace, name string) error {
var secret v1.Secret
if err := k.cli.Get(ctx, pkgtypes.NamespacedName{Namespace: namespace, Name: name}, &secret); err != nil {
if apierrors.IsNotFound(err) {
return fmt.Errorf("the config %s not found", name)
}
return fmt.Errorf("fail to delete the config %s:%w", name, err)
}
if secret.Labels[types.LabelConfigCatalog] != types.VelaCoreConfig {
return fmt.Errorf("found a secret but is not a config")
}
if objects, exist := secret.Data[SaveObjectReferenceKey]; exist {
var objectReferences []v1.ObjectReference
if err := json.Unmarshal(objects, &objectReferences); err != nil {
return err
}
for _, obj := range objectReferences {
if err := k.cli.Delete(ctx, convertObjectReference2Unstructured(obj)); err != nil && !apierrors.IsNotFound(err) {
return fmt.Errorf("fail to clear the object %s:%w", obj.Name, err)
}
}
}
return k.cli.Delete(ctx, &secret)
}
func (k *kubeConfigFactory) MergeDistributionStatus(ctx context.Context, config *Config, namespace string) error {
app := &v1beta1.Application{}
if err := k.cli.Get(ctx, pkgtypes.NamespacedName{Namespace: namespace, Name: DefaultDistributionName(config.Name)}, app); err != nil {
if apierrors.IsNotFound(err) {
return ErrNotFoundDistribution
}
return err
}
var targets []*ClusterTargetStatus
for _, policy := range app.Spec.Policies {
if policy.Type == v1alpha1.TopologyPolicyType {
status := workflowv1alpha1.WorkflowStepPhasePending
message := ""
if app.Status.Workflow != nil {
for _, step := range app.Status.Workflow.Steps {
if policy.Name == strings.Replace(step.Name, "deploy-", "", 1) {
status = step.Phase
message = step.Message
}
}
}
var spec v1alpha1.TopologyPolicySpec
if err := json.Unmarshal(policy.Properties.Raw, &spec); err == nil {
for _, clu := range spec.Clusters {
targets = append(targets, &ClusterTargetStatus{
ClusterTarget: ClusterTarget{
Namespace: spec.Namespace,
ClusterName: clu,
},
Application: NamespacedName{Name: app.Name, Namespace: app.Namespace},
Status: string(status),
Message: message,
})
}
}
}
}
config.Targets = append(config.Targets, targets...)
return nil
}
func (k *kubeConfigFactory) CreateOrUpdateDistribution(ctx context.Context, ns, name string, ads *CreateDistributionSpec) error {
policies := convertTarget2TopologyPolicy(ads.Targets)
if len(policies) == 0 {
return ErrNoConfigOrTarget
}
// create the share policy
shareSpec := v1alpha1.SharedResourcePolicySpec{
Rules: []v1alpha1.SharedResourcePolicyRule{{
Selector: v1alpha1.ResourcePolicyRuleSelector{
CompNames: []string{name},
},
}},
}
properties, err := json.Marshal(shareSpec)
if err == nil {
policies = append(policies, v1beta1.AppPolicy{
Type: v1alpha1.SharedResourcePolicyType,
Name: "share-config",
Properties: &runtime.RawExtension{
Raw: properties,
},
})
}
var objects []map[string]string
for _, s := range ads.Configs {
objects = append(objects, map[string]string{
"name": s.Name,
"namespace": s.Namespace,
"resource": "secret",
})
}
if len(objects) == 0 {
return ErrNoConfigOrTarget
}
objectsBytes, err := json.Marshal(map[string][]map[string]string{"objects": objects})
if err != nil {
return err
}
reqByte, err := json.Marshal(ads)
if err != nil {
return err
}
distribution := &v1beta1.Application{
ObjectMeta: metav1.ObjectMeta{
Name: name,
Namespace: ns,
Labels: map[string]string{
model.LabelSourceOfTruth: model.FromInner,
// This label will override the secret label, then change the catalog of the distributed secrets.
types.LabelConfigCatalog: types.CatalogConfigDistribution,
},
Annotations: map[string]string{
types.AnnotationConfigDistributionSpec: string(reqByte),
oam.AnnotationPublishVersion: utils.GenerateVersion("config"),
},
},
Spec: v1beta1.ApplicationSpec{
Components: []common.ApplicationComponent{
{
Name: name,
Type: v1alpha1.RefObjectsComponentType,
Properties: &runtime.RawExtension{Raw: objectsBytes},
},
},
Policies: policies,
},
}
return k.apiApply.Apply(ctx, distribution, apply.Quiet())
}
func (k *kubeConfigFactory) ListDistributions(ctx context.Context, ns string) ([]*Distribution, error) {
var apps v1beta1.ApplicationList
if err := k.cli.List(ctx, &apps, client.MatchingLabels{
model.LabelSourceOfTruth: model.FromInner,
types.LabelConfigCatalog: types.CatalogConfigDistribution,
}, client.InNamespace(ns)); err != nil {
return nil, err
}
var list []*Distribution
for _, app := range apps.Items {
dis := &Distribution{
Name: app.Name,
Namespace: app.Namespace,
CreatedTime: app.CreationTimestamp.Time,
Application: pkgtypes.NamespacedName{
Namespace: app.Namespace,
Name: app.Name,
},
Status: app.Status,
}
if spec, ok := app.Annotations[types.AnnotationConfigDistributionSpec]; ok {
var req CreateDistributionSpec
if err := json.Unmarshal([]byte(spec), &req); err == nil {
dis.Targets = req.Targets
dis.Configs = req.Configs
}
}
list = append(list, dis)
}
return list, nil
}
func (k *kubeConfigFactory) DeleteDistribution(ctx context.Context, ns, name string) error {
app := &v1beta1.Application{
ObjectMeta: metav1.ObjectMeta{
Namespace: ns,
Name: name,
},
}
if err := k.cli.Delete(ctx, app); err != nil {
if apierrors.IsNotFound(err) {
return ErrNotFoundDistribution
}
return err
}
return nil
}
func convertTarget2TopologyPolicy(targets []*ClusterTarget) (policies []v1beta1.AppPolicy) {
for _, target := range targets {
policySpec := v1alpha1.TopologyPolicySpec{
Placement: v1alpha1.Placement{
Clusters: []string{target.ClusterName},
},
Namespace: target.Namespace,
}
properties, err := json.Marshal(policySpec)
if err == nil {
policies = append(policies, v1beta1.AppPolicy{
Type: v1alpha1.TopologyPolicyType,
Name: fmt.Sprintf("%s-%s", target.ClusterName, target.Namespace),
Properties: &runtime.RawExtension{
Raw: properties,
},
})
}
}
return
}
func convertSecret2Config(se *v1.Secret) (*Config, error) {
if se == nil || se.Labels == nil {
return nil, fmt.Errorf("this secret is not a valid config secret")
}
config := &Config{
Metadata: Metadata{
NamespacedName: NamespacedName{
Name: se.Name,
Namespace: se.Namespace,
},
},
CreateTime: se.CreationTimestamp.Time,
Secret: se,
Template: Template{
NamespacedName: NamespacedName{
Name: se.Labels[types.LabelConfigType],
},
},
}
if se.Annotations != nil {
config.Alias = se.Annotations[types.AnnotationConfigAlias]
config.Description = se.Annotations[types.AnnotationConfigDescription]
config.Template.Namespace = se.Annotations[types.AnnotationConfigTemplateNamespace]
config.Template.Sensitive = se.Annotations[types.AnnotationConfigSensitive] == "true"
}
if !config.Template.Sensitive && len(se.Data[SaveInputPropertiesKey]) > 0 {
var properties = map[string]interface{}{}
if err := yaml.Unmarshal(se.Data[SaveInputPropertiesKey], &properties); err != nil {
return nil, err
}
config.Properties = properties
}
if !config.Template.Sensitive {
config.Secret = se
} else {
seCope := se.DeepCopy()
seCope.Data = nil
seCope.StringData = nil
config.Secret = seCope
}
if content, ok := se.Data[SaveObjectReferenceKey]; ok {
var objectReferences []v1.ObjectReference
if err := json.Unmarshal(content, &objectReferences); err != nil {
klog.Warningf("the object references are invalid, config:%s", se.Name)
}
config.ObjectReferences = objectReferences
}
return config, nil
}
func convertObjectReference2Unstructured(ref v1.ObjectReference) *unstructured.Unstructured {
var obj unstructured.Unstructured
obj.SetAPIVersion(ref.APIVersion)
obj.SetNamespace(ref.Namespace)
obj.SetKind(ref.Kind)
obj.SetName(ref.Name)
return &obj
}
// DefaultDistributionName generate the distribution name by a config name
func DefaultDistributionName(configName string) string {
return fmt.Sprintf("distribute-%s", configName)
}