github.com/oam-dev/kubevela@v1.9.11/pkg/policy/override.go (about) 1 /* 2 Copyright 2021 The KubeVela Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package policy 18 19 import ( 20 "context" 21 "encoding/json" 22 "fmt" 23 24 "github.com/pkg/errors" 25 "sigs.k8s.io/controller-runtime/pkg/client" 26 27 oamutil "github.com/oam-dev/kubevela/pkg/oam/util" 28 29 "github.com/oam-dev/kubevela/apis/core.oam.dev/v1alpha1" 30 "github.com/oam-dev/kubevela/apis/core.oam.dev/v1beta1" 31 ) 32 33 // ParseOverridePolicyRelatedDefinitions get definitions inside override policy 34 func ParseOverridePolicyRelatedDefinitions(ctx context.Context, cli client.Client, _ *v1beta1.Application, policy v1beta1.AppPolicy) (compDefs []*v1beta1.ComponentDefinition, traitDefs []*v1beta1.TraitDefinition, err error) { 35 if policy.Properties == nil { 36 return compDefs, traitDefs, fmt.Errorf("override policy %s must not have empty properties", policy.Name) 37 } 38 spec := &v1alpha1.OverridePolicySpec{} 39 if err = json.Unmarshal(policy.Properties.Raw, spec); err != nil { 40 return nil, nil, errors.Wrapf(err, "invalid override policy spec") 41 } 42 componentTypes := map[string]struct{}{} 43 traitTypes := map[string]struct{}{} 44 for _, comp := range spec.Components { 45 if comp.Type != "" { 46 componentTypes[comp.Type] = struct{}{} 47 } 48 for _, trait := range comp.Traits { 49 if trait.Type != "" { 50 traitTypes[trait.Type] = struct{}{} 51 } 52 } 53 } 54 55 for compDefName := range componentTypes { 56 def := &v1beta1.ComponentDefinition{} 57 if err = oamutil.GetDefinition(ctx, cli, def, compDefName); err != nil { 58 return nil, nil, errors.WithMessagef(err, "failed to get %s definition %s for override policy %s", "component", compDefName, policy.Name) 59 } 60 compDefs = append(compDefs, def) 61 } 62 for traitDefName := range traitTypes { 63 def := &v1beta1.TraitDefinition{} 64 if err = oamutil.GetDefinition(ctx, cli, def, traitDefName); err != nil { 65 return nil, nil, errors.WithMessagef(err, "failed to get %s definition %s for override policy %s", "trait", traitDefName, policy.Name) 66 } 67 traitDefs = append(traitDefs, def) 68 } 69 return compDefs, traitDefs, nil 70 }