Files
kubevela/pkg/appfile/template_test.go
Kanchan Dhamane bc15e5b359
Some checks failed
CodeQL / Analyze (go) (push) Failing after 1m43s
Definition-Lint / definition-doc (push) Failing after 6m13s
E2E MultiCluster Test / detect-noop (push) Successful in 24s
E2E Test / detect-noop (push) Successful in 17s
Go / detect-noop (push) Successful in 21s
license / Check for unapproved licenses (push) Failing after 2m38s
Registry / publish-core-images (push) Failing after 40s
Unit-Test / detect-noop (push) Successful in 20s
E2E MultiCluster Test / e2e-multi-cluster-tests (v1.29) (push) Failing after 1m55s
E2E Test / e2e-tests (v1.29) (push) Failing after 1m18s
Go / staticcheck (push) Successful in 18m35s
Go / lint (push) Failing after 19m38s
Go / check-diff (push) Failing after 15m7s
Go / check-core-image-build (push) Failing after 3m45s
Go / check-cli-image-build (push) Failing after 2m23s
Unit-Test / unit-tests (push) Failing after 12m43s
Go / check-windows (push) Has been cancelled
Scorecards supply-chain security / Scorecards analysis (push) Failing after 48s
Feat: Semantic versioning support for Definitions (#6648)
* feature: Add Semantic versioning to KubeVela Definitions

Fixes https://github.com/kubevela/kubevela/issues/6435
Fixes https://github.com/kubevela/kubevela/issues/6534

Changes:
- Adds an optional "Version" field for all Definition Specs.
- Adds the following new validations to Webhooks for Definitions:
	- Validate the "Version" field follows Semantic versioning.
	- Dis-allow conflicting versioning fields ( Name annotation, Spec.Version)
- Adds the following new validations to Webhooks for Application:
	- Dis-allow the use of both the "publishVersion" & "autoUpdate" annotations.
- Enahnce "multiStageComponentApply" feature to support auto updates.

Boy Scout Changes:
- Fixes Plugin e2e tests broken by the fix for 6534.
- Fixes the dryRun and livediff commands to respect the "-n" namespace flag.
- Fixes the Application ValidationWebhook to respect the "-n" namespace flag.

Co-authored-by: Rahul Kumar <35751394+bugbounce@users.noreply.github.com>
Co-authored-by: Chaitanya Reddy <chaitanyareddy0702@gmail.com>
Co-authored-by: Vibhor Chinda <vibhorchinda@gmail.com>
Co-authored-by: Shivin Gopalani <gopalanishivin@gmail.com>

Signed-off-by: kanchan-dhamane <74534570+kanchan-dhamane@users.noreply.github.com>

* feature: Add KEP to define the proposal

Signed-off-by: kanchan-dhamane <74534570+kanchan-dhamane@users.noreply.github.com>

* fix: Rebase and fix merge conflicts

Signed-off-by: kanchan-dhamane <74534570+kanchan-dhamane@users.noreply.github.com>

* Fix: Adds unit test cases

Signed-off-by: kanchan-dhamane <74534570+kanchan-dhamane@users.noreply.github.com>

---------

Signed-off-by: kanchan-dhamane <74534570+kanchan-dhamane@users.noreply.github.com>
Co-authored-by: bugbounce <35751394+bugbounce@users.noreply.github.com>
2025-02-03 11:09:28 +08:00

383 lines
10 KiB
Go

/*
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 appfile
import (
"context"
"testing"
"cuelang.org/go/cue/cuecontext"
"github.com/crossplane/crossplane-runtime/pkg/test"
"github.com/google/go-cmp/cmp"
"github.com/stretchr/testify/assert"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
ktypes "k8s.io/apimachinery/pkg/types"
"sigs.k8s.io/controller-runtime/pkg/client"
"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"
oamutil "github.com/oam-dev/kubevela/pkg/oam/util"
)
func TestLoadComponentTemplate(t *testing.T) {
cueTemplate := `
context: {
name: "test"
}
output: {
apiVersion: "apps/v1"
kind: "Deployment"
spec: {
selector: matchLabels: {
"app.oam.dev/component": context.name
}
template: {
metadata: labels: {
"app.oam.dev/component": context.name
}
spec: {
containers: [{
name: context.name
image: parameter.image
if parameter["cmd"] != _|_ {
command: parameter.cmd
}
}]
}
}
selector:
matchLabels:
"app.oam.dev/component": context.name
}
}
parameter: {
// +usage=Which image would you like to use for your service
// +short=i
image: string
cmd?: [...string]
}
`
var componentDefintion = `
apiVersion: core.oam.dev/v1beta1
kind: ComponentDefinition
metadata:
name: worker
namespace: default
annotations:
definition.oam.dev/description: "Long-running scalable backend worker without network endpoint"
spec:
workload:
definition:
apiVersion: apps/v1
kind: Deployment
extension:
template: |
` + cueTemplate
// Create mock client
tclient := test.MockClient{
MockGet: func(ctx context.Context, key ktypes.NamespacedName, obj client.Object) error {
switch o := obj.(type) {
case *v1beta1.ComponentDefinition:
cd, err := oamutil.UnMarshalStringToComponentDefinition(componentDefintion)
if err != nil {
return err
}
*o = *cd
}
return nil
},
}
var annotations = make(map[string]string)
temp, err := LoadTemplate(context.TODO(), &tclient, "worker", types.TypeComponentDefinition, annotations)
if err != nil {
t.Error(err)
return
}
inst := cuecontext.New().CompileString(temp.TemplateStr)
instDest := cuecontext.New().CompileString(cueTemplate)
s1, _ := inst.Value().String()
s2, _ := instDest.Value().String()
if s1 != s2 {
t.Errorf("parsered template is not correct")
}
}
func TestLoadTraitTemplate(t *testing.T) {
cueTemplate := `
parameter: {
domain: string
http: [string]: int
}
context: {
name: "test"
}
// trait template can have multiple outputs in one trait
outputs: service: {
apiVersion: "v1"
kind: "Service"
metadata:
name: context.name
spec: {
selector:
"app.oam.dev/component": context.name
ports: [
for k, v in parameter.http {
port: v
targetPort: v
},
]
}
}
outputs: ingress: {
apiVersion: "networking.k8s.io/v1beta1"
kind: "Ingress"
metadata:
name: context.name
spec: {
rules: [{
host: parameter.domain
http: {
paths: [
for k, v in parameter.http {
path: k
backend: {
serviceName: context.name
servicePort: v
}
},
]
}
}]
}
}
`
var traitDefintion = `
apiVersion: core.oam.dev/v1beta1
kind: TraitDefinition
metadata:
annotations:
definition.oam.dev/description: "Configures K8s ingress and service to enable web traffic for your service.
Please use route trait in cap center for advanced usage."
name: ingress
namespace: default
spec:
status:
customStatus: |-
if len(context.outputs.ingress.status.loadBalancer.ingress) > 0 {
message: "Visiting URL: " + context.outputs.ingress.spec.rules[0].host + ", IP: " + context.outputs.ingress.status.loadBalancer.ingress[0].ip
}
if len(context.outputs.ingress.status.loadBalancer.ingress) == 0 {
message: "No loadBalancer found, visiting by using 'vela port-forward " + context.appName + " --route'\n"
}
healthPolicy: |
isHealth: len(context.outputs.service.spec.clusterIP) > 0
appliesToWorkloads:
- deployments.apps
schematic:
cue:
template: |
` + cueTemplate
// Create mock client
tclient := test.MockClient{
MockGet: func(ctx context.Context, key ktypes.NamespacedName, obj client.Object) error {
switch o := obj.(type) {
case *v1beta1.TraitDefinition:
wd, err := oamutil.UnMarshalStringToTraitDefinition(traitDefintion)
if err != nil {
return err
}
*o = *wd
}
return nil
},
}
var annotations = make(map[string]string)
temp, err := LoadTemplate(context.TODO(), &tclient, "ingress", types.TypeTrait, annotations)
if err != nil {
t.Error(err)
return
}
inst := cuecontext.New().CompileString(temp.TemplateStr)
instDest := cuecontext.New().CompileString(cueTemplate)
s1, _ := inst.Value().String()
s2, _ := instDest.Value().String()
if s1 != s2 {
t.Errorf("parsered template is not correct")
}
}
func TestLoadSchematicToTemplate(t *testing.T) {
testCases := map[string]struct {
schematic *common.Schematic
status *common.Status
ext *runtime.RawExtension
want *Template
}{
"only tmp": {
schematic: &common.Schematic{CUE: &common.CUE{Template: "t1"}},
want: &Template{
TemplateStr: "t1",
CapabilityCategory: types.CUECategory,
},
},
"no tmp,but has extension": {
ext: &runtime.RawExtension{Raw: []byte(`{"template":"t1"}`)},
want: &Template{
TemplateStr: "t1",
CapabilityCategory: types.CUECategory,
},
},
"no tmp,but has extension without temp": {
ext: &runtime.RawExtension{Raw: []byte(`{"template":{"t1":"t2"}}`)},
want: &Template{
TemplateStr: "",
CapabilityCategory: types.CUECategory,
},
},
"tmp with status": {
schematic: &common.Schematic{CUE: &common.CUE{Template: "t1"}},
status: &common.Status{
CustomStatus: "s1",
HealthPolicy: "h1",
},
want: &Template{
TemplateStr: "t1",
CustomStatus: "s1",
Health: "h1",
CapabilityCategory: types.CUECategory,
},
},
"no tmp only status": {
status: &common.Status{
CustomStatus: "s1",
HealthPolicy: "h1",
},
want: &Template{
CustomStatus: "s1",
Health: "h1",
},
},
"terraform schematic": {
schematic: &common.Schematic{Terraform: &common.Terraform{}},
want: &Template{
CapabilityCategory: types.TerraformCategory,
Terraform: &common.Terraform{},
},
},
}
for reason, casei := range testCases {
gtmp := &Template{}
err := loadSchematicToTemplate(gtmp, casei.status, casei.schematic, casei.ext)
assert.NoError(t, err, reason)
assert.Equal(t, casei.want, gtmp, reason)
}
}
func TestDryRunTemplateLoader(t *testing.T) {
compDefStr := `
apiVersion: core.oam.dev/v1beta1
kind: ComponentDefinition
metadata:
name: myworker
spec:
status:
customStatus: testCustomStatus
healthPolicy: testHealthPolicy
workload:
definition:
apiVersion: apps/v1
kind: Deployment
schematic:
cue:
template: testCUE `
traitDefStr := `
apiVersion: core.oam.dev/v1beta1
kind: TraitDefinition
metadata:
name: myingress
spec:
status:
customStatus: testCustomStatus
healthPolicy: testHealthPolicy
appliesToWorkloads:
- deployments.apps
schematic:
cue:
template: testCUE `
compDef, _ := oamutil.UnMarshalStringToComponentDefinition(compDefStr)
traitDef, _ := oamutil.UnMarshalStringToTraitDefinition(traitDefStr)
unstrctCompDef, _ := oamutil.Object2Unstructured(compDef)
unstrctTraitDef, _ := oamutil.Object2Unstructured(traitDef)
expectedCompTmpl := &Template{
TemplateStr: "testCUE",
Health: "testHealthPolicy",
CustomStatus: "testCustomStatus",
CapabilityCategory: types.CUECategory,
Reference: common.WorkloadTypeDescriptor{
Definition: common.WorkloadGVK{
APIVersion: "apps/v1",
Kind: "Deployment",
},
},
ComponentDefinition: compDef,
}
expectedTraitTmpl := &Template{
TemplateStr: "testCUE",
Health: "testHealthPolicy",
CustomStatus: "testCustomStatus",
CapabilityCategory: types.CUECategory,
TraitDefinition: traitDef,
}
var annotations = make(map[string]string)
dryRunLoadTemplate := DryRunTemplateLoader([]*unstructured.Unstructured{unstrctCompDef, unstrctTraitDef})
compTmpl, err := dryRunLoadTemplate(nil, nil, "myworker", types.TypeComponentDefinition, annotations)
if err != nil {
t.Error("failed load template of component defintion", err)
}
if diff := cmp.Diff(expectedCompTmpl, compTmpl); diff != "" {
t.Fatal("failed load template of component defintion", diff)
}
traitTmpl, err := dryRunLoadTemplate(nil, nil, "myingress", types.TypeTrait, annotations)
if err != nil {
t.Error("failed load template of component defintion", err)
}
if diff := cmp.Diff(expectedTraitTmpl, traitTmpl); diff != "" {
t.Fatal("failed load template of trait definition ", diff)
}
}