From e66f2a5290da61e3f9fe71329aa3026a88717737 Mon Sep 17 00:00:00 2001 From: odubajDT <93584209+odubajDT@users.noreply.github.com> Date: Fri, 2 Jun 2023 08:35:50 +0200 Subject: [PATCH 01/44] feat: integrate python-runtime into pipelines (#1505) Signed-off-by: odubajDT Signed-off-by: geoffrey1330 --- .../actions/deploy-klt-on-cluster/action.yml | 11 ++-- .github/workflows/CI.yaml | 14 +++-- .github/workflows/e2e-test.yml | 6 +- .github/workflows/helm-checks.yaml | 4 +- .github/workflows/integration-test.yml | 4 +- .github/workflows/load-test.yml | 4 +- .github/workflows/performance-test.yml | 4 +- .github/workflows/release.yml | 2 + .github/workflows/security-scans.yml | 1 + .github/workflows/validate-semantic-pr.yml | 1 + helm/chart/README.md | 55 ++++++++++--------- helm/chart/doc.yaml | 3 +- helm/chart/values.yaml | 1 + operator/config/manager/manager.yaml | 2 + python-runtime/Dockerfile | 2 +- renovate.json | 1 + 16 files changed, 66 insertions(+), 49 deletions(-) diff --git a/.github/actions/deploy-klt-on-cluster/action.yml b/.github/actions/deploy-klt-on-cluster/action.yml index 3580330321..2b911b3574 100644 --- a/.github/actions/deploy-klt-on-cluster/action.yml +++ b/.github/actions/deploy-klt-on-cluster/action.yml @@ -11,8 +11,8 @@ inputs: description: "Kubernetes that should be used" # renovate: datasource=github-releases depName=kubernetes/kubernetes default: "v1.25.3" - functions_runtime_tag: - description: "Tag for the functions runner image" + runtime_tag: + description: "Tag for the runner image" required: true cluster-name: required: false @@ -61,7 +61,9 @@ runs: run: | echo "Installing KLT using manifests" sed -i 's/imagePullPolicy: Always/imagePullPolicy: Never/g' ~/download/artifacts/lifecycle-operator-manifest-test/release.yaml - sed -i 's/ghcr.io\/keptn\/functions-runtime:.*/localhost:5000\/keptn\/functions-runtime:${{ inputs.functions_runtime_tag }}/g' \ + sed -i 's/ghcr.io\/keptn\/functions-runtime:.*/localhost:5000\/keptn\/functions-runtime:${{ inputs.runtime_tag }}/g' \ + ~/download/artifacts/lifecycle-operator-manifest-test/release.yaml + sed -i 's/ghcr.io\/keptn\/python-runtime:.*/localhost:5000\/keptn\/python-runtime:${{ inputs.runtime_tag }}/g' \ ~/download/artifacts/lifecycle-operator-manifest-test/release.yaml kubectl create namespace keptn-lifecycle-toolkit-system kubectl apply -f ~/download/artifacts/lifecycle-operator-manifest-test @@ -89,6 +91,7 @@ runs: --set scheduler.scheduler.imagePullPolicy=Never \ --set lifecycleOperator.manager.imagePullPolicy=Never \ --set metricsOperator.manager.imagePullPolicy=Never \ - --set lifecycleOperator.manager.env.functionRunnerImage=localhost:5000/keptn/functions-runtime:${{ inputs.functions_runtime_tag }} \ + --set lifecycleOperator.manager.env.functionRunnerImage=localhost:5000/keptn/functions-runtime:${{ inputs.runtime_tag }} \ + --set lifecycleOperator.manager.env.pythonRunnerImage=localhost:5000/keptn/python-runtime:${{ inputs.runtime_tag }} \ --set certificateOperator.manager.imagePullPolicy=Never \ --debug --wait --timeout 1m diff --git a/.github/workflows/CI.yaml b/.github/workflows/CI.yaml index 806961b7ec..2397a30498 100644 --- a/.github/workflows/CI.yaml +++ b/.github/workflows/CI.yaml @@ -125,6 +125,8 @@ jobs: folder: "scheduler/" - name: "functions-runtime" folder: "functions-runtime/" + - name: "python-runtime" + folder: "python-runtime/" - name: "certificate-operator" folder: "klt-cert-manager/" steps: @@ -174,14 +176,14 @@ jobs: run: make controller-gen - name: Generate release.yaml - if: matrix.config.name != 'functions-runtime' + if: matrix.config.name != 'functions-runtime' && matrix.config.name != 'python-runtime' working-directory: ./${{ matrix.config.folder }} env: CHART_APPVERSION: dev-${{ env.DATETIME }} run: make release-manifests - name: Upload release.yaml for tests - if: matrix.config.name != 'functions-runtime' + if: matrix.config.name != 'functions-runtime' && matrix.config.name != 'python-runtime' uses: actions/upload-artifact@v3 with: name: ${{ matrix.config.name }}-manifest-test @@ -196,28 +198,28 @@ jobs: name: Integration Tests needs: [prepare_ci_run, build_image] with: - functions_runtime_tag: dev-${{ needs.prepare_ci_run.outputs.DATETIME }} + runtime_tag: dev-${{ needs.prepare_ci_run.outputs.DATETIME }} uses: ./.github/workflows/integration-test.yml load-tests: name: Load Tests needs: [prepare_ci_run, build_image] with: - functions_runtime_tag: dev-${{ needs.prepare_ci_run.outputs.DATETIME }} + runtime_tag: dev-${{ needs.prepare_ci_run.outputs.DATETIME }} uses: ./.github/workflows/load-test.yml e2e_tests: name: End to End Tests needs: [prepare_ci_run, build_image] with: - functions_runtime_tag: dev-${{ needs.prepare_ci_run.outputs.DATETIME }} + runtime_tag: dev-${{ needs.prepare_ci_run.outputs.DATETIME }} uses: ./.github/workflows/e2e-test.yml performance_tests: name: Performance Tests needs: [prepare_ci_run, build_image] with: - functions_runtime_tag: dev-${{ needs.prepare_ci_run.outputs.DATETIME }} + runtime_tag: dev-${{ needs.prepare_ci_run.outputs.DATETIME }} uses: ./.github/workflows/performance-test.yml helm_charts_build: diff --git a/.github/workflows/e2e-test.yml b/.github/workflows/e2e-test.yml index 1724b27d1d..22d6ec9e4f 100644 --- a/.github/workflows/e2e-test.yml +++ b/.github/workflows/e2e-test.yml @@ -2,8 +2,8 @@ name: E2E-Test on: workflow_call: inputs: - functions_runtime_tag: - description: "Tag for the functions runner image" + runtime_tag: + description: "Tag for the runner image" type: "string" required: true env: @@ -30,7 +30,7 @@ jobs: - name: Setup cluster uses: ./.github/actions/deploy-klt-on-cluster with: - functions_runtime_tag: ${{ inputs.functions_runtime_tag }} + runtime_tag: ${{ inputs.runtime_tag }} - name: Run E2E Tests ${{ matrix.config.name }} working-directory: ${{ matrix.config.folder }} diff --git a/.github/workflows/helm-checks.yaml b/.github/workflows/helm-checks.yaml index 91085570e5..09e81665b5 100644 --- a/.github/workflows/helm-checks.yaml +++ b/.github/workflows/helm-checks.yaml @@ -62,6 +62,8 @@ jobs: folder: "scheduler/" - name: "functions-runtime" folder: "functions-runtime/" + - name: "python-runtime" + folder: "python-runtime/" - name: "certificate-operator" folder: "klt-cert-manager/" steps: @@ -141,6 +143,6 @@ jobs: name: Integration Tests needs: [prepare_ci_run, build_helm_chart] with: - functions_runtime_tag: dev-${{ needs.prepare_ci_run.outputs.DATETIME }} + runtime_tag: dev-${{ needs.prepare_ci_run.outputs.DATETIME }} helm-install: true uses: ./.github/workflows/integration-test.yml diff --git a/.github/workflows/integration-test.yml b/.github/workflows/integration-test.yml index 99b40971b1..da07c14d4c 100644 --- a/.github/workflows/integration-test.yml +++ b/.github/workflows/integration-test.yml @@ -2,7 +2,7 @@ name: Integration-Test on: workflow_call: inputs: - functions_runtime_tag: + runtime_tag: description: "Tag for the functions runner image" type: "string" required: true @@ -29,7 +29,7 @@ jobs: - name: Setup cluster uses: ./.github/actions/deploy-klt-on-cluster with: - functions_runtime_tag: ${{ inputs.functions_runtime_tag }} + runtime_tag: ${{ inputs.runtime_tag }} helm-install: ${{ inputs.helm-install }} - name: Install and expose Prometheus diff --git a/.github/workflows/load-test.yml b/.github/workflows/load-test.yml index e2ef034484..7e49d61098 100644 --- a/.github/workflows/load-test.yml +++ b/.github/workflows/load-test.yml @@ -2,7 +2,7 @@ name: Load Tests on: workflow_call: inputs: - functions_runtime_tag: + runtime_tag: description: "Tag for the functions runner image" type: "string" required: true @@ -25,7 +25,7 @@ jobs: - name: Setup cluster uses: ./.github/actions/deploy-klt-on-cluster with: - functions_runtime_tag: ${{ inputs.functions_runtime_tag }} + runtime_tag: ${{ inputs.runtime_tag }} - name: Install and expose Prometheus uses: ./.github/actions/deploy-prometheus-on-cluster diff --git a/.github/workflows/performance-test.yml b/.github/workflows/performance-test.yml index 2195cca7b0..b5384ab281 100644 --- a/.github/workflows/performance-test.yml +++ b/.github/workflows/performance-test.yml @@ -2,7 +2,7 @@ name: Performance Tests on: workflow_call: inputs: - functions_runtime_tag: + runtime_tag: description: "Tag for the functions runner image" type: "string" required: true @@ -23,7 +23,7 @@ jobs: - name: Setup cluster uses: ./.github/actions/deploy-klt-on-cluster with: - functions_runtime_tag: ${{ inputs.functions_runtime_tag }} + runtime_tag: ${{ inputs.runtime_tag }} - name: Execute Performance Tests working-directory: operator diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index a85b6920fb..ada4bdfd90 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -51,6 +51,8 @@ jobs: folder: "scheduler/" - name: "functions-runtime" folder: "functions-runtime/" + - name: "python-runtime" + folder: "python-runtime/" - name: "certificate-operator" folder: "klt-cert-manager/" runs-on: ubuntu-22.04 diff --git a/.github/workflows/security-scans.yml b/.github/workflows/security-scans.yml index dd88c12b46..3d35c6e9fb 100644 --- a/.github/workflows/security-scans.yml +++ b/.github/workflows/security-scans.yml @@ -192,6 +192,7 @@ jobs: matrix: image: - "functions-runtime" + - "python-runtime" - "lifecycle-operator" - "metrics-operator" - "scheduler" diff --git a/.github/workflows/validate-semantic-pr.yml b/.github/workflows/validate-semantic-pr.yml index 7ca94fa61c..180aadde17 100644 --- a/.github/workflows/validate-semantic-pr.yml +++ b/.github/workflows/validate-semantic-pr.yml @@ -39,6 +39,7 @@ jobs: cert-manager metrics-operator functions-runtime + python-runtime dashboards examples # Configure that a scope must always be provided. diff --git a/helm/chart/README.md b/helm/chart/README.md index 20901aa590..bd1aa24c9f 100644 --- a/helm/chart/README.md +++ b/helm/chart/README.md @@ -71,33 +71,34 @@ checks ### Keptn Lifecycle Operator controller -| Name | Description | Value | -| ----------------------------------------------------------------------------- | --------------------------------------------------------------- | ---------------------------------------- | -| `lifecycleOperator.manager.containerSecurityContext` | Sets security context privileges | | -| `lifecycleOperator.manager.containerSecurityContext.allowPrivilegeEscalation` | | `false` | -| `lifecycleOperator.manager.containerSecurityContext.capabilities.drop` | | `["ALL"]` | -| `lifecycleOperator.manager.containerSecurityContext.privileged` | | `false` | -| `lifecycleOperator.manager.containerSecurityContext.runAsGroup` | | `65532` | -| `lifecycleOperator.manager.containerSecurityContext.runAsNonRoot` | | `true` | -| `lifecycleOperator.manager.containerSecurityContext.runAsUser` | | `65532` | -| `lifecycleOperator.manager.containerSecurityContext.seccompProfile.type` | | `RuntimeDefault` | -| `lifecycleOperator.manager.env.keptnAppControllerLogLevel` | sets the log level of Keptn App Controller | `0` | -| `lifecycleOperator.manager.env.keptnAppCreationRequestControllerLogLevel` | sets the log level of Keptn App Creation Request Controller | `0` | -| `lifecycleOperator.manager.env.keptnAppVersionControllerLogLevel` | sets the log level of Keptn AppVersion Controller | `0` | -| `lifecycleOperator.manager.env.keptnEvaluationControllerLogLevel` | sets the log level of Keptn Evaluation Controller | `0` | -| `lifecycleOperator.manager.env.keptnTaskControllerLogLevel` | sets the log level of Keptn Task Controller | `0` | -| `lifecycleOperator.manager.env.keptnTaskDefinitionControllerLogLevel` | sets the log level of Keptn TaskDefinition Controller | `0` | -| `lifecycleOperator.manager.env.keptnWorkloadControllerLogLevel` | sets the log level of Keptn Workload Controller | `0` | -| `lifecycleOperator.manager.env.keptnWorkloadInstanceControllerLogLevel` | sets the log level of Keptn WorkloadInstance Controller | `0` | -| `lifecycleOperator.manager.env.optionsControllerLogLevel` | sets the log level of Keptn Options Controller | `0` | -| `lifecycleOperator.manager.env.otelCollectorUrl` | Sets the URL for the open telemetry collector | `otel-collector:4317` | -| `lifecycleOperator.manager.env.functionRunnerImage` | specify image for task runtime | `ghcr.io/keptn/functions-runtime:v0.7.1` | -| `lifecycleOperator.manager.image.repository` | specify registry for manager image | `ghcr.io/keptn/lifecycle-operator` | -| `lifecycleOperator.manager.image.tag` | select tag for manager image | `v0.7.1` | -| `lifecycleOperator.manager.imagePullPolicy` | specify pull policy for manager image | `Always` | -| `lifecycleOperator.manager.livenessProbe` | custom livenessprobe for manager container | | -| `lifecycleOperator.manager.readinessProbe` | custom readinessprobe for manager container | | -| `lifecycleOperator.manager.resources` | specify limits and requests for manager container | | +| Name | Description | Value | +| ----------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | ---------------------------------------- | +| `lifecycleOperator.manager.containerSecurityContext` | Sets security context privileges | | +| `lifecycleOperator.manager.containerSecurityContext.allowPrivilegeEscalation` | | `false` | +| `lifecycleOperator.manager.containerSecurityContext.capabilities.drop` | | `["ALL"]` | +| `lifecycleOperator.manager.containerSecurityContext.privileged` | | `false` | +| `lifecycleOperator.manager.containerSecurityContext.runAsGroup` | | `65532` | +| `lifecycleOperator.manager.containerSecurityContext.runAsNonRoot` | | `true` | +| `lifecycleOperator.manager.containerSecurityContext.runAsUser` | | `65532` | +| `lifecycleOperator.manager.containerSecurityContext.seccompProfile.type` | | `RuntimeDefault` | +| `lifecycleOperator.manager.env.keptnAppControllerLogLevel` | sets the log level of Keptn App Controller | `0` | +| `lifecycleOperator.manager.env.keptnAppCreationRequestControllerLogLevel` | sets the log level of Keptn App Creation Request Controller | `0` | +| `lifecycleOperator.manager.env.keptnAppVersionControllerLogLevel` | sets the log level of Keptn AppVersion Controller | `0` | +| `lifecycleOperator.manager.env.keptnEvaluationControllerLogLevel` | sets the log level of Keptn Evaluation Controller | `0` | +| `lifecycleOperator.manager.env.keptnTaskControllerLogLevel` | sets the log level of Keptn Task Controller | `0` | +| `lifecycleOperator.manager.env.keptnTaskDefinitionControllerLogLevel` | sets the log level of Keptn TaskDefinition Controller | `0` | +| `lifecycleOperator.manager.env.keptnWorkloadControllerLogLevel` | sets the log level of Keptn Workload Controller | `0` | +| `lifecycleOperator.manager.env.keptnWorkloadInstanceControllerLogLevel` | sets the log level of Keptn WorkloadInstance Controller | `0` | +| `lifecycleOperator.manager.env.optionsControllerLogLevel` | sets the log level of Keptn Options Controller | `0` | +| `lifecycleOperator.manager.env.otelCollectorUrl` | Sets the URL for the open telemetry collector | `otel-collector:4317` | +| `lifecycleOperator.manager.env.functionRunnerImage` | specify image for task runtime with Deno runner | `ghcr.io/keptn/functions-runtime:v0.7.1` | +| `lifecycleOperator.manager.env.pythonRunnerImage` | specify image for task runtime with python runner | `ghcr.io/keptn/python-runtime:0.0.0` | +| `lifecycleOperator.manager.image.repository` | specify registry for manager image | `ghcr.io/keptn/lifecycle-operator` | +| `lifecycleOperator.manager.image.tag` | select tag for manager image | `v0.7.1` | +| `lifecycleOperator.manager.imagePullPolicy` | specify pull policy for manager image | `Always` | +| `lifecycleOperator.manager.livenessProbe` | custom livenessprobe for manager container | | +| `lifecycleOperator.manager.readinessProbe` | custom readinessprobe for manager container | | +| `lifecycleOperator.manager.resources` | specify limits and requests for manager container | | ### Keptn Metrics Operator common diff --git a/helm/chart/doc.yaml b/helm/chart/doc.yaml index af7c3a986e..214df7688e 100644 --- a/helm/chart/doc.yaml +++ b/helm/chart/doc.yaml @@ -132,7 +132,8 @@ ## @param lifecycleOperator.manager.env.optionsControllerLogLevel sets the log level of Keptn Options Controller ## @param lifecycleOperator.manager.env.otelCollectorUrl Sets the URL for the open telemetry collector -## @param lifecycleOperator.manager.env.functionRunnerImage specify image for task runtime +## @param lifecycleOperator.manager.env.functionRunnerImage specify image for task runtime with Deno runner +## @param lifecycleOperator.manager.env.pythonRunnerImage specify image for task runtime with python runner ## @param lifecycleOperator.manager.image.repository specify registry for manager image ## @param lifecycleOperator.manager.image.tag select tag for manager image diff --git a/helm/chart/values.yaml b/helm/chart/values.yaml index 0d3daeb98c..c519eb15b3 100644 --- a/helm/chart/values.yaml +++ b/helm/chart/values.yaml @@ -78,6 +78,7 @@ lifecycleOperator: keptnWorkloadInstanceControllerLogLevel: "0" optionsControllerLogLevel: "0" otelCollectorUrl: otel-collector:4317 + pythonRunnerImage: ghcr.io/keptn/python-runtime:0.0.0 image: repository: ghcr.io/keptn/lifecycle-operator tag: v0.7.1 diff --git a/operator/config/manager/manager.yaml b/operator/config/manager/manager.yaml index 1bd9d121e6..0dfd57d2e6 100644 --- a/operator/config/manager/manager.yaml +++ b/operator/config/manager/manager.yaml @@ -67,6 +67,8 @@ spec: fieldPath: metadata.name - name: FUNCTION_RUNNER_IMAGE value: ghcr.io/keptn/functions-runtime:v0.7.1 # x-release-please-version + - name: PYTHON_RUNNER_IMAGE + value: ghcr.io/keptn/python-runtime:0.0.0 # x-release-please-version - name: OTEL_COLLECTOR_URL value: otel-collector:4317 - name: KEPTN_APP_CONTROLLER_LOG_LEVEL diff --git a/python-runtime/Dockerfile b/python-runtime/Dockerfile index 062f7301a4..6c3a18fbbb 100644 --- a/python-runtime/Dockerfile +++ b/python-runtime/Dockerfile @@ -1,4 +1,4 @@ -FROM python:3.9 AS production +FROM python:3.9-alpine AS production LABEL org.opencontainers.image.source="https://github.com/keptn/lifecycle-toolkit" \ org.opencontainers.image.url="https://keptn.sh" \ diff --git a/renovate.json b/renovate.json index 94473248ed..08430c60b2 100644 --- a/renovate.json +++ b/renovate.json @@ -26,6 +26,7 @@ "ghcr.io/keptn/lifecycle-operator", "ghcr.io/keptn/scheduler", "ghcr.io/keptn/functions-runtime", + "ghcr.io/keptn/python-runtime", "ghcr.io/keptn/certificate-operator", "ghcr.io/keptn/metrics-operator" ], From 2af1475457a9ae4995626533f421c84b96ee1efe Mon Sep 17 00:00:00 2001 From: geoffrey1330 Date: Fri, 2 Jun 2023 10:00:38 +0100 Subject: [PATCH 02/44] added validating webhook for TaskDefinitions Signed-off-by: geoffrey1330 --- operator/PROJECT | 7 + .../v1alpha3/keptntaskdefinition_webhook.go | 64 +++++++++ .../lifecycle/v1alpha3/webhook_suite_test.go | 132 ++++++++++++++++++ .../v1alpha3/zz_generated.deepcopy.go | 2 +- operator/config/certmanager/certificate.yaml | 39 ++++++ .../config/certmanager/kustomization.yaml | 5 + .../config/certmanager/kustomizeconfig.yaml | 16 +++ .../config/default/manager_webhook_patch.yaml | 23 +++ .../default/webhookcainjection_patch.yaml | 29 ++++ operator/main.go | 31 ++-- 10 files changed, 334 insertions(+), 14 deletions(-) create mode 100644 operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook.go create mode 100644 operator/apis/lifecycle/v1alpha3/webhook_suite_test.go create mode 100644 operator/config/certmanager/certificate.yaml create mode 100644 operator/config/certmanager/kustomization.yaml create mode 100644 operator/config/certmanager/kustomizeconfig.yaml create mode 100644 operator/config/default/manager_webhook_patch.yaml create mode 100644 operator/config/default/webhookcainjection_patch.yaml diff --git a/operator/PROJECT b/operator/PROJECT index 5e2a1e5003..30e8c4b73f 100644 --- a/operator/PROJECT +++ b/operator/PROJECT @@ -1,3 +1,7 @@ +# Code generated by tool. DO NOT EDIT. +# This file is used to track the info used to scaffold your project +# and allow the plugins properly work. +# More info: https://book.kubebuilder.io/reference/project-config.html domain: keptn.sh layout: - go.kubebuilder.io/v3 @@ -234,6 +238,9 @@ resources: kind: KeptnTaskDefinition path: github.com/keptn/lifecycle-toolkit/operator/apis/lifecycle/v1alpha3 version: v1alpha3 + webhooks: + validation: true + webhookVersion: v1 - api: crdVersion: v1 namespaced: true diff --git a/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook.go b/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook.go new file mode 100644 index 0000000000..3cd1270bd4 --- /dev/null +++ b/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook.go @@ -0,0 +1,64 @@ +/* +Copyright 2022. + +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 v1alpha3 + +import ( + "k8s.io/apimachinery/pkg/runtime" + ctrl "sigs.k8s.io/controller-runtime" + logf "sigs.k8s.io/controller-runtime/pkg/log" + "sigs.k8s.io/controller-runtime/pkg/webhook" +) + +// log is for logging in this package. +var keptntaskdefinitionlog = logf.Log.WithName("keptntaskdefinition-resource") + +func (r *KeptnTaskDefinition) SetupWebhookWithManager(mgr ctrl.Manager) error { + return ctrl.NewWebhookManagedBy(mgr). + For(r). + Complete() +} + +// TODO(user): EDIT THIS FILE! THIS IS SCAFFOLDING FOR YOU TO OWN! + +// TODO(user): change verbs to "verbs=create;update;delete" if you want to enable deletion validation. +//+kubebuilder:webhook:path=/validate-lifecycle-keptn-sh-v1alpha3-keptntaskdefinition,mutating=false,failurePolicy=fail,sideEffects=None,groups=lifecycle.keptn.sh,resources=keptntaskdefinitions,verbs=create;update,versions=v1alpha3,name=vkeptntaskdefinition.kb.io,admissionReviewVersions=v1 + +var _ webhook.Validator = &KeptnTaskDefinition{} + +// ValidateCreate implements webhook.Validator so a webhook will be registered for the type +func (r *KeptnTaskDefinition) ValidateCreate() error { + keptntaskdefinitionlog.Info("validate create", "name", r.Name) + + // TODO(user): fill in your validation logic upon object creation. + return nil +} + +// ValidateUpdate implements webhook.Validator so a webhook will be registered for the type +func (r *KeptnTaskDefinition) ValidateUpdate(old runtime.Object) error { + keptntaskdefinitionlog.Info("validate update", "name", r.Name) + + // TODO(user): fill in your validation logic upon object update. + return nil +} + +// ValidateDelete implements webhook.Validator so a webhook will be registered for the type +func (r *KeptnTaskDefinition) ValidateDelete() error { + keptntaskdefinitionlog.Info("validate delete", "name", r.Name) + + // TODO(user): fill in your validation logic upon object deletion. + return nil +} diff --git a/operator/apis/lifecycle/v1alpha3/webhook_suite_test.go b/operator/apis/lifecycle/v1alpha3/webhook_suite_test.go new file mode 100644 index 0000000000..dccf30d753 --- /dev/null +++ b/operator/apis/lifecycle/v1alpha3/webhook_suite_test.go @@ -0,0 +1,132 @@ +/* +Copyright 2022. + +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 v1alpha3 + +import ( + "context" + "crypto/tls" + "fmt" + "net" + "path/filepath" + "testing" + "time" + + . "github.com/onsi/ginkgo/v2" + . "github.com/onsi/gomega" + + admissionv1beta1 "k8s.io/api/admission/v1beta1" + //+kubebuilder:scaffold:imports + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/client-go/rest" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/envtest" + logf "sigs.k8s.io/controller-runtime/pkg/log" + "sigs.k8s.io/controller-runtime/pkg/log/zap" +) + +// These tests use Ginkgo (BDD-style Go testing framework). Refer to +// http://onsi.github.io/ginkgo/ to learn more about Ginkgo. + +var cfg *rest.Config +var k8sClient client.Client +var testEnv *envtest.Environment +var ctx context.Context +var cancel context.CancelFunc + +func TestAPIs(t *testing.T) { + RegisterFailHandler(Fail) + + RunSpecs(t, "Webhook Suite") +} + +var _ = BeforeSuite(func() { + logf.SetLogger(zap.New(zap.WriteTo(GinkgoWriter), zap.UseDevMode(true))) + + ctx, cancel = context.WithCancel(context.TODO()) + + By("bootstrapping test environment") + testEnv = &envtest.Environment{ + CRDDirectoryPaths: []string{filepath.Join("..", "..", "..", "config", "crd", "bases")}, + ErrorIfCRDPathMissing: false, + WebhookInstallOptions: envtest.WebhookInstallOptions{ + Paths: []string{filepath.Join("..", "..", "..", "config", "webhook")}, + }, + } + + var err error + // cfg is defined in this file globally. + cfg, err = testEnv.Start() + Expect(err).NotTo(HaveOccurred()) + Expect(cfg).NotTo(BeNil()) + + scheme := runtime.NewScheme() + err = AddToScheme(scheme) + Expect(err).NotTo(HaveOccurred()) + + err = admissionv1beta1.AddToScheme(scheme) + Expect(err).NotTo(HaveOccurred()) + + //+kubebuilder:scaffold:scheme + + k8sClient, err = client.New(cfg, client.Options{Scheme: scheme}) + Expect(err).NotTo(HaveOccurred()) + Expect(k8sClient).NotTo(BeNil()) + + // start webhook server using Manager + webhookInstallOptions := &testEnv.WebhookInstallOptions + mgr, err := ctrl.NewManager(cfg, ctrl.Options{ + Scheme: scheme, + Host: webhookInstallOptions.LocalServingHost, + Port: webhookInstallOptions.LocalServingPort, + CertDir: webhookInstallOptions.LocalServingCertDir, + LeaderElection: false, + MetricsBindAddress: "0", + }) + Expect(err).NotTo(HaveOccurred()) + + err = (&KeptnTaskDefinition{}).SetupWebhookWithManager(mgr) + Expect(err).NotTo(HaveOccurred()) + + //+kubebuilder:scaffold:webhook + + go func() { + defer GinkgoRecover() + err = mgr.Start(ctx) + Expect(err).NotTo(HaveOccurred()) + }() + + // wait for the webhook server to get ready + dialer := &net.Dialer{Timeout: time.Second} + addrPort := fmt.Sprintf("%s:%d", webhookInstallOptions.LocalServingHost, webhookInstallOptions.LocalServingPort) + Eventually(func() error { + conn, err := tls.DialWithDialer(dialer, "tcp", addrPort, &tls.Config{InsecureSkipVerify: true}) + if err != nil { + return err + } + conn.Close() + return nil + }).Should(Succeed()) + +}) + +var _ = AfterSuite(func() { + cancel() + By("tearing down the test environment") + err := testEnv.Stop() + Expect(err).NotTo(HaveOccurred()) +}) diff --git a/operator/apis/lifecycle/v1alpha3/zz_generated.deepcopy.go b/operator/apis/lifecycle/v1alpha3/zz_generated.deepcopy.go index cc68f44e91..e7bd2204bc 100644 --- a/operator/apis/lifecycle/v1alpha3/zz_generated.deepcopy.go +++ b/operator/apis/lifecycle/v1alpha3/zz_generated.deepcopy.go @@ -25,7 +25,7 @@ import ( "github.com/keptn/lifecycle-toolkit/operator/apis/lifecycle/v1alpha3/common" "go.opentelemetry.io/otel/propagation" "k8s.io/api/core/v1" - runtime "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime" ) // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. diff --git a/operator/config/certmanager/certificate.yaml b/operator/config/certmanager/certificate.yaml new file mode 100644 index 0000000000..f587f5bc9d --- /dev/null +++ b/operator/config/certmanager/certificate.yaml @@ -0,0 +1,39 @@ +# The following manifests contain a self-signed issuer CR and a certificate CR. +# More document can be found at https://docs.cert-manager.io +# WARNING: Targets CertManager v1.0. Check https://cert-manager.io/docs/installation/upgrading/ for breaking changes. +apiVersion: cert-manager.io/v1 +kind: Issuer +metadata: + labels: + app.kubernetes.io/name: issuer + app.kubernetes.io/instance: selfsigned-issuer + app.kubernetes.io/component: certificate + app.kubernetes.io/created-by: keptn-lifecycle-toolkit + app.kubernetes.io/part-of: keptn-lifecycle-toolkit + app.kubernetes.io/managed-by: kustomize + name: selfsigned-issuer + namespace: system +spec: + selfSigned: {} +--- +apiVersion: cert-manager.io/v1 +kind: Certificate +metadata: + labels: + app.kubernetes.io/name: certificate + app.kubernetes.io/instance: serving-cert + app.kubernetes.io/component: certificate + app.kubernetes.io/created-by: keptn-lifecycle-toolkit + app.kubernetes.io/part-of: keptn-lifecycle-toolkit + app.kubernetes.io/managed-by: kustomize + name: serving-cert # this name should match the one appeared in kustomizeconfig.yaml + namespace: system +spec: + # $(SERVICE_NAME) and $(SERVICE_NAMESPACE) will be substituted by kustomize + dnsNames: + - $(SERVICE_NAME).$(SERVICE_NAMESPACE).svc + - $(SERVICE_NAME).$(SERVICE_NAMESPACE).svc.cluster.local + issuerRef: + kind: Issuer + name: selfsigned-issuer + secretName: webhook-server-cert # this secret will not be prefixed, since it's not managed by kustomize diff --git a/operator/config/certmanager/kustomization.yaml b/operator/config/certmanager/kustomization.yaml new file mode 100644 index 0000000000..bebea5a595 --- /dev/null +++ b/operator/config/certmanager/kustomization.yaml @@ -0,0 +1,5 @@ +resources: +- certificate.yaml + +configurations: +- kustomizeconfig.yaml diff --git a/operator/config/certmanager/kustomizeconfig.yaml b/operator/config/certmanager/kustomizeconfig.yaml new file mode 100644 index 0000000000..e631f77736 --- /dev/null +++ b/operator/config/certmanager/kustomizeconfig.yaml @@ -0,0 +1,16 @@ +# This configuration is for teaching kustomize how to update name ref and var substitution +nameReference: +- kind: Issuer + group: cert-manager.io + fieldSpecs: + - kind: Certificate + group: cert-manager.io + path: spec/issuerRef/name + +varReference: +- kind: Certificate + group: cert-manager.io + path: spec/commonName +- kind: Certificate + group: cert-manager.io + path: spec/dnsNames diff --git a/operator/config/default/manager_webhook_patch.yaml b/operator/config/default/manager_webhook_patch.yaml new file mode 100644 index 0000000000..738de350b7 --- /dev/null +++ b/operator/config/default/manager_webhook_patch.yaml @@ -0,0 +1,23 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + name: controller-manager + namespace: system +spec: + template: + spec: + containers: + - name: manager + ports: + - containerPort: 9443 + name: webhook-server + protocol: TCP + volumeMounts: + - mountPath: /tmp/k8s-webhook-server/serving-certs + name: cert + readOnly: true + volumes: + - name: cert + secret: + defaultMode: 420 + secretName: webhook-server-cert diff --git a/operator/config/default/webhookcainjection_patch.yaml b/operator/config/default/webhookcainjection_patch.yaml new file mode 100644 index 0000000000..c7cbe14322 --- /dev/null +++ b/operator/config/default/webhookcainjection_patch.yaml @@ -0,0 +1,29 @@ +# This patch add annotation to admission webhook config and +# the variables $(CERTIFICATE_NAMESPACE) and $(CERTIFICATE_NAME) will be substituted by kustomize. +apiVersion: admissionregistration.k8s.io/v1 +kind: MutatingWebhookConfiguration +metadata: + labels: + app.kubernetes.io/name: mutatingwebhookconfiguration + app.kubernetes.io/instance: mutating-webhook-configuration + app.kubernetes.io/component: webhook + app.kubernetes.io/created-by: keptn-lifecycle-toolkit + app.kubernetes.io/part-of: keptn-lifecycle-toolkit + app.kubernetes.io/managed-by: kustomize + name: mutating-webhook-configuration + annotations: + cert-manager.io/inject-ca-from: $(CERTIFICATE_NAMESPACE)/$(CERTIFICATE_NAME) +--- +apiVersion: admissionregistration.k8s.io/v1 +kind: ValidatingWebhookConfiguration +metadata: + labels: + app.kubernetes.io/name: validatingwebhookconfiguration + app.kubernetes.io/instance: validating-webhook-configuration + app.kubernetes.io/component: webhook + app.kubernetes.io/created-by: keptn-lifecycle-toolkit + app.kubernetes.io/part-of: keptn-lifecycle-toolkit + app.kubernetes.io/managed-by: kustomize + name: validating-webhook-configuration + annotations: + cert-manager.io/inject-ca-from: $(CERTIFICATE_NAMESPACE)/$(CERTIFICATE_NAME) diff --git a/operator/main.go b/operator/main.go index 3c1b5f2378..50af730da9 100644 --- a/operator/main.go +++ b/operator/main.go @@ -29,6 +29,20 @@ import ( certCommon "github.com/keptn/lifecycle-toolkit/klt-cert-manager/pkg/common" "github.com/keptn/lifecycle-toolkit/klt-cert-manager/pkg/webhook" metricsapi "github.com/keptn/lifecycle-toolkit/metrics-operator/api/v1alpha3" + "github.com/prometheus/client_golang/prometheus/promhttp" + "go.opentelemetry.io/otel" + otelprom "go.opentelemetry.io/otel/exporters/prometheus" + "go.opentelemetry.io/otel/sdk/metric" + corev1 "k8s.io/api/core/v1" + "k8s.io/apimachinery/pkg/runtime" + utilruntime "k8s.io/apimachinery/pkg/util/runtime" + clientgoscheme "k8s.io/client-go/kubernetes/scheme" + ctrl "sigs.k8s.io/controller-runtime" + ctrlclient "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/healthz" + "sigs.k8s.io/controller-runtime/pkg/log/zap" + ctrlWebhook "sigs.k8s.io/controller-runtime/pkg/webhook" + lifecyclev1alpha1 "github.com/keptn/lifecycle-toolkit/operator/apis/lifecycle/v1alpha1" lifecyclev1alpha2 "github.com/keptn/lifecycle-toolkit/operator/apis/lifecycle/v1alpha2" lifecyclev1alpha3 "github.com/keptn/lifecycle-toolkit/operator/apis/lifecycle/v1alpha3" @@ -44,19 +58,6 @@ import ( "github.com/keptn/lifecycle-toolkit/operator/controllers/lifecycle/keptnworkloadinstance" controlleroptions "github.com/keptn/lifecycle-toolkit/operator/controllers/options" "github.com/keptn/lifecycle-toolkit/operator/webhooks/pod_mutator" - "github.com/prometheus/client_golang/prometheus/promhttp" - "go.opentelemetry.io/otel" - otelprom "go.opentelemetry.io/otel/exporters/prometheus" - "go.opentelemetry.io/otel/sdk/metric" - corev1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/runtime" - utilruntime "k8s.io/apimachinery/pkg/util/runtime" - clientgoscheme "k8s.io/client-go/kubernetes/scheme" - ctrl "sigs.k8s.io/controller-runtime" - ctrlclient "sigs.k8s.io/controller-runtime/pkg/client" - "sigs.k8s.io/controller-runtime/pkg/healthz" - "sigs.k8s.io/controller-runtime/pkg/log/zap" - ctrlWebhook "sigs.k8s.io/controller-runtime/pkg/webhook" ) var ( @@ -306,6 +307,10 @@ func main() { setupLog.Error(err, "unable to create webhook", "webhook", "KeptnWorkloadInstance") os.Exit(1) } + if err = (&lifecyclev1alpha3.KeptnTaskDefinition{}).SetupWebhookWithManager(mgr); err != nil { + setupLog.Error(err, "unable to create webhook", "webhook", "KeptnTaskDefinition") + os.Exit(1) + } // +kubebuilder:scaffold:builder controllercommon.SetUpKeptnMeters(meter, mgr.GetClient()) From 1f6d09cb6ac36594419c2cd6ffd2ea74569ec9a6 Mon Sep 17 00:00:00 2001 From: geoffrey1330 Date: Fri, 2 Jun 2023 10:00:38 +0100 Subject: [PATCH 03/44] added validating webhook for TaskDefinitions Signed-off-by: geoffrey1330 --- operator/PROJECT | 7 + .../v1alpha3/keptntaskdefinition_webhook.go | 64 +++++++++ .../lifecycle/v1alpha3/webhook_suite_test.go | 132 ++++++++++++++++++ .../v1alpha3/zz_generated.deepcopy.go | 2 +- operator/config/certmanager/certificate.yaml | 39 ++++++ .../config/certmanager/kustomization.yaml | 5 + .../config/certmanager/kustomizeconfig.yaml | 16 +++ .../config/default/manager_webhook_patch.yaml | 23 +++ .../default/webhookcainjection_patch.yaml | 29 ++++ operator/main.go | 31 ++-- 10 files changed, 334 insertions(+), 14 deletions(-) create mode 100644 operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook.go create mode 100644 operator/apis/lifecycle/v1alpha3/webhook_suite_test.go create mode 100644 operator/config/certmanager/certificate.yaml create mode 100644 operator/config/certmanager/kustomization.yaml create mode 100644 operator/config/certmanager/kustomizeconfig.yaml create mode 100644 operator/config/default/manager_webhook_patch.yaml create mode 100644 operator/config/default/webhookcainjection_patch.yaml diff --git a/operator/PROJECT b/operator/PROJECT index 5e2a1e5003..30e8c4b73f 100644 --- a/operator/PROJECT +++ b/operator/PROJECT @@ -1,3 +1,7 @@ +# Code generated by tool. DO NOT EDIT. +# This file is used to track the info used to scaffold your project +# and allow the plugins properly work. +# More info: https://book.kubebuilder.io/reference/project-config.html domain: keptn.sh layout: - go.kubebuilder.io/v3 @@ -234,6 +238,9 @@ resources: kind: KeptnTaskDefinition path: github.com/keptn/lifecycle-toolkit/operator/apis/lifecycle/v1alpha3 version: v1alpha3 + webhooks: + validation: true + webhookVersion: v1 - api: crdVersion: v1 namespaced: true diff --git a/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook.go b/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook.go new file mode 100644 index 0000000000..3cd1270bd4 --- /dev/null +++ b/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook.go @@ -0,0 +1,64 @@ +/* +Copyright 2022. + +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 v1alpha3 + +import ( + "k8s.io/apimachinery/pkg/runtime" + ctrl "sigs.k8s.io/controller-runtime" + logf "sigs.k8s.io/controller-runtime/pkg/log" + "sigs.k8s.io/controller-runtime/pkg/webhook" +) + +// log is for logging in this package. +var keptntaskdefinitionlog = logf.Log.WithName("keptntaskdefinition-resource") + +func (r *KeptnTaskDefinition) SetupWebhookWithManager(mgr ctrl.Manager) error { + return ctrl.NewWebhookManagedBy(mgr). + For(r). + Complete() +} + +// TODO(user): EDIT THIS FILE! THIS IS SCAFFOLDING FOR YOU TO OWN! + +// TODO(user): change verbs to "verbs=create;update;delete" if you want to enable deletion validation. +//+kubebuilder:webhook:path=/validate-lifecycle-keptn-sh-v1alpha3-keptntaskdefinition,mutating=false,failurePolicy=fail,sideEffects=None,groups=lifecycle.keptn.sh,resources=keptntaskdefinitions,verbs=create;update,versions=v1alpha3,name=vkeptntaskdefinition.kb.io,admissionReviewVersions=v1 + +var _ webhook.Validator = &KeptnTaskDefinition{} + +// ValidateCreate implements webhook.Validator so a webhook will be registered for the type +func (r *KeptnTaskDefinition) ValidateCreate() error { + keptntaskdefinitionlog.Info("validate create", "name", r.Name) + + // TODO(user): fill in your validation logic upon object creation. + return nil +} + +// ValidateUpdate implements webhook.Validator so a webhook will be registered for the type +func (r *KeptnTaskDefinition) ValidateUpdate(old runtime.Object) error { + keptntaskdefinitionlog.Info("validate update", "name", r.Name) + + // TODO(user): fill in your validation logic upon object update. + return nil +} + +// ValidateDelete implements webhook.Validator so a webhook will be registered for the type +func (r *KeptnTaskDefinition) ValidateDelete() error { + keptntaskdefinitionlog.Info("validate delete", "name", r.Name) + + // TODO(user): fill in your validation logic upon object deletion. + return nil +} diff --git a/operator/apis/lifecycle/v1alpha3/webhook_suite_test.go b/operator/apis/lifecycle/v1alpha3/webhook_suite_test.go new file mode 100644 index 0000000000..dccf30d753 --- /dev/null +++ b/operator/apis/lifecycle/v1alpha3/webhook_suite_test.go @@ -0,0 +1,132 @@ +/* +Copyright 2022. + +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 v1alpha3 + +import ( + "context" + "crypto/tls" + "fmt" + "net" + "path/filepath" + "testing" + "time" + + . "github.com/onsi/ginkgo/v2" + . "github.com/onsi/gomega" + + admissionv1beta1 "k8s.io/api/admission/v1beta1" + //+kubebuilder:scaffold:imports + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/client-go/rest" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/envtest" + logf "sigs.k8s.io/controller-runtime/pkg/log" + "sigs.k8s.io/controller-runtime/pkg/log/zap" +) + +// These tests use Ginkgo (BDD-style Go testing framework). Refer to +// http://onsi.github.io/ginkgo/ to learn more about Ginkgo. + +var cfg *rest.Config +var k8sClient client.Client +var testEnv *envtest.Environment +var ctx context.Context +var cancel context.CancelFunc + +func TestAPIs(t *testing.T) { + RegisterFailHandler(Fail) + + RunSpecs(t, "Webhook Suite") +} + +var _ = BeforeSuite(func() { + logf.SetLogger(zap.New(zap.WriteTo(GinkgoWriter), zap.UseDevMode(true))) + + ctx, cancel = context.WithCancel(context.TODO()) + + By("bootstrapping test environment") + testEnv = &envtest.Environment{ + CRDDirectoryPaths: []string{filepath.Join("..", "..", "..", "config", "crd", "bases")}, + ErrorIfCRDPathMissing: false, + WebhookInstallOptions: envtest.WebhookInstallOptions{ + Paths: []string{filepath.Join("..", "..", "..", "config", "webhook")}, + }, + } + + var err error + // cfg is defined in this file globally. + cfg, err = testEnv.Start() + Expect(err).NotTo(HaveOccurred()) + Expect(cfg).NotTo(BeNil()) + + scheme := runtime.NewScheme() + err = AddToScheme(scheme) + Expect(err).NotTo(HaveOccurred()) + + err = admissionv1beta1.AddToScheme(scheme) + Expect(err).NotTo(HaveOccurred()) + + //+kubebuilder:scaffold:scheme + + k8sClient, err = client.New(cfg, client.Options{Scheme: scheme}) + Expect(err).NotTo(HaveOccurred()) + Expect(k8sClient).NotTo(BeNil()) + + // start webhook server using Manager + webhookInstallOptions := &testEnv.WebhookInstallOptions + mgr, err := ctrl.NewManager(cfg, ctrl.Options{ + Scheme: scheme, + Host: webhookInstallOptions.LocalServingHost, + Port: webhookInstallOptions.LocalServingPort, + CertDir: webhookInstallOptions.LocalServingCertDir, + LeaderElection: false, + MetricsBindAddress: "0", + }) + Expect(err).NotTo(HaveOccurred()) + + err = (&KeptnTaskDefinition{}).SetupWebhookWithManager(mgr) + Expect(err).NotTo(HaveOccurred()) + + //+kubebuilder:scaffold:webhook + + go func() { + defer GinkgoRecover() + err = mgr.Start(ctx) + Expect(err).NotTo(HaveOccurred()) + }() + + // wait for the webhook server to get ready + dialer := &net.Dialer{Timeout: time.Second} + addrPort := fmt.Sprintf("%s:%d", webhookInstallOptions.LocalServingHost, webhookInstallOptions.LocalServingPort) + Eventually(func() error { + conn, err := tls.DialWithDialer(dialer, "tcp", addrPort, &tls.Config{InsecureSkipVerify: true}) + if err != nil { + return err + } + conn.Close() + return nil + }).Should(Succeed()) + +}) + +var _ = AfterSuite(func() { + cancel() + By("tearing down the test environment") + err := testEnv.Stop() + Expect(err).NotTo(HaveOccurred()) +}) diff --git a/operator/apis/lifecycle/v1alpha3/zz_generated.deepcopy.go b/operator/apis/lifecycle/v1alpha3/zz_generated.deepcopy.go index cc68f44e91..e7bd2204bc 100644 --- a/operator/apis/lifecycle/v1alpha3/zz_generated.deepcopy.go +++ b/operator/apis/lifecycle/v1alpha3/zz_generated.deepcopy.go @@ -25,7 +25,7 @@ import ( "github.com/keptn/lifecycle-toolkit/operator/apis/lifecycle/v1alpha3/common" "go.opentelemetry.io/otel/propagation" "k8s.io/api/core/v1" - runtime "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime" ) // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. diff --git a/operator/config/certmanager/certificate.yaml b/operator/config/certmanager/certificate.yaml new file mode 100644 index 0000000000..f587f5bc9d --- /dev/null +++ b/operator/config/certmanager/certificate.yaml @@ -0,0 +1,39 @@ +# The following manifests contain a self-signed issuer CR and a certificate CR. +# More document can be found at https://docs.cert-manager.io +# WARNING: Targets CertManager v1.0. Check https://cert-manager.io/docs/installation/upgrading/ for breaking changes. +apiVersion: cert-manager.io/v1 +kind: Issuer +metadata: + labels: + app.kubernetes.io/name: issuer + app.kubernetes.io/instance: selfsigned-issuer + app.kubernetes.io/component: certificate + app.kubernetes.io/created-by: keptn-lifecycle-toolkit + app.kubernetes.io/part-of: keptn-lifecycle-toolkit + app.kubernetes.io/managed-by: kustomize + name: selfsigned-issuer + namespace: system +spec: + selfSigned: {} +--- +apiVersion: cert-manager.io/v1 +kind: Certificate +metadata: + labels: + app.kubernetes.io/name: certificate + app.kubernetes.io/instance: serving-cert + app.kubernetes.io/component: certificate + app.kubernetes.io/created-by: keptn-lifecycle-toolkit + app.kubernetes.io/part-of: keptn-lifecycle-toolkit + app.kubernetes.io/managed-by: kustomize + name: serving-cert # this name should match the one appeared in kustomizeconfig.yaml + namespace: system +spec: + # $(SERVICE_NAME) and $(SERVICE_NAMESPACE) will be substituted by kustomize + dnsNames: + - $(SERVICE_NAME).$(SERVICE_NAMESPACE).svc + - $(SERVICE_NAME).$(SERVICE_NAMESPACE).svc.cluster.local + issuerRef: + kind: Issuer + name: selfsigned-issuer + secretName: webhook-server-cert # this secret will not be prefixed, since it's not managed by kustomize diff --git a/operator/config/certmanager/kustomization.yaml b/operator/config/certmanager/kustomization.yaml new file mode 100644 index 0000000000..bebea5a595 --- /dev/null +++ b/operator/config/certmanager/kustomization.yaml @@ -0,0 +1,5 @@ +resources: +- certificate.yaml + +configurations: +- kustomizeconfig.yaml diff --git a/operator/config/certmanager/kustomizeconfig.yaml b/operator/config/certmanager/kustomizeconfig.yaml new file mode 100644 index 0000000000..e631f77736 --- /dev/null +++ b/operator/config/certmanager/kustomizeconfig.yaml @@ -0,0 +1,16 @@ +# This configuration is for teaching kustomize how to update name ref and var substitution +nameReference: +- kind: Issuer + group: cert-manager.io + fieldSpecs: + - kind: Certificate + group: cert-manager.io + path: spec/issuerRef/name + +varReference: +- kind: Certificate + group: cert-manager.io + path: spec/commonName +- kind: Certificate + group: cert-manager.io + path: spec/dnsNames diff --git a/operator/config/default/manager_webhook_patch.yaml b/operator/config/default/manager_webhook_patch.yaml new file mode 100644 index 0000000000..738de350b7 --- /dev/null +++ b/operator/config/default/manager_webhook_patch.yaml @@ -0,0 +1,23 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + name: controller-manager + namespace: system +spec: + template: + spec: + containers: + - name: manager + ports: + - containerPort: 9443 + name: webhook-server + protocol: TCP + volumeMounts: + - mountPath: /tmp/k8s-webhook-server/serving-certs + name: cert + readOnly: true + volumes: + - name: cert + secret: + defaultMode: 420 + secretName: webhook-server-cert diff --git a/operator/config/default/webhookcainjection_patch.yaml b/operator/config/default/webhookcainjection_patch.yaml new file mode 100644 index 0000000000..c7cbe14322 --- /dev/null +++ b/operator/config/default/webhookcainjection_patch.yaml @@ -0,0 +1,29 @@ +# This patch add annotation to admission webhook config and +# the variables $(CERTIFICATE_NAMESPACE) and $(CERTIFICATE_NAME) will be substituted by kustomize. +apiVersion: admissionregistration.k8s.io/v1 +kind: MutatingWebhookConfiguration +metadata: + labels: + app.kubernetes.io/name: mutatingwebhookconfiguration + app.kubernetes.io/instance: mutating-webhook-configuration + app.kubernetes.io/component: webhook + app.kubernetes.io/created-by: keptn-lifecycle-toolkit + app.kubernetes.io/part-of: keptn-lifecycle-toolkit + app.kubernetes.io/managed-by: kustomize + name: mutating-webhook-configuration + annotations: + cert-manager.io/inject-ca-from: $(CERTIFICATE_NAMESPACE)/$(CERTIFICATE_NAME) +--- +apiVersion: admissionregistration.k8s.io/v1 +kind: ValidatingWebhookConfiguration +metadata: + labels: + app.kubernetes.io/name: validatingwebhookconfiguration + app.kubernetes.io/instance: validating-webhook-configuration + app.kubernetes.io/component: webhook + app.kubernetes.io/created-by: keptn-lifecycle-toolkit + app.kubernetes.io/part-of: keptn-lifecycle-toolkit + app.kubernetes.io/managed-by: kustomize + name: validating-webhook-configuration + annotations: + cert-manager.io/inject-ca-from: $(CERTIFICATE_NAMESPACE)/$(CERTIFICATE_NAME) diff --git a/operator/main.go b/operator/main.go index 3c1b5f2378..50af730da9 100644 --- a/operator/main.go +++ b/operator/main.go @@ -29,6 +29,20 @@ import ( certCommon "github.com/keptn/lifecycle-toolkit/klt-cert-manager/pkg/common" "github.com/keptn/lifecycle-toolkit/klt-cert-manager/pkg/webhook" metricsapi "github.com/keptn/lifecycle-toolkit/metrics-operator/api/v1alpha3" + "github.com/prometheus/client_golang/prometheus/promhttp" + "go.opentelemetry.io/otel" + otelprom "go.opentelemetry.io/otel/exporters/prometheus" + "go.opentelemetry.io/otel/sdk/metric" + corev1 "k8s.io/api/core/v1" + "k8s.io/apimachinery/pkg/runtime" + utilruntime "k8s.io/apimachinery/pkg/util/runtime" + clientgoscheme "k8s.io/client-go/kubernetes/scheme" + ctrl "sigs.k8s.io/controller-runtime" + ctrlclient "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/healthz" + "sigs.k8s.io/controller-runtime/pkg/log/zap" + ctrlWebhook "sigs.k8s.io/controller-runtime/pkg/webhook" + lifecyclev1alpha1 "github.com/keptn/lifecycle-toolkit/operator/apis/lifecycle/v1alpha1" lifecyclev1alpha2 "github.com/keptn/lifecycle-toolkit/operator/apis/lifecycle/v1alpha2" lifecyclev1alpha3 "github.com/keptn/lifecycle-toolkit/operator/apis/lifecycle/v1alpha3" @@ -44,19 +58,6 @@ import ( "github.com/keptn/lifecycle-toolkit/operator/controllers/lifecycle/keptnworkloadinstance" controlleroptions "github.com/keptn/lifecycle-toolkit/operator/controllers/options" "github.com/keptn/lifecycle-toolkit/operator/webhooks/pod_mutator" - "github.com/prometheus/client_golang/prometheus/promhttp" - "go.opentelemetry.io/otel" - otelprom "go.opentelemetry.io/otel/exporters/prometheus" - "go.opentelemetry.io/otel/sdk/metric" - corev1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/runtime" - utilruntime "k8s.io/apimachinery/pkg/util/runtime" - clientgoscheme "k8s.io/client-go/kubernetes/scheme" - ctrl "sigs.k8s.io/controller-runtime" - ctrlclient "sigs.k8s.io/controller-runtime/pkg/client" - "sigs.k8s.io/controller-runtime/pkg/healthz" - "sigs.k8s.io/controller-runtime/pkg/log/zap" - ctrlWebhook "sigs.k8s.io/controller-runtime/pkg/webhook" ) var ( @@ -306,6 +307,10 @@ func main() { setupLog.Error(err, "unable to create webhook", "webhook", "KeptnWorkloadInstance") os.Exit(1) } + if err = (&lifecyclev1alpha3.KeptnTaskDefinition{}).SetupWebhookWithManager(mgr); err != nil { + setupLog.Error(err, "unable to create webhook", "webhook", "KeptnTaskDefinition") + os.Exit(1) + } // +kubebuilder:scaffold:builder controllercommon.SetUpKeptnMeters(meter, mgr.GetClient()) From cee01145481aefe5497984ada828ea7a0c686298 Mon Sep 17 00:00:00 2001 From: geoffrey1330 Date: Fri, 2 Jun 2023 15:55:20 +0100 Subject: [PATCH 04/44] Added TaskDefinition validation logic to allow either Function spec or container spec but not both Signed-off-by: geoffrey1330 --- 1 | 24 +++++++++++++++++++ .../v1alpha3/keptntaskdefinition_webhook.go | 23 ++++++++++++++++++ 2 files changed, 47 insertions(+) create mode 100644 1 diff --git a/1 b/1 new file mode 100644 index 0000000000..6c03eb1f44 --- /dev/null +++ b/1 @@ -0,0 +1,24 @@ +added validating webhook for TaskDefinitions + +Signed-off-by: geoffrey1330 + +# Please enter the commit message for your changes. Lines starting +# with '#' will be ignored, and an empty message aborts the commit. +# +# Date: Fri Jun 2 10:00:38 2023 +0100 +# +# On branch feat/1486/validating_webhook +# Your branch is up to date with 'origin/feat/1486/validating_webhook'. +# +# Changes to be committed: +# modified: operator/PROJECT +# new file: operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook.go +# new file: operator/apis/lifecycle/v1alpha3/webhook_suite_test.go +# modified: operator/apis/lifecycle/v1alpha3/zz_generated.deepcopy.go +# new file: operator/config/certmanager/certificate.yaml +# new file: operator/config/certmanager/kustomization.yaml +# new file: operator/config/certmanager/kustomizeconfig.yaml +# new file: operator/config/default/manager_webhook_patch.yaml +# new file: operator/config/default/webhookcainjection_patch.yaml +# modified: operator/main.go +# diff --git a/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook.go b/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook.go index 3cd1270bd4..db2cde1e01 100644 --- a/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook.go +++ b/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook.go @@ -62,3 +62,26 @@ func (r *KeptnTaskDefinition) ValidateDelete() error { // TODO(user): fill in your validation logic upon object deletion. return nil } + +func (r *KeptnTaskDefinition) validateFields() error { + if r.Spec.Function == nil && r.Spec.Container == nil { + return ValidationError{Field: "spec", Message: "Either Function or Container field must be defined"} + } + + if r.Spec.Function != nil && r.Spec.Container != nil { + return ValidationError{Field: "spec", Message: "Both Function and Container fields cannot be defined simultaneously"} + } + + return nil +} + +// ValidationError represents a validation error with a specific field and message +type ValidationError struct { + Field string + Message string +} + +// Error returns the validation error message +func (e ValidationError) Error() string { + return e.Message +} From 42c81938ce246bd4703266cbb5db09e5945ed8f1 Mon Sep 17 00:00:00 2001 From: geoffrey1330 Date: Fri, 2 Jun 2023 16:28:06 +0100 Subject: [PATCH 05/44] Added TaskDefinition validation logic to allow either Function spec or container spec but not both Signed-off-by: geoffrey1330 --- 1 | 24 ------------------------ 1 file changed, 24 deletions(-) delete mode 100644 1 diff --git a/1 b/1 deleted file mode 100644 index 6c03eb1f44..0000000000 --- a/1 +++ /dev/null @@ -1,24 +0,0 @@ -added validating webhook for TaskDefinitions - -Signed-off-by: geoffrey1330 - -# Please enter the commit message for your changes. Lines starting -# with '#' will be ignored, and an empty message aborts the commit. -# -# Date: Fri Jun 2 10:00:38 2023 +0100 -# -# On branch feat/1486/validating_webhook -# Your branch is up to date with 'origin/feat/1486/validating_webhook'. -# -# Changes to be committed: -# modified: operator/PROJECT -# new file: operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook.go -# new file: operator/apis/lifecycle/v1alpha3/webhook_suite_test.go -# modified: operator/apis/lifecycle/v1alpha3/zz_generated.deepcopy.go -# new file: operator/config/certmanager/certificate.yaml -# new file: operator/config/certmanager/kustomization.yaml -# new file: operator/config/certmanager/kustomizeconfig.yaml -# new file: operator/config/default/manager_webhook_patch.yaml -# new file: operator/config/default/webhookcainjection_patch.yaml -# modified: operator/main.go -# From caca04d5885edf1f0cea2a8a1c6244e756bd98a5 Mon Sep 17 00:00:00 2001 From: Geoffrey Israel Date: Fri, 2 Jun 2023 18:16:19 +0100 Subject: [PATCH 06/44] Update operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook.go Co-authored-by: Rakshit Gondwal <98955085+rakshitgondwal@users.noreply.github.com> Signed-off-by: Geoffrey Israel --- .../apis/lifecycle/v1alpha3/keptntaskdefinition_webhook.go | 3 --- 1 file changed, 3 deletions(-) diff --git a/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook.go b/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook.go index db2cde1e01..323668cb39 100644 --- a/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook.go +++ b/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook.go @@ -32,9 +32,6 @@ func (r *KeptnTaskDefinition) SetupWebhookWithManager(mgr ctrl.Manager) error { Complete() } -// TODO(user): EDIT THIS FILE! THIS IS SCAFFOLDING FOR YOU TO OWN! - -// TODO(user): change verbs to "verbs=create;update;delete" if you want to enable deletion validation. //+kubebuilder:webhook:path=/validate-lifecycle-keptn-sh-v1alpha3-keptntaskdefinition,mutating=false,failurePolicy=fail,sideEffects=None,groups=lifecycle.keptn.sh,resources=keptntaskdefinitions,verbs=create;update,versions=v1alpha3,name=vkeptntaskdefinition.kb.io,admissionReviewVersions=v1 var _ webhook.Validator = &KeptnTaskDefinition{} From adf509c4bd4b702d9ff9aebd9eb8805621171f08 Mon Sep 17 00:00:00 2001 From: Geoffrey Israel Date: Fri, 2 Jun 2023 18:16:31 +0100 Subject: [PATCH 07/44] Update operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook.go Co-authored-by: Rakshit Gondwal <98955085+rakshitgondwal@users.noreply.github.com> Signed-off-by: Geoffrey Israel --- .../apis/lifecycle/v1alpha3/keptntaskdefinition_webhook.go | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook.go b/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook.go index 323668cb39..466a6e5fe4 100644 --- a/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook.go +++ b/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook.go @@ -40,8 +40,7 @@ var _ webhook.Validator = &KeptnTaskDefinition{} func (r *KeptnTaskDefinition) ValidateCreate() error { keptntaskdefinitionlog.Info("validate create", "name", r.Name) - // TODO(user): fill in your validation logic upon object creation. - return nil + return r.validateKeptnTaskDefination() } // ValidateUpdate implements webhook.Validator so a webhook will be registered for the type From 658e71ea8bff87d064448d4e83398f65b0fc6092 Mon Sep 17 00:00:00 2001 From: Geoffrey Israel Date: Fri, 2 Jun 2023 18:16:39 +0100 Subject: [PATCH 08/44] Update operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook.go Co-authored-by: Rakshit Gondwal <98955085+rakshitgondwal@users.noreply.github.com> Signed-off-by: Geoffrey Israel --- .../apis/lifecycle/v1alpha3/keptntaskdefinition_webhook.go | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook.go b/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook.go index 466a6e5fe4..d35669b262 100644 --- a/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook.go +++ b/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook.go @@ -47,8 +47,7 @@ func (r *KeptnTaskDefinition) ValidateCreate() error { func (r *KeptnTaskDefinition) ValidateUpdate(old runtime.Object) error { keptntaskdefinitionlog.Info("validate update", "name", r.Name) - // TODO(user): fill in your validation logic upon object update. - return nil + return r.validateKeptnTaskDefination() } // ValidateDelete implements webhook.Validator so a webhook will be registered for the type From 2f4608651dddb980a7110d54c7f617df95bbbe8b Mon Sep 17 00:00:00 2001 From: Geoffrey Israel Date: Fri, 2 Jun 2023 18:16:53 +0100 Subject: [PATCH 09/44] Update operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook.go Co-authored-by: Rakshit Gondwal <98955085+rakshitgondwal@users.noreply.github.com> Signed-off-by: Geoffrey Israel --- operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook.go | 1 - 1 file changed, 1 deletion(-) diff --git a/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook.go b/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook.go index d35669b262..5970bfe03f 100644 --- a/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook.go +++ b/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook.go @@ -54,7 +54,6 @@ func (r *KeptnTaskDefinition) ValidateUpdate(old runtime.Object) error { func (r *KeptnTaskDefinition) ValidateDelete() error { keptntaskdefinitionlog.Info("validate delete", "name", r.Name) - // TODO(user): fill in your validation logic upon object deletion. return nil } From 3c45ddb3c372ea90684efe3d8075146e8e2f6874 Mon Sep 17 00:00:00 2001 From: Geoffrey Israel Date: Fri, 2 Jun 2023 18:17:05 +0100 Subject: [PATCH 10/44] Update operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook.go Co-authored-by: Rakshit Gondwal <98955085+rakshitgondwal@users.noreply.github.com> Signed-off-by: Geoffrey Israel --- .../v1alpha3/keptntaskdefinition_webhook.go | 41 ++++++++++++------- 1 file changed, 27 insertions(+), 14 deletions(-) diff --git a/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook.go b/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook.go index 5970bfe03f..4be0cffcef 100644 --- a/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook.go +++ b/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook.go @@ -57,25 +57,38 @@ func (r *KeptnTaskDefinition) ValidateDelete() error { return nil } -func (r *KeptnTaskDefinition) validateFields() error { +func (r *KeptnTaskDefinition) validateKeptnTaskDefination() error { + var allErrs field.ErrorList //defined as a list to allow returning multiple validation errors + var err *field.Error + if err = r.validateFields(); err != nil { + allErrs = append(allErrs, err) + } + if len(allErrs) == 0 { + return nil + } + + return apierrors.NewInvalid( + schema.GroupKind{Group: "lifecycle.keptn.sh", Kind: "KeptnTaskDefinition"}, + r.Name, + allErrs) +} +func (r *KeptnTaskDefinition) validateFields() *field.Error { + if r.Spec.Function == nil && r.Spec.Container == nil { - return ValidationError{Field: "spec", Message: "Either Function or Container field must be defined"} + return field.Invalid( + field.NewPath("spec"), + r.Spec, + errors.New("Forbidden! Either Function or Container field must be defined").Error(), + ) } if r.Spec.Function != nil && r.Spec.Container != nil { - return ValidationError{Field: "spec", Message: "Both Function and Container fields cannot be defined simultaneously"} + return field.Invalid( + field.NewPath("spec"), + r.Spec, + errors.New("Forbidden! Both Function and Container fields cannot be defined simultaneously").Error(), + ) } return nil } - -// ValidationError represents a validation error with a specific field and message -type ValidationError struct { - Field string - Message string -} - -// Error returns the validation error message -func (e ValidationError) Error() string { - return e.Message -} From 101f20a0d3a297ff8e3b2b55eb08957453961f34 Mon Sep 17 00:00:00 2001 From: geoffrey1330 Date: Fri, 2 Jun 2023 18:18:40 +0100 Subject: [PATCH 11/44] Added TaskDefinition validation logic to allow either Function spec or container spec but not both Signed-off-by: geoffrey1330 --- .../apis/lifecycle/v1alpha3/keptntaskdefinition_webhook.go | 3 --- 1 file changed, 3 deletions(-) diff --git a/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook.go b/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook.go index db2cde1e01..323668cb39 100644 --- a/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook.go +++ b/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook.go @@ -32,9 +32,6 @@ func (r *KeptnTaskDefinition) SetupWebhookWithManager(mgr ctrl.Manager) error { Complete() } -// TODO(user): EDIT THIS FILE! THIS IS SCAFFOLDING FOR YOU TO OWN! - -// TODO(user): change verbs to "verbs=create;update;delete" if you want to enable deletion validation. //+kubebuilder:webhook:path=/validate-lifecycle-keptn-sh-v1alpha3-keptntaskdefinition,mutating=false,failurePolicy=fail,sideEffects=None,groups=lifecycle.keptn.sh,resources=keptntaskdefinitions,verbs=create;update,versions=v1alpha3,name=vkeptntaskdefinition.kb.io,admissionReviewVersions=v1 var _ webhook.Validator = &KeptnTaskDefinition{} From 95c8234ce3c51e6a6c4dd78114faf0dfd9a6f884 Mon Sep 17 00:00:00 2001 From: geoffrey1330 Date: Fri, 2 Jun 2023 18:37:49 +0100 Subject: [PATCH 12/44] added ValidatingWebhookConfiguration manifest Signed-off-by: geoffrey1330 --- operator/config/webhook/manifests.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/operator/config/webhook/manifests.yaml b/operator/config/webhook/manifests.yaml index e4d1f7a094..7be5de23da 100644 --- a/operator/config/webhook/manifests.yaml +++ b/operator/config/webhook/manifests.yaml @@ -57,4 +57,4 @@ webhooks: resources: - keptntaskdefinitions sideEffects: None - \ No newline at end of file + From 609d75ac679d978d122a293078ec61c43e31956f Mon Sep 17 00:00:00 2001 From: geoffrey1330 Date: Fri, 2 Jun 2023 18:53:55 +0100 Subject: [PATCH 13/44] deleted webhook_suite_test.go file Signed-off-by: geoffrey1330 --- .../lifecycle/v1alpha3/webhook_suite_test.go | 132 ------------------ 1 file changed, 132 deletions(-) delete mode 100644 operator/apis/lifecycle/v1alpha3/webhook_suite_test.go diff --git a/operator/apis/lifecycle/v1alpha3/webhook_suite_test.go b/operator/apis/lifecycle/v1alpha3/webhook_suite_test.go deleted file mode 100644 index dccf30d753..0000000000 --- a/operator/apis/lifecycle/v1alpha3/webhook_suite_test.go +++ /dev/null @@ -1,132 +0,0 @@ -/* -Copyright 2022. - -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 v1alpha3 - -import ( - "context" - "crypto/tls" - "fmt" - "net" - "path/filepath" - "testing" - "time" - - . "github.com/onsi/ginkgo/v2" - . "github.com/onsi/gomega" - - admissionv1beta1 "k8s.io/api/admission/v1beta1" - //+kubebuilder:scaffold:imports - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/client-go/rest" - ctrl "sigs.k8s.io/controller-runtime" - "sigs.k8s.io/controller-runtime/pkg/client" - "sigs.k8s.io/controller-runtime/pkg/envtest" - logf "sigs.k8s.io/controller-runtime/pkg/log" - "sigs.k8s.io/controller-runtime/pkg/log/zap" -) - -// These tests use Ginkgo (BDD-style Go testing framework). Refer to -// http://onsi.github.io/ginkgo/ to learn more about Ginkgo. - -var cfg *rest.Config -var k8sClient client.Client -var testEnv *envtest.Environment -var ctx context.Context -var cancel context.CancelFunc - -func TestAPIs(t *testing.T) { - RegisterFailHandler(Fail) - - RunSpecs(t, "Webhook Suite") -} - -var _ = BeforeSuite(func() { - logf.SetLogger(zap.New(zap.WriteTo(GinkgoWriter), zap.UseDevMode(true))) - - ctx, cancel = context.WithCancel(context.TODO()) - - By("bootstrapping test environment") - testEnv = &envtest.Environment{ - CRDDirectoryPaths: []string{filepath.Join("..", "..", "..", "config", "crd", "bases")}, - ErrorIfCRDPathMissing: false, - WebhookInstallOptions: envtest.WebhookInstallOptions{ - Paths: []string{filepath.Join("..", "..", "..", "config", "webhook")}, - }, - } - - var err error - // cfg is defined in this file globally. - cfg, err = testEnv.Start() - Expect(err).NotTo(HaveOccurred()) - Expect(cfg).NotTo(BeNil()) - - scheme := runtime.NewScheme() - err = AddToScheme(scheme) - Expect(err).NotTo(HaveOccurred()) - - err = admissionv1beta1.AddToScheme(scheme) - Expect(err).NotTo(HaveOccurred()) - - //+kubebuilder:scaffold:scheme - - k8sClient, err = client.New(cfg, client.Options{Scheme: scheme}) - Expect(err).NotTo(HaveOccurred()) - Expect(k8sClient).NotTo(BeNil()) - - // start webhook server using Manager - webhookInstallOptions := &testEnv.WebhookInstallOptions - mgr, err := ctrl.NewManager(cfg, ctrl.Options{ - Scheme: scheme, - Host: webhookInstallOptions.LocalServingHost, - Port: webhookInstallOptions.LocalServingPort, - CertDir: webhookInstallOptions.LocalServingCertDir, - LeaderElection: false, - MetricsBindAddress: "0", - }) - Expect(err).NotTo(HaveOccurred()) - - err = (&KeptnTaskDefinition{}).SetupWebhookWithManager(mgr) - Expect(err).NotTo(HaveOccurred()) - - //+kubebuilder:scaffold:webhook - - go func() { - defer GinkgoRecover() - err = mgr.Start(ctx) - Expect(err).NotTo(HaveOccurred()) - }() - - // wait for the webhook server to get ready - dialer := &net.Dialer{Timeout: time.Second} - addrPort := fmt.Sprintf("%s:%d", webhookInstallOptions.LocalServingHost, webhookInstallOptions.LocalServingPort) - Eventually(func() error { - conn, err := tls.DialWithDialer(dialer, "tcp", addrPort, &tls.Config{InsecureSkipVerify: true}) - if err != nil { - return err - } - conn.Close() - return nil - }).Should(Succeed()) - -}) - -var _ = AfterSuite(func() { - cancel() - By("tearing down the test environment") - err := testEnv.Stop() - Expect(err).NotTo(HaveOccurred()) -}) From dcb52c71a7ff11ecbb30f87fe1bc9e105196d49d Mon Sep 17 00:00:00 2001 From: geoffrey1330 Date: Sat, 3 Jun 2023 00:04:27 +0100 Subject: [PATCH 14/44] Added neccessary import for keptntaskdefinition_webhook Signed-off-by: geoffrey1330 --- .../lifecycle/v1alpha3/keptntaskdefinition_webhook.go | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook.go b/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook.go index 4be0cffcef..93fcbab267 100644 --- a/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook.go +++ b/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook.go @@ -17,7 +17,11 @@ limitations under the License. package v1alpha3 import ( + "github.com/pkg/errors" + apierrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/apimachinery/pkg/util/validation/field" ctrl "sigs.k8s.io/controller-runtime" logf "sigs.k8s.io/controller-runtime/pkg/log" "sigs.k8s.io/controller-runtime/pkg/webhook" @@ -78,7 +82,7 @@ func (r *KeptnTaskDefinition) validateFields() *field.Error { return field.Invalid( field.NewPath("spec"), r.Spec, - errors.New("Forbidden! Either Function or Container field must be defined").Error(), + errors.New("Forbidden! Either Function or Container field must be defined").Error(), ) } @@ -86,7 +90,7 @@ func (r *KeptnTaskDefinition) validateFields() *field.Error { return field.Invalid( field.NewPath("spec"), r.Spec, - errors.New("Forbidden! Both Function and Container fields cannot be defined simultaneously").Error(), + errors.New("Forbidden! Both Function and Container fields cannot be defined simultaneously").Error(), ) } From 74f7d394de56515018c8fe90af510a7a690120c7 Mon Sep 17 00:00:00 2001 From: Geoffrey Israel Date: Sun, 4 Jun 2023 13:27:38 +0100 Subject: [PATCH 15/44] Update operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook.go Co-authored-by: Rakshit Gondwal <98955085+rakshitgondwal@users.noreply.github.com> Signed-off-by: Geoffrey Israel --- operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook.go b/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook.go index 93fcbab267..8769e53817 100644 --- a/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook.go +++ b/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook.go @@ -61,7 +61,7 @@ func (r *KeptnTaskDefinition) ValidateDelete() error { return nil } -func (r *KeptnTaskDefinition) validateKeptnTaskDefination() error { +func (r *KeptnTaskDefinition) validateKeptnTaskDefinition() error { var allErrs field.ErrorList //defined as a list to allow returning multiple validation errors var err *field.Error if err = r.validateFields(); err != nil { From 8ccfa036b461634998ba803ceb0dbbefe399dada Mon Sep 17 00:00:00 2001 From: Geoffrey Israel Date: Sun, 4 Jun 2023 13:28:10 +0100 Subject: [PATCH 16/44] Update operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook.go Co-authored-by: Rakshit Gondwal <98955085+rakshitgondwal@users.noreply.github.com> Signed-off-by: Geoffrey Israel --- operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook.go b/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook.go index 8769e53817..123cfb9a85 100644 --- a/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook.go +++ b/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook.go @@ -51,7 +51,7 @@ func (r *KeptnTaskDefinition) ValidateCreate() error { func (r *KeptnTaskDefinition) ValidateUpdate(old runtime.Object) error { keptntaskdefinitionlog.Info("validate update", "name", r.Name) - return r.validateKeptnTaskDefination() + return r.validateKeptnTaskDefinition() } // ValidateDelete implements webhook.Validator so a webhook will be registered for the type From f410f6dd3dfdd89ec4fd3603f423ba4d754e47bb Mon Sep 17 00:00:00 2001 From: Geoffrey Israel Date: Sun, 4 Jun 2023 13:28:28 +0100 Subject: [PATCH 17/44] Update operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook.go Co-authored-by: Rakshit Gondwal <98955085+rakshitgondwal@users.noreply.github.com> Signed-off-by: Geoffrey Israel --- operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook.go b/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook.go index 123cfb9a85..d06601747c 100644 --- a/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook.go +++ b/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook.go @@ -44,7 +44,7 @@ var _ webhook.Validator = &KeptnTaskDefinition{} func (r *KeptnTaskDefinition) ValidateCreate() error { keptntaskdefinitionlog.Info("validate create", "name", r.Name) - return r.validateKeptnTaskDefination() + return r.validateKeptnTaskDefinition() } // ValidateUpdate implements webhook.Validator so a webhook will be registered for the type From fdff5892763833f8e827acbc119334c5e513dea9 Mon Sep 17 00:00:00 2001 From: geoffrey1330 Date: Sun, 4 Jun 2023 14:00:50 +0100 Subject: [PATCH 18/44] Added testcase keptntaskdefinition_webhook_test.go for keptntaskdefinition_webhook.go Signed-off-by: geoffrey1330 --- .../keptntaskdefinition_webhook_test.go | 66 +++++ .../interfaces/fake/phaseitem_mock.go | 248 ++++++++++-------- 2 files changed, 203 insertions(+), 111 deletions(-) create mode 100644 operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook_test.go diff --git a/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook_test.go b/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook_test.go new file mode 100644 index 0000000000..4cf6063991 --- /dev/null +++ b/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook_test.go @@ -0,0 +1,66 @@ +package v1alpha3 + +import ( + "reflect" + "testing" + + "github.com/pkg/errors" + //metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/util/validation/field" +) + +func TestKeptnTaskDefinition_ValidateFields(t *testing.T) { + tests := []struct { + name string + spec KeptnTaskDefinitionSpec + want *field.Error + }{ + { + name: "with-no-function-or-container", + spec: KeptnTaskDefinitionSpec{}, + want: field.Invalid( + field.NewPath("spec"), + KeptnTaskDefinitionSpec{}, + errors.New("Forbidden! Either Function or Container field must be defined").Error(), + ), + }, + { + name: "with-both-function-and-container", + spec: KeptnTaskDefinitionSpec{ + Function: &FunctionSpec{}, + Container: &ContainerSpec{}, + }, + want: field.Invalid( + field.NewPath("spec"), + KeptnTaskDefinitionSpec{ + Function: &FunctionSpec{}, + Container: &ContainerSpec{}, + }, + errors.New("Forbidden! Both Function and Container fields cannot be defined simultaneously").Error(), + ), + }, + { + name: "with-function-only", + spec: KeptnTaskDefinitionSpec{ + Function: &FunctionSpec{}, + }, + }, + { + name: "with-container-only", + spec: KeptnTaskDefinitionSpec{ + Container: &ContainerSpec{}, + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + ktd := &KeptnTaskDefinition{ + Spec: tt.spec, + } + if got := ktd.validateFields(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("validateFields() = %v, want %v", got, tt.want) + } + }) + } +} diff --git a/operator/controllers/lifecycle/interfaces/fake/phaseitem_mock.go b/operator/controllers/lifecycle/interfaces/fake/phaseitem_mock.go index ba2d753f70..55cb514a1b 100644 --- a/operator/controllers/lifecycle/interfaces/fake/phaseitem_mock.go +++ b/operator/controllers/lifecycle/interfaces/fake/phaseitem_mock.go @@ -14,94 +14,94 @@ import ( // PhaseItemMock is a mock implementation of interfaces.PhaseItem. // -// func TestSomethingThatUsesPhaseItem(t *testing.T) { +// func TestSomethingThatUsesPhaseItem(t *testing.T) { // -// // make and configure a mocked interfaces.PhaseItem -// mockedPhaseItem := &PhaseItemMock{ -// CompleteFunc: func() { -// panic("mock out the Complete method") -// }, -// DeprecateRemainingPhasesFunc: func(phase apicommon.KeptnPhaseType) { -// panic("mock out the DeprecateRemainingPhases method") -// }, -// GenerateEvaluationFunc: func(evaluationDefinition klcv1alpha3.KeptnEvaluationDefinition, checkType apicommon.CheckType) klcv1alpha3.KeptnEvaluation { -// panic("mock out the GenerateEvaluation method") -// }, -// GenerateTaskFunc: func(taskDefinition klcv1alpha3.KeptnTaskDefinition, checkType apicommon.CheckType) klcv1alpha3.KeptnTask { -// panic("mock out the GenerateTask method") -// }, -// GetAppNameFunc: func() string { -// panic("mock out the GetAppName method") -// }, -// GetCurrentPhaseFunc: func() string { -// panic("mock out the GetCurrentPhase method") -// }, -// GetEndTimeFunc: func() time.Time { -// panic("mock out the GetEndTime method") -// }, -// GetNamespaceFunc: func() string { -// panic("mock out the GetNamespace method") -// }, -// GetParentNameFunc: func() string { -// panic("mock out the GetParentName method") -// }, -// GetPostDeploymentEvaluationTaskStatusFunc: func() []klcv1alpha3.ItemStatus { -// panic("mock out the GetPostDeploymentEvaluationTaskStatus method") -// }, -// GetPostDeploymentEvaluationsFunc: func() []string { -// panic("mock out the GetPostDeploymentEvaluations method") -// }, -// GetPostDeploymentTaskStatusFunc: func() []klcv1alpha3.ItemStatus { -// panic("mock out the GetPostDeploymentTaskStatus method") -// }, -// GetPostDeploymentTasksFunc: func() []string { -// panic("mock out the GetPostDeploymentTasks method") -// }, -// GetPreDeploymentEvaluationTaskStatusFunc: func() []klcv1alpha3.ItemStatus { -// panic("mock out the GetPreDeploymentEvaluationTaskStatus method") -// }, -// GetPreDeploymentEvaluationsFunc: func() []string { -// panic("mock out the GetPreDeploymentEvaluations method") -// }, -// GetPreDeploymentTaskStatusFunc: func() []klcv1alpha3.ItemStatus { -// panic("mock out the GetPreDeploymentTaskStatus method") -// }, -// GetPreDeploymentTasksFunc: func() []string { -// panic("mock out the GetPreDeploymentTasks method") -// }, -// GetPreviousVersionFunc: func() string { -// panic("mock out the GetPreviousVersion method") -// }, -// GetSpanAttributesFunc: func() []attribute.KeyValue { -// panic("mock out the GetSpanAttributes method") -// }, -// GetStartTimeFunc: func() time.Time { -// panic("mock out the GetStartTime method") -// }, -// GetStateFunc: func() apicommon.KeptnState { -// panic("mock out the GetState method") -// }, -// GetVersionFunc: func() string { -// panic("mock out the GetVersion method") -// }, -// IsEndTimeSetFunc: func() bool { -// panic("mock out the IsEndTimeSet method") -// }, -// SetCurrentPhaseFunc: func(s string) { -// panic("mock out the SetCurrentPhase method") -// }, -// SetSpanAttributesFunc: func(span trace.Span) { -// panic("mock out the SetSpanAttributes method") -// }, -// SetStateFunc: func(keptnState apicommon.KeptnState) { -// panic("mock out the SetState method") -// }, -// } +// // make and configure a mocked interfaces.PhaseItem +// mockedPhaseItem := &PhaseItemMock{ +// CompleteFunc: func() { +// panic("mock out the Complete method") +// }, +// DeprecateRemainingPhasesFunc: func(phase apicommon.KeptnPhaseType) { +// panic("mock out the DeprecateRemainingPhases method") +// }, +// GenerateEvaluationFunc: func(evaluationDefinition klcv1alpha3.KeptnEvaluationDefinition, checkType apicommon.CheckType) klcv1alpha3.KeptnEvaluation { +// panic("mock out the GenerateEvaluation method") +// }, +// GenerateTaskFunc: func(taskDefinition klcv1alpha3.KeptnTaskDefinition, checkType apicommon.CheckType) klcv1alpha3.KeptnTask { +// panic("mock out the GenerateTask method") +// }, +// GetAppNameFunc: func() string { +// panic("mock out the GetAppName method") +// }, +// GetCurrentPhaseFunc: func() string { +// panic("mock out the GetCurrentPhase method") +// }, +// GetEndTimeFunc: func() time.Time { +// panic("mock out the GetEndTime method") +// }, +// GetNamespaceFunc: func() string { +// panic("mock out the GetNamespace method") +// }, +// GetParentNameFunc: func() string { +// panic("mock out the GetParentName method") +// }, +// GetPostDeploymentEvaluationTaskStatusFunc: func() []klcv1alpha3.ItemStatus { +// panic("mock out the GetPostDeploymentEvaluationTaskStatus method") +// }, +// GetPostDeploymentEvaluationsFunc: func() []string { +// panic("mock out the GetPostDeploymentEvaluations method") +// }, +// GetPostDeploymentTaskStatusFunc: func() []klcv1alpha3.ItemStatus { +// panic("mock out the GetPostDeploymentTaskStatus method") +// }, +// GetPostDeploymentTasksFunc: func() []string { +// panic("mock out the GetPostDeploymentTasks method") +// }, +// GetPreDeploymentEvaluationTaskStatusFunc: func() []klcv1alpha3.ItemStatus { +// panic("mock out the GetPreDeploymentEvaluationTaskStatus method") +// }, +// GetPreDeploymentEvaluationsFunc: func() []string { +// panic("mock out the GetPreDeploymentEvaluations method") +// }, +// GetPreDeploymentTaskStatusFunc: func() []klcv1alpha3.ItemStatus { +// panic("mock out the GetPreDeploymentTaskStatus method") +// }, +// GetPreDeploymentTasksFunc: func() []string { +// panic("mock out the GetPreDeploymentTasks method") +// }, +// GetPreviousVersionFunc: func() string { +// panic("mock out the GetPreviousVersion method") +// }, +// GetSpanAttributesFunc: func() []attribute.KeyValue { +// panic("mock out the GetSpanAttributes method") +// }, +// GetStartTimeFunc: func() time.Time { +// panic("mock out the GetStartTime method") +// }, +// GetStateFunc: func() apicommon.KeptnState { +// panic("mock out the GetState method") +// }, +// GetVersionFunc: func() string { +// panic("mock out the GetVersion method") +// }, +// IsEndTimeSetFunc: func() bool { +// panic("mock out the IsEndTimeSet method") +// }, +// SetCurrentPhaseFunc: func(s string) { +// panic("mock out the SetCurrentPhase method") +// }, +// SetSpanAttributesFunc: func(span trace.Span) { +// panic("mock out the SetSpanAttributes method") +// }, +// SetStateFunc: func(keptnState apicommon.KeptnState) { +// panic("mock out the SetState method") +// }, +// } // -// // use mockedPhaseItem in code that requires interfaces.PhaseItem -// // and then make assertions. +// // use mockedPhaseItem in code that requires interfaces.PhaseItem +// // and then make assertions. // -// } +// } type PhaseItemMock struct { // CompleteFunc mocks the Complete method. CompleteFunc func() @@ -321,7 +321,8 @@ func (mock *PhaseItemMock) Complete() { // CompleteCalls gets all the calls that were made to Complete. // Check the length with: -// len(mockedPhaseItem.CompleteCalls()) +// +// len(mockedPhaseItem.CompleteCalls()) func (mock *PhaseItemMock) CompleteCalls() []struct { } { var calls []struct { @@ -350,7 +351,8 @@ func (mock *PhaseItemMock) DeprecateRemainingPhases(phase apicommon.KeptnPhaseTy // DeprecateRemainingPhasesCalls gets all the calls that were made to DeprecateRemainingPhases. // Check the length with: -// len(mockedPhaseItem.DeprecateRemainingPhasesCalls()) +// +// len(mockedPhaseItem.DeprecateRemainingPhasesCalls()) func (mock *PhaseItemMock) DeprecateRemainingPhasesCalls() []struct { Phase apicommon.KeptnPhaseType } { @@ -383,7 +385,8 @@ func (mock *PhaseItemMock) GenerateEvaluation(evaluationDefinition klcv1alpha3.K // GenerateEvaluationCalls gets all the calls that were made to GenerateEvaluation. // Check the length with: -// len(mockedPhaseItem.GenerateEvaluationCalls()) +// +// len(mockedPhaseItem.GenerateEvaluationCalls()) func (mock *PhaseItemMock) GenerateEvaluationCalls() []struct { EvaluationDefinition klcv1alpha3.KeptnEvaluationDefinition CheckType apicommon.CheckType @@ -418,7 +421,8 @@ func (mock *PhaseItemMock) GenerateTask(taskDefinition klcv1alpha3.KeptnTaskDefi // GenerateTaskCalls gets all the calls that were made to GenerateTask. // Check the length with: -// len(mockedPhaseItem.GenerateTaskCalls()) +// +// len(mockedPhaseItem.GenerateTaskCalls()) func (mock *PhaseItemMock) GenerateTaskCalls() []struct { TaskDefinition klcv1alpha3.KeptnTaskDefinition CheckType apicommon.CheckType @@ -448,7 +452,8 @@ func (mock *PhaseItemMock) GetAppName() string { // GetAppNameCalls gets all the calls that were made to GetAppName. // Check the length with: -// len(mockedPhaseItem.GetAppNameCalls()) +// +// len(mockedPhaseItem.GetAppNameCalls()) func (mock *PhaseItemMock) GetAppNameCalls() []struct { } { var calls []struct { @@ -474,7 +479,8 @@ func (mock *PhaseItemMock) GetCurrentPhase() string { // GetCurrentPhaseCalls gets all the calls that were made to GetCurrentPhase. // Check the length with: -// len(mockedPhaseItem.GetCurrentPhaseCalls()) +// +// len(mockedPhaseItem.GetCurrentPhaseCalls()) func (mock *PhaseItemMock) GetCurrentPhaseCalls() []struct { } { var calls []struct { @@ -500,7 +506,8 @@ func (mock *PhaseItemMock) GetEndTime() time.Time { // GetEndTimeCalls gets all the calls that were made to GetEndTime. // Check the length with: -// len(mockedPhaseItem.GetEndTimeCalls()) +// +// len(mockedPhaseItem.GetEndTimeCalls()) func (mock *PhaseItemMock) GetEndTimeCalls() []struct { } { var calls []struct { @@ -526,7 +533,8 @@ func (mock *PhaseItemMock) GetNamespace() string { // GetNamespaceCalls gets all the calls that were made to GetNamespace. // Check the length with: -// len(mockedPhaseItem.GetNamespaceCalls()) +// +// len(mockedPhaseItem.GetNamespaceCalls()) func (mock *PhaseItemMock) GetNamespaceCalls() []struct { } { var calls []struct { @@ -552,7 +560,8 @@ func (mock *PhaseItemMock) GetParentName() string { // GetParentNameCalls gets all the calls that were made to GetParentName. // Check the length with: -// len(mockedPhaseItem.GetParentNameCalls()) +// +// len(mockedPhaseItem.GetParentNameCalls()) func (mock *PhaseItemMock) GetParentNameCalls() []struct { } { var calls []struct { @@ -578,7 +587,8 @@ func (mock *PhaseItemMock) GetPostDeploymentEvaluationTaskStatus() []klcv1alpha3 // GetPostDeploymentEvaluationTaskStatusCalls gets all the calls that were made to GetPostDeploymentEvaluationTaskStatus. // Check the length with: -// len(mockedPhaseItem.GetPostDeploymentEvaluationTaskStatusCalls()) +// +// len(mockedPhaseItem.GetPostDeploymentEvaluationTaskStatusCalls()) func (mock *PhaseItemMock) GetPostDeploymentEvaluationTaskStatusCalls() []struct { } { var calls []struct { @@ -604,7 +614,8 @@ func (mock *PhaseItemMock) GetPostDeploymentEvaluations() []string { // GetPostDeploymentEvaluationsCalls gets all the calls that were made to GetPostDeploymentEvaluations. // Check the length with: -// len(mockedPhaseItem.GetPostDeploymentEvaluationsCalls()) +// +// len(mockedPhaseItem.GetPostDeploymentEvaluationsCalls()) func (mock *PhaseItemMock) GetPostDeploymentEvaluationsCalls() []struct { } { var calls []struct { @@ -630,7 +641,8 @@ func (mock *PhaseItemMock) GetPostDeploymentTaskStatus() []klcv1alpha3.ItemStatu // GetPostDeploymentTaskStatusCalls gets all the calls that were made to GetPostDeploymentTaskStatus. // Check the length with: -// len(mockedPhaseItem.GetPostDeploymentTaskStatusCalls()) +// +// len(mockedPhaseItem.GetPostDeploymentTaskStatusCalls()) func (mock *PhaseItemMock) GetPostDeploymentTaskStatusCalls() []struct { } { var calls []struct { @@ -656,7 +668,8 @@ func (mock *PhaseItemMock) GetPostDeploymentTasks() []string { // GetPostDeploymentTasksCalls gets all the calls that were made to GetPostDeploymentTasks. // Check the length with: -// len(mockedPhaseItem.GetPostDeploymentTasksCalls()) +// +// len(mockedPhaseItem.GetPostDeploymentTasksCalls()) func (mock *PhaseItemMock) GetPostDeploymentTasksCalls() []struct { } { var calls []struct { @@ -682,7 +695,8 @@ func (mock *PhaseItemMock) GetPreDeploymentEvaluationTaskStatus() []klcv1alpha3. // GetPreDeploymentEvaluationTaskStatusCalls gets all the calls that were made to GetPreDeploymentEvaluationTaskStatus. // Check the length with: -// len(mockedPhaseItem.GetPreDeploymentEvaluationTaskStatusCalls()) +// +// len(mockedPhaseItem.GetPreDeploymentEvaluationTaskStatusCalls()) func (mock *PhaseItemMock) GetPreDeploymentEvaluationTaskStatusCalls() []struct { } { var calls []struct { @@ -708,7 +722,8 @@ func (mock *PhaseItemMock) GetPreDeploymentEvaluations() []string { // GetPreDeploymentEvaluationsCalls gets all the calls that were made to GetPreDeploymentEvaluations. // Check the length with: -// len(mockedPhaseItem.GetPreDeploymentEvaluationsCalls()) +// +// len(mockedPhaseItem.GetPreDeploymentEvaluationsCalls()) func (mock *PhaseItemMock) GetPreDeploymentEvaluationsCalls() []struct { } { var calls []struct { @@ -734,7 +749,8 @@ func (mock *PhaseItemMock) GetPreDeploymentTaskStatus() []klcv1alpha3.ItemStatus // GetPreDeploymentTaskStatusCalls gets all the calls that were made to GetPreDeploymentTaskStatus. // Check the length with: -// len(mockedPhaseItem.GetPreDeploymentTaskStatusCalls()) +// +// len(mockedPhaseItem.GetPreDeploymentTaskStatusCalls()) func (mock *PhaseItemMock) GetPreDeploymentTaskStatusCalls() []struct { } { var calls []struct { @@ -760,7 +776,8 @@ func (mock *PhaseItemMock) GetPreDeploymentTasks() []string { // GetPreDeploymentTasksCalls gets all the calls that were made to GetPreDeploymentTasks. // Check the length with: -// len(mockedPhaseItem.GetPreDeploymentTasksCalls()) +// +// len(mockedPhaseItem.GetPreDeploymentTasksCalls()) func (mock *PhaseItemMock) GetPreDeploymentTasksCalls() []struct { } { var calls []struct { @@ -786,7 +803,8 @@ func (mock *PhaseItemMock) GetPreviousVersion() string { // GetPreviousVersionCalls gets all the calls that were made to GetPreviousVersion. // Check the length with: -// len(mockedPhaseItem.GetPreviousVersionCalls()) +// +// len(mockedPhaseItem.GetPreviousVersionCalls()) func (mock *PhaseItemMock) GetPreviousVersionCalls() []struct { } { var calls []struct { @@ -812,7 +830,8 @@ func (mock *PhaseItemMock) GetSpanAttributes() []attribute.KeyValue { // GetSpanAttributesCalls gets all the calls that were made to GetSpanAttributes. // Check the length with: -// len(mockedPhaseItem.GetSpanAttributesCalls()) +// +// len(mockedPhaseItem.GetSpanAttributesCalls()) func (mock *PhaseItemMock) GetSpanAttributesCalls() []struct { } { var calls []struct { @@ -838,7 +857,8 @@ func (mock *PhaseItemMock) GetStartTime() time.Time { // GetStartTimeCalls gets all the calls that were made to GetStartTime. // Check the length with: -// len(mockedPhaseItem.GetStartTimeCalls()) +// +// len(mockedPhaseItem.GetStartTimeCalls()) func (mock *PhaseItemMock) GetStartTimeCalls() []struct { } { var calls []struct { @@ -864,7 +884,8 @@ func (mock *PhaseItemMock) GetState() apicommon.KeptnState { // GetStateCalls gets all the calls that were made to GetState. // Check the length with: -// len(mockedPhaseItem.GetStateCalls()) +// +// len(mockedPhaseItem.GetStateCalls()) func (mock *PhaseItemMock) GetStateCalls() []struct { } { var calls []struct { @@ -890,7 +911,8 @@ func (mock *PhaseItemMock) GetVersion() string { // GetVersionCalls gets all the calls that were made to GetVersion. // Check the length with: -// len(mockedPhaseItem.GetVersionCalls()) +// +// len(mockedPhaseItem.GetVersionCalls()) func (mock *PhaseItemMock) GetVersionCalls() []struct { } { var calls []struct { @@ -916,7 +938,8 @@ func (mock *PhaseItemMock) IsEndTimeSet() bool { // IsEndTimeSetCalls gets all the calls that were made to IsEndTimeSet. // Check the length with: -// len(mockedPhaseItem.IsEndTimeSetCalls()) +// +// len(mockedPhaseItem.IsEndTimeSetCalls()) func (mock *PhaseItemMock) IsEndTimeSetCalls() []struct { } { var calls []struct { @@ -945,7 +968,8 @@ func (mock *PhaseItemMock) SetCurrentPhase(s string) { // SetCurrentPhaseCalls gets all the calls that were made to SetCurrentPhase. // Check the length with: -// len(mockedPhaseItem.SetCurrentPhaseCalls()) +// +// len(mockedPhaseItem.SetCurrentPhaseCalls()) func (mock *PhaseItemMock) SetCurrentPhaseCalls() []struct { S string } { @@ -976,7 +1000,8 @@ func (mock *PhaseItemMock) SetSpanAttributes(span trace.Span) { // SetSpanAttributesCalls gets all the calls that were made to SetSpanAttributes. // Check the length with: -// len(mockedPhaseItem.SetSpanAttributesCalls()) +// +// len(mockedPhaseItem.SetSpanAttributesCalls()) func (mock *PhaseItemMock) SetSpanAttributesCalls() []struct { Span trace.Span } { @@ -1007,7 +1032,8 @@ func (mock *PhaseItemMock) SetState(keptnState apicommon.KeptnState) { // SetStateCalls gets all the calls that were made to SetState. // Check the length with: -// len(mockedPhaseItem.SetStateCalls()) +// +// len(mockedPhaseItem.SetStateCalls()) func (mock *PhaseItemMock) SetStateCalls() []struct { KeptnState apicommon.KeptnState } { From 17a073670b188f076c18d1943e740d10d2ff8e6a Mon Sep 17 00:00:00 2001 From: geoffrey1330 Date: Sun, 4 Jun 2023 14:02:27 +0100 Subject: [PATCH 19/44] Added testcase keptntaskdefinition_webhook_test.go for keptntaskdefinition_webhook.go Signed-off-by: geoffrey1330 --- .../apis/lifecycle/v1alpha3/keptntaskdefinition_webhook_test.go | 1 - 1 file changed, 1 deletion(-) diff --git a/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook_test.go b/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook_test.go index 4cf6063991..48f64b08c5 100644 --- a/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook_test.go +++ b/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook_test.go @@ -5,7 +5,6 @@ import ( "testing" "github.com/pkg/errors" - //metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/util/validation/field" ) From 47ecfcd37427f9ab1dd5eb9934bfd1e1a4067a22 Mon Sep 17 00:00:00 2001 From: geoffrey1330 Date: Sun, 4 Jun 2023 14:13:11 +0100 Subject: [PATCH 20/44] Added ObjectMeta to the testcase keptntaskdefinition_webhook_test.go for keptntaskdefinition_webhook.go Signed-off-by: geoffrey1330 --- .../lifecycle/v1alpha3/keptntaskdefinition_webhook_test.go | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook_test.go b/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook_test.go index 48f64b08c5..540d10a025 100644 --- a/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook_test.go +++ b/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook_test.go @@ -5,6 +5,7 @@ import ( "testing" "github.com/pkg/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/util/validation/field" ) @@ -55,7 +56,8 @@ func TestKeptnTaskDefinition_ValidateFields(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ktd := &KeptnTaskDefinition{ - Spec: tt.spec, + ObjectMeta: metav1.ObjectMeta{Name: tt.name}, + Spec: tt.spec, } if got := ktd.validateFields(); !reflect.DeepEqual(got, tt.want) { t.Errorf("validateFields() = %v, want %v", got, tt.want) From 21cf221721f4d3a9ec6ebf471bc514ac49f070c4 Mon Sep 17 00:00:00 2001 From: geoffrey1330 Date: Sun, 4 Jun 2023 19:18:42 +0100 Subject: [PATCH 21/44] deleted certificate.yaml and webhookcainjection_patch.yaml Signed-off-by: geoffrey1330 --- operator/PROJECT | 4 -- operator/config/certmanager/certificate.yaml | 39 ------------------- .../default/webhookcainjection_patch.yaml | 29 -------------- 3 files changed, 72 deletions(-) delete mode 100644 operator/config/certmanager/certificate.yaml delete mode 100644 operator/config/default/webhookcainjection_patch.yaml diff --git a/operator/PROJECT b/operator/PROJECT index 30e8c4b73f..8c88afe3d8 100644 --- a/operator/PROJECT +++ b/operator/PROJECT @@ -1,7 +1,3 @@ -# Code generated by tool. DO NOT EDIT. -# This file is used to track the info used to scaffold your project -# and allow the plugins properly work. -# More info: https://book.kubebuilder.io/reference/project-config.html domain: keptn.sh layout: - go.kubebuilder.io/v3 diff --git a/operator/config/certmanager/certificate.yaml b/operator/config/certmanager/certificate.yaml deleted file mode 100644 index f587f5bc9d..0000000000 --- a/operator/config/certmanager/certificate.yaml +++ /dev/null @@ -1,39 +0,0 @@ -# The following manifests contain a self-signed issuer CR and a certificate CR. -# More document can be found at https://docs.cert-manager.io -# WARNING: Targets CertManager v1.0. Check https://cert-manager.io/docs/installation/upgrading/ for breaking changes. -apiVersion: cert-manager.io/v1 -kind: Issuer -metadata: - labels: - app.kubernetes.io/name: issuer - app.kubernetes.io/instance: selfsigned-issuer - app.kubernetes.io/component: certificate - app.kubernetes.io/created-by: keptn-lifecycle-toolkit - app.kubernetes.io/part-of: keptn-lifecycle-toolkit - app.kubernetes.io/managed-by: kustomize - name: selfsigned-issuer - namespace: system -spec: - selfSigned: {} ---- -apiVersion: cert-manager.io/v1 -kind: Certificate -metadata: - labels: - app.kubernetes.io/name: certificate - app.kubernetes.io/instance: serving-cert - app.kubernetes.io/component: certificate - app.kubernetes.io/created-by: keptn-lifecycle-toolkit - app.kubernetes.io/part-of: keptn-lifecycle-toolkit - app.kubernetes.io/managed-by: kustomize - name: serving-cert # this name should match the one appeared in kustomizeconfig.yaml - namespace: system -spec: - # $(SERVICE_NAME) and $(SERVICE_NAMESPACE) will be substituted by kustomize - dnsNames: - - $(SERVICE_NAME).$(SERVICE_NAMESPACE).svc - - $(SERVICE_NAME).$(SERVICE_NAMESPACE).svc.cluster.local - issuerRef: - kind: Issuer - name: selfsigned-issuer - secretName: webhook-server-cert # this secret will not be prefixed, since it's not managed by kustomize diff --git a/operator/config/default/webhookcainjection_patch.yaml b/operator/config/default/webhookcainjection_patch.yaml deleted file mode 100644 index c7cbe14322..0000000000 --- a/operator/config/default/webhookcainjection_patch.yaml +++ /dev/null @@ -1,29 +0,0 @@ -# This patch add annotation to admission webhook config and -# the variables $(CERTIFICATE_NAMESPACE) and $(CERTIFICATE_NAME) will be substituted by kustomize. -apiVersion: admissionregistration.k8s.io/v1 -kind: MutatingWebhookConfiguration -metadata: - labels: - app.kubernetes.io/name: mutatingwebhookconfiguration - app.kubernetes.io/instance: mutating-webhook-configuration - app.kubernetes.io/component: webhook - app.kubernetes.io/created-by: keptn-lifecycle-toolkit - app.kubernetes.io/part-of: keptn-lifecycle-toolkit - app.kubernetes.io/managed-by: kustomize - name: mutating-webhook-configuration - annotations: - cert-manager.io/inject-ca-from: $(CERTIFICATE_NAMESPACE)/$(CERTIFICATE_NAME) ---- -apiVersion: admissionregistration.k8s.io/v1 -kind: ValidatingWebhookConfiguration -metadata: - labels: - app.kubernetes.io/name: validatingwebhookconfiguration - app.kubernetes.io/instance: validating-webhook-configuration - app.kubernetes.io/component: webhook - app.kubernetes.io/created-by: keptn-lifecycle-toolkit - app.kubernetes.io/part-of: keptn-lifecycle-toolkit - app.kubernetes.io/managed-by: kustomize - name: validating-webhook-configuration - annotations: - cert-manager.io/inject-ca-from: $(CERTIFICATE_NAMESPACE)/$(CERTIFICATE_NAME) From b6fa939bccebf4066dd54b87f46086f4a88582c0 Mon Sep 17 00:00:00 2001 From: geoffrey1330 Date: Sun, 4 Jun 2023 19:27:20 +0100 Subject: [PATCH 22/44] deleted config directory Signed-off-by: geoffrey1330 --- operator/config/certmanager/kustomization.yaml | 5 ----- operator/config/certmanager/kustomizeconfig.yaml | 16 ---------------- 2 files changed, 21 deletions(-) delete mode 100644 operator/config/certmanager/kustomization.yaml delete mode 100644 operator/config/certmanager/kustomizeconfig.yaml diff --git a/operator/config/certmanager/kustomization.yaml b/operator/config/certmanager/kustomization.yaml deleted file mode 100644 index bebea5a595..0000000000 --- a/operator/config/certmanager/kustomization.yaml +++ /dev/null @@ -1,5 +0,0 @@ -resources: -- certificate.yaml - -configurations: -- kustomizeconfig.yaml diff --git a/operator/config/certmanager/kustomizeconfig.yaml b/operator/config/certmanager/kustomizeconfig.yaml deleted file mode 100644 index e631f77736..0000000000 --- a/operator/config/certmanager/kustomizeconfig.yaml +++ /dev/null @@ -1,16 +0,0 @@ -# This configuration is for teaching kustomize how to update name ref and var substitution -nameReference: -- kind: Issuer - group: cert-manager.io - fieldSpecs: - - kind: Certificate - group: cert-manager.io - path: spec/issuerRef/name - -varReference: -- kind: Certificate - group: cert-manager.io - path: spec/commonName -- kind: Certificate - group: cert-manager.io - path: spec/dnsNames From fe86366ff038ad1a4ce20cfc2e49f5232c94ba06 Mon Sep 17 00:00:00 2001 From: geoffrey1330 Date: Mon, 5 Jun 2023 07:28:29 +0100 Subject: [PATCH 23/44] reverted back the changes in the imports in main.go and fixed yaml issue Signed-off-by: geoffrey1330 --- operator/main.go | 27 +++++++++++++-------------- 1 file changed, 13 insertions(+), 14 deletions(-) diff --git a/operator/main.go b/operator/main.go index 50af730da9..809f844a86 100644 --- a/operator/main.go +++ b/operator/main.go @@ -29,20 +29,6 @@ import ( certCommon "github.com/keptn/lifecycle-toolkit/klt-cert-manager/pkg/common" "github.com/keptn/lifecycle-toolkit/klt-cert-manager/pkg/webhook" metricsapi "github.com/keptn/lifecycle-toolkit/metrics-operator/api/v1alpha3" - "github.com/prometheus/client_golang/prometheus/promhttp" - "go.opentelemetry.io/otel" - otelprom "go.opentelemetry.io/otel/exporters/prometheus" - "go.opentelemetry.io/otel/sdk/metric" - corev1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/runtime" - utilruntime "k8s.io/apimachinery/pkg/util/runtime" - clientgoscheme "k8s.io/client-go/kubernetes/scheme" - ctrl "sigs.k8s.io/controller-runtime" - ctrlclient "sigs.k8s.io/controller-runtime/pkg/client" - "sigs.k8s.io/controller-runtime/pkg/healthz" - "sigs.k8s.io/controller-runtime/pkg/log/zap" - ctrlWebhook "sigs.k8s.io/controller-runtime/pkg/webhook" - lifecyclev1alpha1 "github.com/keptn/lifecycle-toolkit/operator/apis/lifecycle/v1alpha1" lifecyclev1alpha2 "github.com/keptn/lifecycle-toolkit/operator/apis/lifecycle/v1alpha2" lifecyclev1alpha3 "github.com/keptn/lifecycle-toolkit/operator/apis/lifecycle/v1alpha3" @@ -58,6 +44,19 @@ import ( "github.com/keptn/lifecycle-toolkit/operator/controllers/lifecycle/keptnworkloadinstance" controlleroptions "github.com/keptn/lifecycle-toolkit/operator/controllers/options" "github.com/keptn/lifecycle-toolkit/operator/webhooks/pod_mutator" + "github.com/prometheus/client_golang/prometheus/promhttp" + "go.opentelemetry.io/otel" + otelprom "go.opentelemetry.io/otel/exporters/prometheus" + "go.opentelemetry.io/otel/sdk/metric" + corev1 "k8s.io/api/core/v1" + "k8s.io/apimachinery/pkg/runtime" + utilruntime "k8s.io/apimachinery/pkg/util/runtime" + clientgoscheme "k8s.io/client-go/kubernetes/scheme" + ctrl "sigs.k8s.io/controller-runtime" + ctrlclient "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/healthz" + "sigs.k8s.io/controller-runtime/pkg/log/zap" + ctrlWebhook "sigs.k8s.io/controller-runtime/pkg/webhook" ) var ( From b5e4d78cbeaf74c4c2146e7224f57999e90f96b3 Mon Sep 17 00:00:00 2001 From: geoffrey1330 Date: Mon, 5 Jun 2023 07:39:27 +0100 Subject: [PATCH 24/44] reverted back the changes in the imports in main.go and fixed yaml issue Signed-off-by: geoffrey1330 --- operator/config/webhook/manifests.yaml | 2 -- 1 file changed, 2 deletions(-) diff --git a/operator/config/webhook/manifests.yaml b/operator/config/webhook/manifests.yaml index 7be5de23da..125ff82aef 100644 --- a/operator/config/webhook/manifests.yaml +++ b/operator/config/webhook/manifests.yaml @@ -27,7 +27,6 @@ webhooks: resources: - pods sideEffects: None - --- apiVersion: admissionregistration.k8s.io/v1 kind: ValidatingWebhookConfiguration @@ -57,4 +56,3 @@ webhooks: resources: - keptntaskdefinitions sideEffects: None - From afe5d3285315da6f98ca10b714573450dd6a77df Mon Sep 17 00:00:00 2001 From: geoffrey1330 Date: Mon, 5 Jun 2023 07:49:24 +0100 Subject: [PATCH 25/44] reverted back the changes in the imports in main.go and fixed yaml issue Signed-off-by: geoffrey1330 --- operator/config/webhook/manifests.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/operator/config/webhook/manifests.yaml b/operator/config/webhook/manifests.yaml index 125ff82aef..b53d4e7942 100644 --- a/operator/config/webhook/manifests.yaml +++ b/operator/config/webhook/manifests.yaml @@ -42,9 +42,9 @@ webhooks: service: name: lifecycle-webhook-service namespace: system - path: /validate-lifecycle-keptn-sh-v1alpha3-keptntaskdefinition + path: /validate-lifecycle-keptn-sh-v1alpha3-keptntaskdefinition failurePolicy: Fail - name: vkeptntaskdefinition.kb.io + name: vkeptntaskdefinition.kb.io rules: - apiGroups: - lifecycle.keptn.sh From 1bf4bbf34d0aaf007aa16f5f81d85ae29f3c36a8 Mon Sep 17 00:00:00 2001 From: geoffrey1330 Date: Mon, 5 Jun 2023 07:53:57 +0100 Subject: [PATCH 26/44] reverted back the changes in the imports in main.go and fixed yaml issue Signed-off-by: geoffrey1330 --- .../config/default/manager_webhook_patch.yaml | 26 +++++++++---------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/operator/config/default/manager_webhook_patch.yaml b/operator/config/default/manager_webhook_patch.yaml index 738de350b7..8a96063a23 100644 --- a/operator/config/default/manager_webhook_patch.yaml +++ b/operator/config/default/manager_webhook_patch.yaml @@ -7,17 +7,17 @@ spec: template: spec: containers: - - name: manager - ports: - - containerPort: 9443 - name: webhook-server - protocol: TCP - volumeMounts: - - mountPath: /tmp/k8s-webhook-server/serving-certs - name: cert - readOnly: true + - name: manager + ports: + - containerPort: 9443 + name: webhook-server + protocol: TCP + volumeMounts: + - mountPath: /tmp/k8s-webhook-server/serving-certs + name: cert + readOnly: true volumes: - - name: cert - secret: - defaultMode: 420 - secretName: webhook-server-cert + - name: cert + secret: + defaultMode: 420 + secretName: webhook-server-cert From 5ab6bc2b1e38b004e170726881a52af535cb987a Mon Sep 17 00:00:00 2001 From: geoffrey1330 Date: Mon, 5 Jun 2023 09:49:18 +0100 Subject: [PATCH 27/44] Added integration test for validate taskdefinition Signed-off-by: geoffrey1330 --- .../00-teststep-install.yaml | 7 +++++ .../01-teststep-assert.yaml | 6 ++++ .../badtaskdefinition.yaml | 24 +++++++++++++++ .../goodtaskdefinition.yaml | 29 +++++++++++++++++++ 4 files changed, 66 insertions(+) create mode 100644 test/integration/validate-taskdefinition/00-teststep-install.yaml create mode 100644 test/integration/validate-taskdefinition/01-teststep-assert.yaml create mode 100644 test/integration/validate-taskdefinition/badtaskdefinition.yaml create mode 100644 test/integration/validate-taskdefinition/goodtaskdefinition.yaml diff --git a/test/integration/validate-taskdefinition/00-teststep-install.yaml b/test/integration/validate-taskdefinition/00-teststep-install.yaml new file mode 100644 index 0000000000..a3ce371ca2 --- /dev/null +++ b/test/integration/validate-taskdefinition/00-teststep-install.yaml @@ -0,0 +1,7 @@ +apiVersion: kuttl.dev/v1beta1 +kind: TestStep +apply: + - goodtaskdefinition.yaml +commands: + - command: kubectl apply -f badtaskdefinition.yaml + ignoreFailure: true #we must install ignoring the validating webhook error to proceed with the test diff --git a/test/integration/validate-taskdefinition/01-teststep-assert.yaml b/test/integration/validate-taskdefinition/01-teststep-assert.yaml new file mode 100644 index 0000000000..2c6105a719 --- /dev/null +++ b/test/integration/validate-taskdefinition/01-teststep-assert.yaml @@ -0,0 +1,6 @@ +apiVersion: kuttl.dev/v1beta1 +kind: TestStep +error: #this checks that kubectl get resource fails, AKA bad CRD not added + - badtaskdefinition.yaml +assert: #this checks that kubectl get resource succeeds + - goodtaskdefinition.yaml diff --git a/test/integration/validate-taskdefinition/badtaskdefinition.yaml b/test/integration/validate-taskdefinition/badtaskdefinition.yaml new file mode 100644 index 0000000000..c933f5c398 --- /dev/null +++ b/test/integration/validate-taskdefinition/badtaskdefinition.yaml @@ -0,0 +1,24 @@ +apiVersion: lifecycle.keptn.sh/v1alpha3 +kind: KeptnTaskDefinition +metadata: + name: badtaskdefinition +spec: + container: + name: keptntaskdefinition + image: busybox:1.36.0 + resources: + limits: + memory: "200Mi" + command: + - 'echo' + - 'Hello World!' + - '>' + - '/cache/log.txt' + volumeMounts: + - mountPath: /cache + name: logger + function: + inline: + code: | + console.log('hello'); + \ No newline at end of file diff --git a/test/integration/validate-taskdefinition/goodtaskdefinition.yaml b/test/integration/validate-taskdefinition/goodtaskdefinition.yaml new file mode 100644 index 0000000000..519f5dcbee --- /dev/null +++ b/test/integration/validate-taskdefinition/goodtaskdefinition.yaml @@ -0,0 +1,29 @@ +apiVersion: lifecycle.keptn.sh/v1alpha3 +kind: KeptnTaskDefinition +metadata: + name: goodtaskdefinition1 +spec: + container: + name: keptntaskdefinition1 + image: busybox:1.36.0 + resources: + limits: + memory: "200Mi" + command: + - 'echo' + - 'Hello World!' + - '>' + - '/cache/log.txt' + volumeMounts: + - mountPath: /cache + name: logger +--- +apiVersion: lifecycle.keptn.sh/v1alpha3 +kind: KeptnTaskDefinition +metadata: + name: goodtaskdefinition2 +spec: + function: + inline: + code: | + console.log('hello'); From 6244d0421cb02ccaa741bacfc6f7f1ed81a8e505 Mon Sep 17 00:00:00 2001 From: geoffrey1330 Date: Mon, 5 Jun 2023 10:13:37 +0100 Subject: [PATCH 28/44] Added integration test for validate taskdefinition Signed-off-by: geoffrey1330 --- .../validate-taskdefinition/00-teststep-install.yaml | 6 +++--- .../validate-taskdefinition/01-teststep-assert.yaml | 8 ++++---- .../validate-taskdefinition/badtaskdefinition.yaml | 2 +- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/test/integration/validate-taskdefinition/00-teststep-install.yaml b/test/integration/validate-taskdefinition/00-teststep-install.yaml index a3ce371ca2..a65f372148 100644 --- a/test/integration/validate-taskdefinition/00-teststep-install.yaml +++ b/test/integration/validate-taskdefinition/00-teststep-install.yaml @@ -1,7 +1,7 @@ apiVersion: kuttl.dev/v1beta1 kind: TestStep apply: - - goodtaskdefinition.yaml + - goodtaskdefinition.yaml commands: - - command: kubectl apply -f badtaskdefinition.yaml - ignoreFailure: true #we must install ignoring the validating webhook error to proceed with the test + - command: kubectl apply -f badtaskdefinition.yaml + ignoreFailure: true # we must install ignoring the validating webhook error to proceed with the test diff --git a/test/integration/validate-taskdefinition/01-teststep-assert.yaml b/test/integration/validate-taskdefinition/01-teststep-assert.yaml index 2c6105a719..92a0b614a1 100644 --- a/test/integration/validate-taskdefinition/01-teststep-assert.yaml +++ b/test/integration/validate-taskdefinition/01-teststep-assert.yaml @@ -1,6 +1,6 @@ apiVersion: kuttl.dev/v1beta1 kind: TestStep -error: #this checks that kubectl get resource fails, AKA bad CRD not added - - badtaskdefinition.yaml -assert: #this checks that kubectl get resource succeeds - - goodtaskdefinition.yaml +error: # this checks that kubectl get resource fails, AKA bad CRD not added + - badtaskdefinition.yaml +assert: # this checks that kubectl get resource succeeds + - goodtaskdefinition.yaml diff --git a/test/integration/validate-taskdefinition/badtaskdefinition.yaml b/test/integration/validate-taskdefinition/badtaskdefinition.yaml index c933f5c398..10ad2cdfc8 100644 --- a/test/integration/validate-taskdefinition/badtaskdefinition.yaml +++ b/test/integration/validate-taskdefinition/badtaskdefinition.yaml @@ -21,4 +21,4 @@ spec: inline: code: | console.log('hello'); - \ No newline at end of file + From 58708022fba8e7f66d649eaa669149c2a3dd002a Mon Sep 17 00:00:00 2001 From: geoffrey1330 Date: Mon, 5 Jun 2023 10:42:15 +0100 Subject: [PATCH 29/44] Added comment to the integration test for validating taskdefinition Signed-off-by: geoffrey1330 --- .../validate-taskdefinition/badtaskdefinition.yaml | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/test/integration/validate-taskdefinition/badtaskdefinition.yaml b/test/integration/validate-taskdefinition/badtaskdefinition.yaml index 10ad2cdfc8..7ae77a106a 100644 --- a/test/integration/validate-taskdefinition/badtaskdefinition.yaml +++ b/test/integration/validate-taskdefinition/badtaskdefinition.yaml @@ -1,7 +1,8 @@ +#this TaskDefinition will not be accepted by the validation webhook as it contains both containerSpec and functionSpec apiVersion: lifecycle.keptn.sh/v1alpha3 kind: KeptnTaskDefinition metadata: - name: badtaskdefinition + name: badtaskdefinition1 spec: container: name: keptntaskdefinition @@ -21,4 +22,10 @@ spec: inline: code: | console.log('hello'); - +--- +#this TaskDefinition will not be accepted by the validation webhook as it doesn't contains either containerSpec or functionSpec +apiVersion: lifecycle.keptn.sh/v1alpha3 +kind: KeptnTaskDefinition +metadata: + name: badtaskdefinition2 +spec: From a9e05b4701ef3bee006288bcb2ad20b4fcc27b6d Mon Sep 17 00:00:00 2001 From: geoffrey1330 Date: Mon, 5 Jun 2023 10:44:05 +0100 Subject: [PATCH 30/44] Added comment to the integration test for validating taskdefinition Signed-off-by: geoffrey1330 --- .../validate-taskdefinition/badtaskdefinition.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/integration/validate-taskdefinition/badtaskdefinition.yaml b/test/integration/validate-taskdefinition/badtaskdefinition.yaml index 7ae77a106a..6640f7d8dd 100644 --- a/test/integration/validate-taskdefinition/badtaskdefinition.yaml +++ b/test/integration/validate-taskdefinition/badtaskdefinition.yaml @@ -1,4 +1,4 @@ -#this TaskDefinition will not be accepted by the validation webhook as it contains both containerSpec and functionSpec +# This TaskDefinition will not be accepted by the validation webhook as it contains both containerSpec and functionSpec apiVersion: lifecycle.keptn.sh/v1alpha3 kind: KeptnTaskDefinition metadata: @@ -23,7 +23,7 @@ spec: code: | console.log('hello'); --- -#this TaskDefinition will not be accepted by the validation webhook as it doesn't contains either containerSpec or functionSpec +# This TaskDefinition will not be accepted by the validation webhook as it doesn't contains either containerSpec or functionSpec apiVersion: lifecycle.keptn.sh/v1alpha3 kind: KeptnTaskDefinition metadata: From 16cc385a13ebc31d4f8b3b8b520acf6f5b689f11 Mon Sep 17 00:00:00 2001 From: geoffrey1330 Date: Mon, 5 Jun 2023 10:45:21 +0100 Subject: [PATCH 31/44] Added comment to the integration test for validating taskdefinition Signed-off-by: geoffrey1330 --- test/integration/validate-taskdefinition/badtaskdefinition.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/integration/validate-taskdefinition/badtaskdefinition.yaml b/test/integration/validate-taskdefinition/badtaskdefinition.yaml index 6640f7d8dd..83a4d02ae6 100644 --- a/test/integration/validate-taskdefinition/badtaskdefinition.yaml +++ b/test/integration/validate-taskdefinition/badtaskdefinition.yaml @@ -23,7 +23,7 @@ spec: code: | console.log('hello'); --- -# This TaskDefinition will not be accepted by the validation webhook as it doesn't contains either containerSpec or functionSpec +# This TaskDefinition will not be accepted by the validation webhook as it doesn't contain either containerSpec or functionSpec apiVersion: lifecycle.keptn.sh/v1alpha3 kind: KeptnTaskDefinition metadata: From c2d41290e6c03cbbab4221ee7901b862ac837e80 Mon Sep 17 00:00:00 2001 From: geoffrey1330 Date: Mon, 5 Jun 2023 11:08:21 +0100 Subject: [PATCH 32/44] Added comment to the integration test for validating taskdefinition Signed-off-by: geoffrey1330 --- test/integration/validate-taskdefinition/badtaskdefinition.yaml | 1 + 1 file changed, 1 insertion(+) diff --git a/test/integration/validate-taskdefinition/badtaskdefinition.yaml b/test/integration/validate-taskdefinition/badtaskdefinition.yaml index 83a4d02ae6..f4e6bca882 100644 --- a/test/integration/validate-taskdefinition/badtaskdefinition.yaml +++ b/test/integration/validate-taskdefinition/badtaskdefinition.yaml @@ -29,3 +29,4 @@ kind: KeptnTaskDefinition metadata: name: badtaskdefinition2 spec: + From ba845ecf8eaba81c6ab5504a006b16a087258fb3 Mon Sep 17 00:00:00 2001 From: geoffrey1330 Date: Mon, 5 Jun 2023 11:19:13 +0100 Subject: [PATCH 33/44] Added comment to the integration test for validating taskdefinition Signed-off-by: geoffrey1330 --- .../validate-taskdefinition/badtaskdefinition.yaml | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/test/integration/validate-taskdefinition/badtaskdefinition.yaml b/test/integration/validate-taskdefinition/badtaskdefinition.yaml index f4e6bca882..70f8fe407d 100644 --- a/test/integration/validate-taskdefinition/badtaskdefinition.yaml +++ b/test/integration/validate-taskdefinition/badtaskdefinition.yaml @@ -1,4 +1,4 @@ -# This TaskDefinition will not be accepted by the validation webhook as it contains both containerSpec and functionSpec +# This TaskDefinition will not be accepted by the validation webhook as it contains both containerSpec and functionSpec apiVersion: lifecycle.keptn.sh/v1alpha3 kind: KeptnTaskDefinition metadata: @@ -18,15 +18,12 @@ spec: volumeMounts: - mountPath: /cache name: logger - function: - inline: - code: | - console.log('hello'); + --- -# This TaskDefinition will not be accepted by the validation webhook as it doesn't contain either containerSpec or functionSpec +# This TaskDefinition will not be accepted by the validation webhook as it doesn't contain either containerSpec or functionSpec apiVersion: lifecycle.keptn.sh/v1alpha3 kind: KeptnTaskDefinition metadata: name: badtaskdefinition2 spec: - + From 4528ea8b10a1e36c3616b19417ca0f7b3f3954a9 Mon Sep 17 00:00:00 2001 From: geoffrey1330 Date: Mon, 5 Jun 2023 11:23:43 +0100 Subject: [PATCH 34/44] Added comment to the integration test for validating taskdefinition Signed-off-by: geoffrey1330 --- test/integration/validate-taskdefinition/badtaskdefinition.yaml | 2 -- 1 file changed, 2 deletions(-) diff --git a/test/integration/validate-taskdefinition/badtaskdefinition.yaml b/test/integration/validate-taskdefinition/badtaskdefinition.yaml index 70f8fe407d..3ddb285e7a 100644 --- a/test/integration/validate-taskdefinition/badtaskdefinition.yaml +++ b/test/integration/validate-taskdefinition/badtaskdefinition.yaml @@ -18,7 +18,6 @@ spec: volumeMounts: - mountPath: /cache name: logger - --- # This TaskDefinition will not be accepted by the validation webhook as it doesn't contain either containerSpec or functionSpec apiVersion: lifecycle.keptn.sh/v1alpha3 @@ -26,4 +25,3 @@ kind: KeptnTaskDefinition metadata: name: badtaskdefinition2 spec: - From 682151d88a88b9aa4af222db78ea4cc177acbec2 Mon Sep 17 00:00:00 2001 From: geoffrey1330 Date: Mon, 5 Jun 2023 12:40:28 +0100 Subject: [PATCH 35/44] Added tests to cover the Validate[Create/Update/Delete]() methods Signed-off-by: geoffrey1330 --- .../keptntaskdefinition_webhook_test.go | 49 +++++++++++++++++-- 1 file changed, 44 insertions(+), 5 deletions(-) diff --git a/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook_test.go b/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook_test.go index 540d10a025..d18034dcea 100644 --- a/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook_test.go +++ b/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook_test.go @@ -6,14 +6,17 @@ import ( "github.com/pkg/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/util/validation/field" ) func TestKeptnTaskDefinition_ValidateFields(t *testing.T) { tests := []struct { - name string - spec KeptnTaskDefinitionSpec - want *field.Error + name string + spec KeptnTaskDefinitionSpec + want *field.Error + verb string + oldSpec runtime.Object }{ { name: "with-no-function-or-container", @@ -23,6 +26,7 @@ func TestKeptnTaskDefinition_ValidateFields(t *testing.T) { KeptnTaskDefinitionSpec{}, errors.New("Forbidden! Either Function or Container field must be defined").Error(), ), + verb: "create", }, { name: "with-both-function-and-container", @@ -38,18 +42,42 @@ func TestKeptnTaskDefinition_ValidateFields(t *testing.T) { }, errors.New("Forbidden! Both Function and Container fields cannot be defined simultaneously").Error(), ), + verb: "create", }, { name: "with-function-only", spec: KeptnTaskDefinitionSpec{ Function: &FunctionSpec{}, }, + verb: "create", }, { name: "with-container-only", spec: KeptnTaskDefinitionSpec{ Container: &ContainerSpec{}, }, + verb: "create", + }, + { + name: "update-with-both-function-and-container", + spec: KeptnTaskDefinitionSpec{ + Function: &FunctionSpec{}, + Container: &ContainerSpec{}, + }, + want: field.Invalid( + field.NewPath("spec"), + KeptnTaskDefinitionSpec{ + Function: &FunctionSpec{}, + Container: &ContainerSpec{}, + }, + errors.New("Forbidden! Both Function and Container fields cannot be defined simultaneously").Error(), + ), + verb: "update", + oldSpec: &KeptnTaskDefinitionSpec{Function: &FunctionSpec{}}, + }, + { + name: "delete", + verb: "delete", }, } @@ -59,8 +87,19 @@ func TestKeptnTaskDefinition_ValidateFields(t *testing.T) { ObjectMeta: metav1.ObjectMeta{Name: tt.name}, Spec: tt.spec, } - if got := ktd.validateFields(); !reflect.DeepEqual(got, tt.want) { - t.Errorf("validateFields() = %v, want %v", got, tt.want) + + var got *field.Error + switch tt.verb { + case "create": + got = ktd.ValidateCreate() + case "update": + got = ktd.ValidateUpdate(tt.oldSpec) + case "delete": + got = ktd.ValidateDelete() + } + + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("Validation failed. Got error:\n%v\nExpected error:\n%v", got, tt.want) } }) } From eb83821989e49747e0a6d54fbaeeb0daf684a1b4 Mon Sep 17 00:00:00 2001 From: geoffrey1330 Date: Mon, 5 Jun 2023 13:32:19 +0100 Subject: [PATCH 36/44] Added tests to cover the Validate[Create/Update/Delete]() methods Signed-off-by: geoffrey1330 --- .../keptntaskdefinition_webhook_test.go | 49 ++----------------- 1 file changed, 5 insertions(+), 44 deletions(-) diff --git a/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook_test.go b/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook_test.go index d18034dcea..540d10a025 100644 --- a/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook_test.go +++ b/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook_test.go @@ -6,17 +6,14 @@ import ( "github.com/pkg/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/util/validation/field" ) func TestKeptnTaskDefinition_ValidateFields(t *testing.T) { tests := []struct { - name string - spec KeptnTaskDefinitionSpec - want *field.Error - verb string - oldSpec runtime.Object + name string + spec KeptnTaskDefinitionSpec + want *field.Error }{ { name: "with-no-function-or-container", @@ -26,7 +23,6 @@ func TestKeptnTaskDefinition_ValidateFields(t *testing.T) { KeptnTaskDefinitionSpec{}, errors.New("Forbidden! Either Function or Container field must be defined").Error(), ), - verb: "create", }, { name: "with-both-function-and-container", @@ -42,42 +38,18 @@ func TestKeptnTaskDefinition_ValidateFields(t *testing.T) { }, errors.New("Forbidden! Both Function and Container fields cannot be defined simultaneously").Error(), ), - verb: "create", }, { name: "with-function-only", spec: KeptnTaskDefinitionSpec{ Function: &FunctionSpec{}, }, - verb: "create", }, { name: "with-container-only", spec: KeptnTaskDefinitionSpec{ Container: &ContainerSpec{}, }, - verb: "create", - }, - { - name: "update-with-both-function-and-container", - spec: KeptnTaskDefinitionSpec{ - Function: &FunctionSpec{}, - Container: &ContainerSpec{}, - }, - want: field.Invalid( - field.NewPath("spec"), - KeptnTaskDefinitionSpec{ - Function: &FunctionSpec{}, - Container: &ContainerSpec{}, - }, - errors.New("Forbidden! Both Function and Container fields cannot be defined simultaneously").Error(), - ), - verb: "update", - oldSpec: &KeptnTaskDefinitionSpec{Function: &FunctionSpec{}}, - }, - { - name: "delete", - verb: "delete", }, } @@ -87,19 +59,8 @@ func TestKeptnTaskDefinition_ValidateFields(t *testing.T) { ObjectMeta: metav1.ObjectMeta{Name: tt.name}, Spec: tt.spec, } - - var got *field.Error - switch tt.verb { - case "create": - got = ktd.ValidateCreate() - case "update": - got = ktd.ValidateUpdate(tt.oldSpec) - case "delete": - got = ktd.ValidateDelete() - } - - if !reflect.DeepEqual(got, tt.want) { - t.Errorf("Validation failed. Got error:\n%v\nExpected error:\n%v", got, tt.want) + if got := ktd.validateFields(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("validateFields() = %v, want %v", got, tt.want) } }) } From f3cf46a2588226c6d6418c8a404db6b64aafb84b Mon Sep 17 00:00:00 2001 From: geoffrey1330 Date: Mon, 5 Jun 2023 13:37:50 +0100 Subject: [PATCH 37/44] Added tests to cover the Validate[Create/Update/Delete]() methods Signed-off-by: geoffrey1330 --- .../keptntaskdefinition_webhook_test.go | 39 ++++++++++++++++--- 1 file changed, 34 insertions(+), 5 deletions(-) diff --git a/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook_test.go b/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook_test.go index 540d10a025..3d72565e76 100644 --- a/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook_test.go +++ b/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook_test.go @@ -6,14 +6,17 @@ import ( "github.com/pkg/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/util/validation/field" ) func TestKeptnTaskDefinition_ValidateFields(t *testing.T) { tests := []struct { - name string - spec KeptnTaskDefinitionSpec - want *field.Error + name string + spec KeptnTaskDefinitionSpec + want *field.Error + verb string + oldSpec runtime.Object }{ { name: "with-no-function-or-container", @@ -23,6 +26,7 @@ func TestKeptnTaskDefinition_ValidateFields(t *testing.T) { KeptnTaskDefinitionSpec{}, errors.New("Forbidden! Either Function or Container field must be defined").Error(), ), + verb: "create", }, { name: "with-both-function-and-container", @@ -38,18 +42,32 @@ func TestKeptnTaskDefinition_ValidateFields(t *testing.T) { }, errors.New("Forbidden! Both Function and Container fields cannot be defined simultaneously").Error(), ), + verb: "create", }, { name: "with-function-only", spec: KeptnTaskDefinitionSpec{ Function: &FunctionSpec{}, }, + verb: "create", }, { name: "with-container-only", spec: KeptnTaskDefinitionSpec{ Container: &ContainerSpec{}, }, + verb: "create", + }, + { + name: "update-with-both-function-and-container", + spec: KeptnTaskDefinitionSpec{Function: &FunctionSpec{}}, + want: field.Invalid(field.NewPath("spec"), KeptnTaskDefinitionSpec{Function: &FunctionSpec{}}, errors.New("Forbidden! Both Function and Container fields cannot be defined simultaneously").Error()), + verb: "update", + oldSpec: &KeptnTaskDefinitionSpec{Function: &FunctionSpec{}}, + }, + { + name: "delete", + verb: "delete", }, } @@ -59,8 +77,19 @@ func TestKeptnTaskDefinition_ValidateFields(t *testing.T) { ObjectMeta: metav1.ObjectMeta{Name: tt.name}, Spec: tt.spec, } - if got := ktd.validateFields(); !reflect.DeepEqual(got, tt.want) { - t.Errorf("validateFields() = %v, want %v", got, tt.want) + + var got *field.Error + switch tt.verb { + case "create": + got = ktd.ValidateCreate() + case "update": + got = ktd.ValidateUpdate(tt.oldSpec) + case "delete": + got = ktd.ValidateDelete() + } + + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("Validation failed. Got error:\n%v\nExpected error:\n%v", got, tt.want) } }) } From 7480936a65c49b7e00e3a13ffdd8c313de231990 Mon Sep 17 00:00:00 2001 From: geoffrey1330 Date: Mon, 5 Jun 2023 15:05:23 +0100 Subject: [PATCH 38/44] Added tests to cover the Validate[Create/Update/Delete]() methods Signed-off-by: geoffrey1330 --- .../v1alpha3/keptntaskdefinition_webhook.go | 6 ++--- .../keptntaskdefinition_webhook_test.go | 26 ++++++++++++------- 2 files changed, 20 insertions(+), 12 deletions(-) diff --git a/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook.go b/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook.go index d06601747c..93fcbab267 100644 --- a/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook.go +++ b/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook.go @@ -44,14 +44,14 @@ var _ webhook.Validator = &KeptnTaskDefinition{} func (r *KeptnTaskDefinition) ValidateCreate() error { keptntaskdefinitionlog.Info("validate create", "name", r.Name) - return r.validateKeptnTaskDefinition() + return r.validateKeptnTaskDefination() } // ValidateUpdate implements webhook.Validator so a webhook will be registered for the type func (r *KeptnTaskDefinition) ValidateUpdate(old runtime.Object) error { keptntaskdefinitionlog.Info("validate update", "name", r.Name) - return r.validateKeptnTaskDefinition() + return r.validateKeptnTaskDefination() } // ValidateDelete implements webhook.Validator so a webhook will be registered for the type @@ -61,7 +61,7 @@ func (r *KeptnTaskDefinition) ValidateDelete() error { return nil } -func (r *KeptnTaskDefinition) validateKeptnTaskDefinition() error { +func (r *KeptnTaskDefinition) validateKeptnTaskDefination() error { var allErrs field.ErrorList //defined as a list to allow returning multiple validation errors var err *field.Error if err = r.validateFields(); err != nil { diff --git a/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook_test.go b/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook_test.go index 3d72565e76..f7dd4c057a 100644 --- a/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook_test.go +++ b/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook_test.go @@ -59,11 +59,19 @@ func TestKeptnTaskDefinition_ValidateFields(t *testing.T) { verb: "create", }, { - name: "update-with-both-function-and-container", - spec: KeptnTaskDefinitionSpec{Function: &FunctionSpec{}}, - want: field.Invalid(field.NewPath("spec"), KeptnTaskDefinitionSpec{Function: &FunctionSpec{}}, errors.New("Forbidden! Both Function and Container fields cannot be defined simultaneously").Error()), - verb: "update", - oldSpec: &KeptnTaskDefinitionSpec{Function: &FunctionSpec{}}, + name: "update-with-both-function-and-container", + spec: KeptnTaskDefinitionSpec{ + Function: &FunctionSpec{}, + }, + want: field.Invalid( + field.NewPath("spec"), + KeptnTaskDefinitionSpec{Function: &FunctionSpec{}}, + errors.New("Forbidden! Both Function and Container fields cannot be defined simultaneously").Error()), + oldSpec: &KeptnTaskDefinitionSpec{ + Function: &FunctionSpec{}, + }, + + verb: "update", }, { name: "delete", @@ -78,18 +86,18 @@ func TestKeptnTaskDefinition_ValidateFields(t *testing.T) { Spec: tt.spec, } - var got *field.Error + var got error switch tt.verb { case "create": got = ktd.ValidateCreate() - case "update": - got = ktd.ValidateUpdate(tt.oldSpec) + // case "update": + // got = ktd.ValidateUpdate(runtime.Object) case "delete": got = ktd.ValidateDelete() } if !reflect.DeepEqual(got, tt.want) { - t.Errorf("Validation failed. Got error:\n%v\nExpected error:\n%v", got, tt.want) + t.Errorf("validateFields() = %v, want %v", got, tt.want) } }) } From 2cc657aedc226948a83da401c7a2eb822420dcc2 Mon Sep 17 00:00:00 2001 From: geoffrey1330 Date: Mon, 5 Jun 2023 15:23:00 +0100 Subject: [PATCH 39/44] Added tests to cover the Validate[Create/Update/Delete]() methods Signed-off-by: geoffrey1330 --- .../lifecycle/v1alpha3/keptntaskdefinition_webhook_test.go | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook_test.go b/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook_test.go index f7dd4c057a..90eb283b77 100644 --- a/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook_test.go +++ b/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook_test.go @@ -70,7 +70,6 @@ func TestKeptnTaskDefinition_ValidateFields(t *testing.T) { oldSpec: &KeptnTaskDefinitionSpec{ Function: &FunctionSpec{}, }, - verb: "update", }, { @@ -90,8 +89,8 @@ func TestKeptnTaskDefinition_ValidateFields(t *testing.T) { switch tt.verb { case "create": got = ktd.ValidateCreate() - // case "update": - // got = ktd.ValidateUpdate(runtime.Object) + case "update": + got = ktd.ValidateUpdate(tt.oldSpec) case "delete": got = ktd.ValidateDelete() } From 1605588019cf0aa48024433cf250f2ceea417e00 Mon Sep 17 00:00:00 2001 From: geoffrey1330 Date: Mon, 5 Jun 2023 16:11:40 +0100 Subject: [PATCH 40/44] Added tests to cover the Validate[Create/Update/Delete]() methods Signed-off-by: geoffrey1330 --- .../apis/lifecycle/v1alpha3/keptntaskdefinition_webhook_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook_test.go b/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook_test.go index 90eb283b77..275f7bafed 100644 --- a/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook_test.go +++ b/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook_test.go @@ -67,7 +67,7 @@ func TestKeptnTaskDefinition_ValidateFields(t *testing.T) { field.NewPath("spec"), KeptnTaskDefinitionSpec{Function: &FunctionSpec{}}, errors.New("Forbidden! Both Function and Container fields cannot be defined simultaneously").Error()), - oldSpec: &KeptnTaskDefinitionSpec{ + oldSpec: KeptnTaskDefinitionSpec{ Function: &FunctionSpec{}, }, verb: "update", From 8de7acf2e487cbe151202f902b49c52a0ca90e9f Mon Sep 17 00:00:00 2001 From: geoffrey1330 Date: Mon, 5 Jun 2023 16:31:30 +0100 Subject: [PATCH 41/44] Added tests to cover the Validate[Create/Update/Delete]() methods Signed-off-by: geoffrey1330 --- .../apis/lifecycle/v1alpha3/keptntaskdefinition_webhook.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook.go b/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook.go index 93fcbab267..d06601747c 100644 --- a/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook.go +++ b/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook.go @@ -44,14 +44,14 @@ var _ webhook.Validator = &KeptnTaskDefinition{} func (r *KeptnTaskDefinition) ValidateCreate() error { keptntaskdefinitionlog.Info("validate create", "name", r.Name) - return r.validateKeptnTaskDefination() + return r.validateKeptnTaskDefinition() } // ValidateUpdate implements webhook.Validator so a webhook will be registered for the type func (r *KeptnTaskDefinition) ValidateUpdate(old runtime.Object) error { keptntaskdefinitionlog.Info("validate update", "name", r.Name) - return r.validateKeptnTaskDefination() + return r.validateKeptnTaskDefinition() } // ValidateDelete implements webhook.Validator so a webhook will be registered for the type @@ -61,7 +61,7 @@ func (r *KeptnTaskDefinition) ValidateDelete() error { return nil } -func (r *KeptnTaskDefinition) validateKeptnTaskDefination() error { +func (r *KeptnTaskDefinition) validateKeptnTaskDefinition() error { var allErrs field.ErrorList //defined as a list to allow returning multiple validation errors var err *field.Error if err = r.validateFields(); err != nil { From 9b464d842115d691495b625e6b6187939a2716d4 Mon Sep 17 00:00:00 2001 From: geoffrey1330 Date: Mon, 5 Jun 2023 17:49:05 +0100 Subject: [PATCH 42/44] Added tests to cover the Validate[Create/Update/Delete]() methods Signed-off-by: geoffrey1330 --- .../v1alpha3/keptntaskdefinition_webhook_test.go | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook_test.go b/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook_test.go index 275f7bafed..8e34bc9d8c 100644 --- a/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook_test.go +++ b/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook_test.go @@ -1,10 +1,10 @@ package v1alpha3 import ( - "reflect" "testing" "github.com/pkg/errors" + "github.com/stretchr/testify/require" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/util/validation/field" @@ -67,8 +67,8 @@ func TestKeptnTaskDefinition_ValidateFields(t *testing.T) { field.NewPath("spec"), KeptnTaskDefinitionSpec{Function: &FunctionSpec{}}, errors.New("Forbidden! Both Function and Container fields cannot be defined simultaneously").Error()), - oldSpec: KeptnTaskDefinitionSpec{ - Function: &FunctionSpec{}, + oldSpec: &KeptnTaskDefinition{ + Spec: KeptnTaskDefinitionSpec{}, }, verb: "update", }, @@ -85,7 +85,7 @@ func TestKeptnTaskDefinition_ValidateFields(t *testing.T) { Spec: tt.spec, } - var got error + got := ktd.validateKeptnTaskDefinition() switch tt.verb { case "create": got = ktd.ValidateCreate() @@ -95,8 +95,11 @@ func TestKeptnTaskDefinition_ValidateFields(t *testing.T) { got = ktd.ValidateDelete() } - if !reflect.DeepEqual(got, tt.want) { - t.Errorf("validateFields() = %v, want %v", got, tt.want) + if tt.want != nil { + require.NotNil(t, got) + require.Contains(t, got.Error(), tt.want.Error()) + } else { + require.Nil(t, got) } }) } From 330e3c4998e11b75ee12673e4ad6037beef1602c Mon Sep 17 00:00:00 2001 From: Geoffrey Israel Date: Tue, 6 Jun 2023 08:58:45 +0100 Subject: [PATCH 43/44] Update operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook_test.go Co-authored-by: Florian Bacher Signed-off-by: Geoffrey Israel --- .../keptntaskdefinition_webhook_test.go | 67 +++++++++++-------- 1 file changed, 40 insertions(+), 27 deletions(-) diff --git a/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook_test.go b/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook_test.go index 8e34bc9d8c..1d65021ca9 100644 --- a/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook_test.go +++ b/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook_test.go @@ -11,38 +11,48 @@ import ( ) func TestKeptnTaskDefinition_ValidateFields(t *testing.T) { + + specWithFunctionAndContainer := KeptnTaskDefinitionSpec{ + Function: &FunctionSpec{}, + Container: &ContainerSpec{}, + } + + emptySpec := KeptnTaskDefinitionSpec{} + tests := []struct { name string spec KeptnTaskDefinitionSpec - want *field.Error + want error verb string oldSpec runtime.Object }{ { name: "with-no-function-or-container", - spec: KeptnTaskDefinitionSpec{}, - want: field.Invalid( - field.NewPath("spec"), - KeptnTaskDefinitionSpec{}, - errors.New("Forbidden! Either Function or Container field must be defined").Error(), + spec: emptySpec, + want: apierrors.NewInvalid( + schema.GroupKind{Group: "lifecycle.keptn.sh", Kind: "KeptnTaskDefinition"}, + "with-no-function-or-container", + []*field.Error{field.Invalid( + field.NewPath("spec"), + emptySpec, + errors.New("Forbidden! Either Function or Container field must be defined").Error(), + )}, ), verb: "create", }, { name: "with-both-function-and-container", - spec: KeptnTaskDefinitionSpec{ - Function: &FunctionSpec{}, - Container: &ContainerSpec{}, - }, - want: field.Invalid( - field.NewPath("spec"), - KeptnTaskDefinitionSpec{ - Function: &FunctionSpec{}, - Container: &ContainerSpec{}, - }, - errors.New("Forbidden! Both Function and Container fields cannot be defined simultaneously").Error(), - ), + spec: specWithFunctionAndContainer, verb: "create", + want: apierrors.NewInvalid( + schema.GroupKind{Group: "lifecycle.keptn.sh", Kind: "KeptnTaskDefinition"}, + "with-both-function-and-container", + []*field.Error{field.Invalid( + field.NewPath("spec"), + specWithFunctionAndContainer, + errors.New("Forbidden! Both Function and Container fields cannot be defined simultaneously").Error(), + )}, + ), }, { name: "with-function-only", @@ -60,13 +70,16 @@ func TestKeptnTaskDefinition_ValidateFields(t *testing.T) { }, { name: "update-with-both-function-and-container", - spec: KeptnTaskDefinitionSpec{ - Function: &FunctionSpec{}, - }, - want: field.Invalid( - field.NewPath("spec"), - KeptnTaskDefinitionSpec{Function: &FunctionSpec{}}, - errors.New("Forbidden! Both Function and Container fields cannot be defined simultaneously").Error()), + spec: specWithFunctionAndContainer, + want: apierrors.NewInvalid( + schema.GroupKind{Group: "lifecycle.keptn.sh", Kind: "KeptnTaskDefinition"}, + "update-with-both-function-and-container", + []*field.Error{field.Invalid( + field.NewPath("spec"), + specWithFunctionAndContainer, + errors.New("Forbidden! Both Function and Container fields cannot be defined simultaneously").Error(), + )}, + ), oldSpec: &KeptnTaskDefinition{ Spec: KeptnTaskDefinitionSpec{}, }, @@ -85,7 +98,7 @@ func TestKeptnTaskDefinition_ValidateFields(t *testing.T) { Spec: tt.spec, } - got := ktd.validateKeptnTaskDefinition() + var got error switch tt.verb { case "create": got = ktd.ValidateCreate() @@ -97,7 +110,7 @@ func TestKeptnTaskDefinition_ValidateFields(t *testing.T) { if tt.want != nil { require.NotNil(t, got) - require.Contains(t, got.Error(), tt.want.Error()) + require.EqualValues(t, tt.want, got) } else { require.Nil(t, got) } From 0d9daea16d5c7c241a2c67f95645749930be1a36 Mon Sep 17 00:00:00 2001 From: geoffrey1330 Date: Tue, 6 Jun 2023 09:08:29 +0100 Subject: [PATCH 44/44] Added fixes for tests that covers the Validate[Create/Update/Delete]() methods Signed-off-by: geoffrey1330 --- .../apis/lifecycle/v1alpha3/keptntaskdefinition_webhook_test.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook_test.go b/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook_test.go index 1d65021ca9..efd372c307 100644 --- a/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook_test.go +++ b/operator/apis/lifecycle/v1alpha3/keptntaskdefinition_webhook_test.go @@ -5,8 +5,10 @@ import ( "github.com/pkg/errors" "github.com/stretchr/testify/require" + apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/util/validation/field" )