Skip to content

Commit

Permalink
Move docker infrastructure API v1beta1 webhooks to separate package
Browse files Browse the repository at this point in the history
  • Loading branch information
Ankitasw committed Sep 19, 2023
1 parent 66d18d9 commit a0ec023
Show file tree
Hide file tree
Showing 10 changed files with 211 additions and 76 deletions.
4 changes: 3 additions & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -334,13 +334,15 @@ generate-manifests-kubeadm-control-plane: $(CONTROLLER_GEN) ## Generate manifest

.PHONY: generate-manifests-docker-infrastructure
generate-manifests-docker-infrastructure: $(CONTROLLER_GEN) ## Generate manifests e.g. CRD, RBAC etc. for docker infrastructure provider
$(MAKE) clean-generated-yaml SRC_DIRS="$(CAPD_DIR)/config/crd/bases"
$(MAKE) clean-generated-yaml SRC_DIRS="$(CAPD_DIR)/config/crd/bases,$(CAPD_DIR)/config/webhook/manifests.yaml"
cd $(CAPD_DIR); $(CONTROLLER_GEN) \
paths=./ \
paths=./api/... \
paths=./$(EXP_DIR)/api/... \
paths=./$(EXP_DIR)/internal/controllers/... \
paths=./$(EXP_DIR)/internal/webhooks/... \
paths=./internal/controllers/... \
paths=./internal/webhooks/... \
crd:crdVersions=v1 \
rbac:roleName=manager-role \
output:crd:dir=./config/crd/bases \
Expand Down
18 changes: 18 additions & 0 deletions test/infrastructure/docker/internal/webhooks/doc.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
/*
Copyright 2023 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

// Package webhooks implements docker infrastructure webhooks.
package webhooks
Original file line number Diff line number Diff line change
Expand Up @@ -14,60 +14,79 @@ See the License for the specific language governing permissions and
limitations under the License.
*/

package v1beta1
package webhooks

import (
"context"
"fmt"

apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/util/validation/field"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/webhook"
"sigs.k8s.io/controller-runtime/pkg/webhook/admission"

infrav1 "sigs.k8s.io/cluster-api/test/infrastructure/docker/api/v1beta1"
)

func (c *DockerCluster) SetupWebhookWithManager(mgr ctrl.Manager) error {
// DockerCluster implements a validating and defaulting webhook for DockerCluster.
type DockerCluster struct{}

func (webhook *DockerCluster) SetupWebhookWithManager(mgr ctrl.Manager) error {
return ctrl.NewWebhookManagedBy(mgr).
For(c).
For(&infrav1.DockerCluster{}).
WithDefaulter(webhook).
WithValidator(webhook).
Complete()
}

// +kubebuilder:webhook:verbs=create;update,path=/mutate-infrastructure-cluster-x-k8s-io-v1beta1-dockercluster,mutating=true,failurePolicy=fail,matchPolicy=Equivalent,groups=infrastructure.cluster.x-k8s.io,resources=dockerclusters,versions=v1beta1,name=default.dockercluster.infrastructure.cluster.x-k8s.io,sideEffects=None,admissionReviewVersions=v1;v1beta1

var _ webhook.Defaulter = &DockerCluster{}
var _ webhook.CustomDefaulter = &DockerCluster{}

// Default implements webhook.Defaulter so a webhook will be registered for the type.
func (c *DockerCluster) Default() {
defaultDockerClusterSpec(&c.Spec)
func (webhook *DockerCluster) Default(_ context.Context, obj runtime.Object) error {
cluster, ok := obj.(*infrav1.DockerCluster)
if !ok {
return apierrors.NewBadRequest(fmt.Sprintf("expected a DockerCluster but got a %T", obj))
}
defaultDockerClusterSpec(&cluster.Spec)
return nil
}

// +kubebuilder:webhook:verbs=create;update,path=/validate-infrastructure-cluster-x-k8s-io-v1beta1-dockercluster,mutating=false,failurePolicy=fail,matchPolicy=Equivalent,groups=infrastructure.cluster.x-k8s.io,resources=dockerclusters,versions=v1beta1,name=validation.dockercluster.infrastructure.cluster.x-k8s.io,sideEffects=None,admissionReviewVersions=v1;v1beta1

var _ webhook.Validator = &DockerCluster{}
var _ webhook.CustomValidator = &DockerCluster{}

// ValidateCreate implements webhook.Validator so a webhook will be registered for the type.
func (c *DockerCluster) ValidateCreate() (admission.Warnings, error) {
if allErrs := validateDockerClusterSpec(c.Spec); len(allErrs) > 0 {
return nil, apierrors.NewInvalid(GroupVersion.WithKind("DockerCluster").GroupKind(), c.Name, allErrs)
func (webhook *DockerCluster) ValidateCreate(_ context.Context, obj runtime.Object) (admission.Warnings, error) {
cluster, ok := obj.(*infrav1.DockerCluster)
if !ok {
return nil, apierrors.NewBadRequest(fmt.Sprintf("expected a DockerCluster but got a %T", obj))
}
if allErrs := validateDockerClusterSpec(cluster.Spec); len(allErrs) > 0 {
return nil, apierrors.NewInvalid(infrav1.GroupVersion.WithKind("DockerCluster").GroupKind(), cluster.Name, allErrs)
}
return nil, nil
}

// ValidateUpdate implements webhook.Validator so a webhook will be registered for the type.
func (c *DockerCluster) ValidateUpdate(_ runtime.Object) (admission.Warnings, error) {
func (webhook *DockerCluster) ValidateUpdate(_ context.Context, _, _ runtime.Object) (admission.Warnings, error) {
return nil, nil
}

// ValidateDelete implements webhook.Validator so a webhook will be registered for the type.
func (c *DockerCluster) ValidateDelete() (admission.Warnings, error) {
func (webhook *DockerCluster) ValidateDelete(_ context.Context, _ runtime.Object) (admission.Warnings, error) {
return nil, nil
}

func defaultDockerClusterSpec(s *DockerClusterSpec) {
func defaultDockerClusterSpec(s *infrav1.DockerClusterSpec) {
if s.ControlPlaneEndpoint.Port == 0 {
s.ControlPlaneEndpoint.Port = 6443
}
}

func validateDockerClusterSpec(_ DockerClusterSpec) field.ErrorList {
func validateDockerClusterSpec(_ infrav1.DockerClusterSpec) field.ErrorList {
return nil
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,10 @@ See the License for the specific language governing permissions and
limitations under the License.
*/

package v1beta1
package webhooks

import (
"context"
"fmt"
"reflect"

Expand All @@ -28,31 +29,42 @@ import (
"sigs.k8s.io/controller-runtime/pkg/webhook/admission"

"sigs.k8s.io/cluster-api/feature"
infrav1 "sigs.k8s.io/cluster-api/test/infrastructure/docker/api/v1beta1"
)

const dockerClusterTemplateImmutableMsg = "DockerClusterTemplate spec.template.spec field is immutable. Please create a new resource instead."

func (r *DockerClusterTemplate) SetupWebhookWithManager(mgr ctrl.Manager) error {
// DockerClusterTemplate implements a validating and defaulting webhook for DockerClusterTemplate.
type DockerClusterTemplate struct{}

func (webhook *DockerClusterTemplate) SetupWebhookWithManager(mgr ctrl.Manager) error {
return ctrl.NewWebhookManagedBy(mgr).
For(r).
For(&infrav1.DockerClusterTemplate{}).
WithDefaulter(webhook).
WithValidator(webhook).
Complete()
}

// +kubebuilder:webhook:verbs=create;update,path=/mutate-infrastructure-cluster-x-k8s-io-v1beta1-dockerclustertemplate,mutating=true,failurePolicy=fail,matchPolicy=Equivalent,groups=infrastructure.cluster.x-k8s.io,resources=dockerclustertemplates,versions=v1beta1,name=default.dockerclustertemplate.infrastructure.cluster.x-k8s.io,sideEffects=None,admissionReviewVersions=v1;v1beta1

var _ webhook.Defaulter = &DockerClusterTemplate{}
var _ webhook.CustomDefaulter = &DockerClusterTemplate{}

// Default implements webhook.Defaulter so a webhook will be registered for the type.
func (r *DockerClusterTemplate) Default() {
defaultDockerClusterSpec(&r.Spec.Template.Spec)
func (webhook *DockerClusterTemplate) Default(_ context.Context, obj runtime.Object) error {
clusterTemplate, ok := obj.(*infrav1.DockerClusterTemplate)
if !ok {
return apierrors.NewBadRequest(fmt.Sprintf("expected a DockerClusterTemplate but got a %T", obj))
}
defaultDockerClusterSpec(&clusterTemplate.Spec.Template.Spec)
return nil
}

// +kubebuilder:webhook:verbs=create;update,path=/validate-infrastructure-cluster-x-k8s-io-v1beta1-dockerclustertemplate,mutating=false,failurePolicy=fail,matchPolicy=Equivalent,groups=infrastructure.cluster.x-k8s.io,resources=dockerclustertemplates,versions=v1beta1,name=validation.dockerclustertemplate.infrastructure.cluster.x-k8s.io,sideEffects=None,admissionReviewVersions=v1;v1beta1

var _ webhook.Validator = &DockerClusterTemplate{}
var _ webhook.CustomValidator = &DockerClusterTemplate{}

// ValidateCreate implements webhook.Validator so a webhook will be registered for the type.
func (r *DockerClusterTemplate) ValidateCreate() (admission.Warnings, error) {
func (webhook *DockerClusterTemplate) ValidateCreate(_ context.Context, obj runtime.Object) (admission.Warnings, error) {
// NOTE: DockerClusterTemplate is behind ClusterTopology feature gate flag; the web hook
// must prevent creating new objects in case the feature flag is disabled.
if !feature.Gates.Enabled(feature.ClusterTopology) {
Expand All @@ -62,34 +74,43 @@ func (r *DockerClusterTemplate) ValidateCreate() (admission.Warnings, error) {
)
}

allErrs := validateDockerClusterSpec(r.Spec.Template.Spec)
clusterTemplate, ok := obj.(*infrav1.DockerClusterTemplate)
if !ok {
return nil, apierrors.NewBadRequest(fmt.Sprintf("expected a DockerClusterTemplate but got a %T", obj))
}

allErrs := validateDockerClusterSpec(clusterTemplate.Spec.Template.Spec)

// Validate the metadata of the template.
allErrs = append(allErrs, r.Spec.Template.ObjectMeta.Validate(field.NewPath("spec", "template", "metadata"))...)
allErrs = append(allErrs, clusterTemplate.Spec.Template.ObjectMeta.Validate(field.NewPath("spec", "template", "metadata"))...)

if len(allErrs) > 0 {
return nil, apierrors.NewInvalid(GroupVersion.WithKind("DockerClusterTemplate").GroupKind(), r.Name, allErrs)
return nil, apierrors.NewInvalid(infrav1.GroupVersion.WithKind("DockerClusterTemplate").GroupKind(), clusterTemplate.Name, allErrs)
}
return nil, nil
}

// ValidateUpdate implements webhook.Validator so a webhook will be registered for the type.
func (r *DockerClusterTemplate) ValidateUpdate(oldRaw runtime.Object) (admission.Warnings, error) {
func (webhook *DockerClusterTemplate) ValidateUpdate(_ context.Context, oldRaw, newRaw runtime.Object) (admission.Warnings, error) {
var allErrs field.ErrorList
old, ok := oldRaw.(*DockerClusterTemplate)
oldTemplate, ok := oldRaw.(*infrav1.DockerClusterTemplate)
if !ok {
return nil, apierrors.NewBadRequest(fmt.Sprintf("expected a DockerClusterTemplate but got a %T", oldRaw))
}
if !reflect.DeepEqual(r.Spec.Template.Spec, old.Spec.Template.Spec) {
allErrs = append(allErrs, field.Invalid(field.NewPath("spec", "template", "spec"), r, dockerClusterTemplateImmutableMsg))
newTemplate, ok := newRaw.(*infrav1.DockerClusterTemplate)
if !ok {
return nil, apierrors.NewBadRequest(fmt.Sprintf("expected a DockerClusterTemplate but got a %T", newRaw))
}
if !reflect.DeepEqual(newTemplate.Spec.Template.Spec, oldTemplate.Spec.Template.Spec) {
allErrs = append(allErrs, field.Invalid(field.NewPath("spec", "template", "spec"), newTemplate, dockerClusterTemplateImmutableMsg))
}
if len(allErrs) == 0 {
return nil, nil
}
return nil, apierrors.NewInvalid(GroupVersion.WithKind("DockerClusterTemplate").GroupKind(), r.Name, allErrs)
return nil, apierrors.NewInvalid(infrav1.GroupVersion.WithKind("DockerClusterTemplate").GroupKind(), newTemplate.Name, allErrs)
}

// ValidateDelete implements webhook.Validator so a webhook will be registered for the type.
func (r *DockerClusterTemplate) ValidateDelete() (admission.Warnings, error) {
func (webhook *DockerClusterTemplate) ValidateDelete(_ context.Context, _ runtime.Object) (admission.Warnings, error) {
return nil, nil
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and
limitations under the License.
*/

package v1beta1
package webhooks

import (
"strings"
Expand All @@ -23,28 +23,33 @@ import (
. "github.com/onsi/gomega"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
utilfeature "k8s.io/component-base/featuregate/testing"
ctrl "sigs.k8s.io/controller-runtime"

clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1"
"sigs.k8s.io/cluster-api/feature"
infrav1 "sigs.k8s.io/cluster-api/test/infrastructure/docker/api/v1beta1"
)

var ctx = ctrl.SetupSignalHandler()

func TestDockerClusterTemplateValidationFeatureGateEnabled(t *testing.T) {
defer utilfeature.SetFeatureGateDuringTest(t, feature.Gates, feature.ClusterTopology, true)()

t.Run("create dockerclustertemplate should pass if gate enabled and valid dockerclustertemplate", func(t *testing.T) {
g := NewWithT(t)
dct := &DockerClusterTemplate{
dct := &infrav1.DockerClusterTemplate{
ObjectMeta: metav1.ObjectMeta{
Name: "dockerclustertemplate-test",
Namespace: "test-namespace",
},
Spec: DockerClusterTemplateSpec{
Template: DockerClusterTemplateResource{
Spec: DockerClusterSpec{},
Spec: infrav1.DockerClusterTemplateSpec{
Template: infrav1.DockerClusterTemplateResource{
Spec: infrav1.DockerClusterSpec{},
},
},
}
warnings, err := dct.ValidateCreate()
webhook := DockerClusterTemplate{}
warnings, err := webhook.ValidateCreate(ctx, dct)
g.Expect(err).ToNot(HaveOccurred())
g.Expect(warnings).To(BeEmpty())
})
Expand All @@ -54,18 +59,19 @@ func TestDockerClusterTemplateValidationFeatureGateDisabled(t *testing.T) {
// NOTE: ClusterTopology feature flag is disabled by default, thus preventing to create DockerClusterTemplate.
t.Run("create dockerclustertemplate should not pass if gate disabled and valid dockerclustertemplate", func(t *testing.T) {
g := NewWithT(t)
dct := &DockerClusterTemplate{
dct := &infrav1.DockerClusterTemplate{
ObjectMeta: metav1.ObjectMeta{
Name: "dockerclustertemplate-test",
Namespace: "test-namespace",
},
Spec: DockerClusterTemplateSpec{
Template: DockerClusterTemplateResource{
Spec: DockerClusterSpec{},
Spec: infrav1.DockerClusterTemplateSpec{
Template: infrav1.DockerClusterTemplateResource{
Spec: infrav1.DockerClusterSpec{},
},
},
}
warnings, err := dct.ValidateCreate()
webhook := DockerClusterTemplate{}
warnings, err := webhook.ValidateCreate(ctx, dct)
g.Expect(err).To(HaveOccurred())
g.Expect(warnings).To(BeEmpty())
})
Expand Down Expand Up @@ -97,13 +103,13 @@ func TestDockerClusterTemplateValidationMetadata(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
g := NewWithT(t)
dct := &DockerClusterTemplate{
dct := &infrav1.DockerClusterTemplate{
ObjectMeta: metav1.ObjectMeta{
Name: "dockerclustertemplate-test",
Namespace: "test-namespace",
},
Spec: DockerClusterTemplateSpec{
Template: DockerClusterTemplateResource{
Spec: infrav1.DockerClusterTemplateSpec{
Template: infrav1.DockerClusterTemplateResource{
ObjectMeta: clusterv1.ObjectMeta{
Labels: map[string]string{
"foo": "$invalid-key",
Expand All @@ -114,11 +120,12 @@ func TestDockerClusterTemplateValidationMetadata(t *testing.T) {
"/invalid-key": "foo",
},
},
Spec: DockerClusterSpec{},
Spec: infrav1.DockerClusterSpec{},
},
},
}
warnings, err := dct.ValidateCreate()
webhook := DockerClusterTemplate{}
warnings, err := webhook.ValidateCreate(ctx, dct)
if tt.expectErr {
g.Expect(err).To(HaveOccurred())
g.Expect(warnings).To(BeEmpty())
Expand Down
Loading

0 comments on commit a0ec023

Please sign in to comment.