Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Define strategy to provide value for bundleLookupTag in Cluster Template #287

Merged
merged 20 commits into from
Jan 13, 2022
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions PROJECT
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,10 @@ resources:
kind: ByoCluster
path: github.com/vmware-tanzu/cluster-api-provider-bringyourownhost/apis/infrastructure/v1beta1
version: v1beta1
webhooks:
defaulting: true
huchen2021 marked this conversation as resolved.
Show resolved Hide resolved
validation: true
webhookVersion: v1
- api:
crdVersion: v1
namespaced: true
Expand Down
73 changes: 73 additions & 0 deletions apis/infrastructure/v1beta1/byocluster_webhook.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
// Copyright 2021 VMware, Inc. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0

package v1beta1

import (
"errors"

apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
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 byoclusterlog = logf.Log.WithName("byocluster-resource")

func (r *ByoCluster) SetupWebhookWithManager(mgr ctrl.Manager) error {
return ctrl.NewWebhookManagedBy(mgr).
For(r).
Complete()
}

// TODO(user): EDIT THIS FILE! THIS IS SCAFFOLDING FOR YOU TO OWN!
huchen2021 marked this conversation as resolved.
Show resolved Hide resolved

//+kubebuilder:webhook:path=/mutate-infrastructure-cluster-x-k8s-io-v1beta1-byocluster,mutating=true,failurePolicy=fail,sideEffects=None,groups=infrastructure.cluster.x-k8s.io,resources=byoclusters,verbs=create;update,versions=v1beta1,name=mbyocluster.kb.io,admissionReviewVersions=v1

var _ webhook.Defaulter = &ByoCluster{}

// Default implements webhook.Defaulter so a webhook will be registered for the type
// nolint: stylecheck
func (r *ByoCluster) Default() {
byoclusterlog.Info("default", "name", r.Name)
}
huchen2021 marked this conversation as resolved.
Show resolved Hide resolved

// TODO(user): change verbs to "verbs=create;update;delete" if you want to enable deletion validation.
//+kubebuilder:webhook:path=/validate-infrastructure-cluster-x-k8s-io-v1beta1-byocluster,mutating=false,failurePolicy=fail,sideEffects=None,groups=infrastructure.cluster.x-k8s.io,resources=byoclusters,verbs=create;update,versions=v1beta1,name=vbyocluster.kb.io,admissionReviewVersions=v1

var _ webhook.Validator = &ByoCluster{}

// ValidateCreate implements webhook.Validator so a webhook will be registered for the type
func (r *ByoCluster) ValidateCreate() error {
byoclusterlog.Info("validate create", "name", r.Name)
huchen2021 marked this conversation as resolved.
Show resolved Hide resolved
groupResource := schema.GroupResource{Group: "infrastructure.cluster.x-k8s.io", Resource: "byocluster"}

if r.Spec.BundleLookupTag == "" {
return apierrors.NewForbidden(groupResource, r.Name, errors.New("cannot create ByoCluster with Spec.BundleLookupTag"))
huchen2021 marked this conversation as resolved.
Show resolved Hide resolved
}

return nil
}

// ValidateUpdate implements webhook.Validator so a webhook will be registered for the type
func (r *ByoCluster) ValidateUpdate(old runtime.Object) error {
byoclusterlog.Info("validate update", "name", r.Name)
huchen2021 marked this conversation as resolved.
Show resolved Hide resolved

groupResource := schema.GroupResource{Group: "infrastructure.cluster.x-k8s.io", Resource: "byocluster"}

if r.Spec.BundleLookupTag == "" {
return apierrors.NewForbidden(groupResource, r.Name, errors.New("cannot create ByoCluster with empty Spec.BundleLookupTag"))
huchen2021 marked this conversation as resolved.
Show resolved Hide resolved
}
return nil
}

// ValidateDelete implements webhook.Validator so a webhook will be registered for the type
func (r *ByoCluster) ValidateDelete() error {
huchen2021 marked this conversation as resolved.
Show resolved Hide resolved
byoclusterlog.Info("validate delete", "name", r.Name)
huchen2021 marked this conversation as resolved.
Show resolved Hide resolved

// TODO(user): fill in your validation logic upon object deletion.
return nil
}
87 changes: 87 additions & 0 deletions apis/infrastructure/v1beta1/byocluster_webhook_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
// Copyright 2021 VMware, Inc. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0

package v1beta1

import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/kubectl/pkg/scheme"
clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1"
"sigs.k8s.io/controller-runtime/pkg/client"
)

var _ = Describe("ByoclusterWebhook", func() {
XContext("When ByoCluster gets a create request", func() {
huchen2021 marked this conversation as resolved.
Show resolved Hide resolved
var (
byoCluster *ByoCluster
)
BeforeEach(func() {
_, clientErr := client.New(cfg, client.Options{Scheme: scheme.Scheme})
Expect(clientErr).NotTo(HaveOccurred())

byoCluster = &ByoCluster{
TypeMeta: metav1.TypeMeta{
Kind: "ByoCluster",
APIVersion: clusterv1.GroupVersion.String(),
},
ObjectMeta: metav1.ObjectMeta{
Name: "byocluster-create",
Namespace: "default",
},
Spec: ByoClusterSpec{},
}
})

It("should reject the request when BundleLookupTag is empty", func() {
huchen2021 marked this conversation as resolved.
Show resolved Hide resolved
err := byoCluster.ValidateCreate()
huchen2021 marked this conversation as resolved.
Show resolved Hide resolved
Expect(err).To(HaveOccurred())
Expect(err).To(MatchError("cSpec.BundleLookupTag of ByoCluster is empty"))
})

})

XContext("When ByoCluster gets a update request", func() {
var (
oldbyoCluster *ByoCluster
newbyoCluster *ByoCluster
)
BeforeEach(func() {
_, clientErr := client.New(cfg, client.Options{Scheme: scheme.Scheme})
Expect(clientErr).NotTo(HaveOccurred())

oldbyoCluster = &ByoCluster{
TypeMeta: metav1.TypeMeta{
Kind: "ByoCluster",
APIVersion: clusterv1.GroupVersion.String(),
},
ObjectMeta: metav1.ObjectMeta{
Name: "byocluster-update",
Namespace: "default",
},
Spec: ByoClusterSpec{
BundleLookupTag: "v0.1.0_alpha.2",
},
}
newbyoCluster = &ByoCluster{
TypeMeta: metav1.TypeMeta{
Kind: "ByoCluster",
APIVersion: clusterv1.GroupVersion.String(),
},
ObjectMeta: metav1.ObjectMeta{
Name: "byocluster-update",
Namespace: "default",
},
Spec: ByoClusterSpec{},
}
})

It("should reject the request when BundleLookupTag is empty", func() {
err := newbyoCluster.ValidateUpdate(oldbyoCluster)
Expect(err).To(HaveOccurred())
Expect(err).To(MatchError("Spec.BundleLookupTag of ByoCluster is empty"))
})

})
})
6 changes: 6 additions & 0 deletions apis/infrastructure/v1beta1/webhook_suite_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,9 @@ var _ = BeforeSuite(func() {
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})
Expand All @@ -96,6 +99,9 @@ var _ = BeforeSuite(func() {
err = (&ByoHost{}).SetupWebhookWithManager(mgr)
Expect(err).NotTo(HaveOccurred())

err = (&ByoCluster{}).SetupWebhookWithManager(mgr)
Expect(err).NotTo(HaveOccurred())

//+kubebuilder:scaffold:webhook

go func() {
Expand Down
4 changes: 2 additions & 2 deletions config/crd/kustomization.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ patchesStrategicMerge:
#- patches/webhook_in_byomachines.yaml
- patches/webhook_in_byohosts.yaml
#- patches/webhook_in_byomachinetemplates.yaml
#- patches/webhook_in_byoclusters.yaml
- patches/webhook_in_byoclusters.yaml
#- patches/webhook_in_byohosts.yaml
#+kubebuilder:scaffold:crdkustomizewebhookpatch

Expand All @@ -27,7 +27,7 @@ patchesStrategicMerge:
#- patches/cainjection_in_byomachines.yaml
- patches/cainjection_in_byohosts.yaml
#- patches/cainjection_in_byomachinetemplates.yaml
#- patches/cainjection_in_byoclusters.yaml
- patches/cainjection_in_byoclusters.yaml
#- patches/cainjection_in_byohosts.yaml
#+kubebuilder:scaffold:crdkustomizecainjectionpatch

Expand Down
6 changes: 6 additions & 0 deletions config/default/webhookcainjection_patch.yaml
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
# 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:
name: mutating-webhook-configuration
annotations:
cert-manager.io/inject-ca-from: $(CERTIFICATE_NAMESPACE)/$(CERTIFICATE_NAME)
---
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingWebhookConfiguration
Expand Down
48 changes: 48 additions & 0 deletions config/webhook/manifests.yaml
Original file line number Diff line number Diff line change
@@ -1,11 +1,59 @@

---
apiVersion: admissionregistration.k8s.io/v1
kind: MutatingWebhookConfiguration
metadata:
creationTimestamp: null
name: mutating-webhook-configuration
webhooks:
- admissionReviewVersions:
- v1
clientConfig:
service:
name: webhook-service
namespace: system
path: /mutate-infrastructure-cluster-x-k8s-io-v1beta1-byocluster
failurePolicy: Fail
name: mbyocluster.kb.io
rules:
- apiGroups:
- infrastructure.cluster.x-k8s.io
apiVersions:
- v1beta1
operations:
- CREATE
- UPDATE
resources:
- byoclusters
sideEffects: None

---
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingWebhookConfiguration
metadata:
creationTimestamp: null
name: validating-webhook-configuration
webhooks:
- admissionReviewVersions:
- v1
clientConfig:
service:
name: webhook-service
namespace: system
path: /validate-infrastructure-cluster-x-k8s-io-v1beta1-byocluster
failurePolicy: Fail
name: vbyocluster.kb.io
rules:
- apiGroups:
- infrastructure.cluster.x-k8s.io
apiVersions:
- v1beta1
operations:
- CREATE
- UPDATE
resources:
- byoclusters
sideEffects: None
- admissionReviewVersions:
- v1
- v1beta1
Expand Down
4 changes: 4 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,10 @@ func main() {
setupLog.Error(err, "unable to create webhook", "webhook", "ByoHost")
os.Exit(1)
}
if err = (&infrastructurev1beta1.ByoCluster{}).SetupWebhookWithManager(mgr); err != nil {
setupLog.Error(err, "unable to create webhook", "webhook", "ByoCluster")
os.Exit(1)
}
//+kubebuilder:scaffold:builder

if err := mgr.AddHealthzCheck("healthz", healthz.Ping); err != nil {
Expand Down