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

Admission webhook #807

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all 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
5 changes: 5 additions & 0 deletions cmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,11 @@ func main() {
setupLog.Error(err, "unable to create controller", "controller", "K0sController")
os.Exit(1)
}

if err = (&controlplane.K0sControlPlaneValidator{}).SetupK0sControlPlaneWebhookWithManager(mgr); err != nil {
setupLog.Error(err, "unable to create validation webhook", "webhook", "K0sControlPlaneValidator")
os.Exit(1)
}
}

if isControllerEnabled(infrastructureController) {
Expand Down
26 changes: 26 additions & 0 deletions config/webhook/manifests.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
---
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingWebhookConfiguration
metadata:
name: validating-webhook-configuration
webhooks:
- admissionReviewVersions:
- v1
clientConfig:
service:
name: webhook-service
namespace: system
path: /validate-v1beta1-k0scontrolplane
failurePolicy: Fail
name: validate-k0scontolplane-v1beta1.k0smotron.io
rules:
- apiGroups:
- controlplane.cluster.x-k8s.io
apiVersions:
- v1beta1
operations:
- CREATE
- UPDATE
resources:
- k0scontolplanes
sideEffects: None
110 changes: 110 additions & 0 deletions internal/controller/controlplane/k0s_controlplane_webhook.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
/*
Copyright 2023.

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 controlplane

import (
"context"
"fmt"

"github.com/k0sproject/version"
"k8s.io/apimachinery/pkg/runtime"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/webhook"
"sigs.k8s.io/controller-runtime/pkg/webhook/admission"

"github.com/k0sproject/k0smotron/api/controlplane/v1beta1"
)

// +kubebuilder:webhook:path=/validate-v1beta1-k0scontrolplane,mutating=false,failurePolicy=fail,sideEffects=None,groups=controlplane.cluster.x-k8s.io,resources=k0scontolplanes,verbs=create;update,versions=v1beta1,name=validate-k0scontolplane-v1beta1.k0smotron.io,admissionReviewVersions=v1

// K0sControlPlaneValidator struct is responsible for validating the K0sControlPlane resource when it is created, updated, or deleted.
//
// NOTE: The +kubebuilder:object:generate=false marker prevents controller-gen from generating DeepCopy methods,
// as this struct is used only for temporary operations and does not need to be deeply copied.
type K0sControlPlaneValidator struct {
//TODO(user): Add more fields as needed for validation
}

var _ webhook.CustomValidator = &K0sControlPlaneValidator{}

// ValidateCreate implements webhook.CustomValidator so a webhook will be registered for the type K0sControlPlane.
func (v *K0sControlPlaneValidator) ValidateCreate(ctx context.Context, obj runtime.Object) (admission.Warnings, error) {

Check warning on line 45 in internal/controller/controlplane/k0s_controlplane_webhook.go

View workflow job for this annotation

GitHub Actions / Lint

unused-parameter: parameter 'ctx' seems to be unused, consider removing or renaming it as _ (revive)
kcp, ok := obj.(*v1beta1.K0sControlPlane)
if !ok {
return nil, fmt.Errorf("expected a K0sControlPlane object but got %T", obj)
}

return nil, validateK0sControlPlane(kcp)
}

// ValidateUpdate implements webhook.CustomValidator so a webhook will be registered for the type K0sControlPlane.
func (v *K0sControlPlaneValidator) ValidateUpdate(ctx context.Context, oldObj, newObj runtime.Object) (admission.Warnings, error) {

Check warning on line 55 in internal/controller/controlplane/k0s_controlplane_webhook.go

View workflow job for this annotation

GitHub Actions / Lint

unused-parameter: parameter 'ctx' seems to be unused, consider removing or renaming it as _ (revive)
newKCP, ok := newObj.(*v1beta1.K0sControlPlane)
if !ok {
return nil, fmt.Errorf("expected a new K0sControlPlane object but got %T", newObj)
}
oldKCP, ok := oldObj.(*v1beta1.K0sControlPlane)
if !ok {
return nil, fmt.Errorf("expected a old K0sControlPlane object but got %T", oldObj)
}

if oldKCP.Spec.Version != newKCP.Spec.Version {
oldV, err := version.NewVersion(oldKCP.Spec.Version)
if err != nil {
return nil, fmt.Errorf("failed to parse old version: %v", err)
}
newV, err := version.NewVersion(newKCP.Spec.Version)
if err != nil {
return nil, fmt.Errorf("failed to parse new version: %v", err)
}

// According to the Kubernetes skew policy, we can't upgrade more than one minor version at a time.
if newV.Core().Segments()[1]-oldV.Core().Segments()[1] > 1 {
return nil, fmt.Errorf("upgrading more than one minor version at a time is not allowed by the Kubernetes skew policy")
}
}

return nil, validateK0sControlPlane(newKCP)
}

// ValidateDelete implements webhook.CustomValidator so a webhook will be registered for the type K0sControlPlane.
func (v *K0sControlPlaneValidator) ValidateDelete(ctx context.Context, obj runtime.Object) (admission.Warnings, error) {

Check warning on line 85 in internal/controller/controlplane/k0s_controlplane_webhook.go

View workflow job for this annotation

GitHub Actions / Lint

unused-parameter: parameter 'ctx' seems to be unused, consider removing or renaming it as _ (revive)
return nil, nil
}

func validateK0sControlPlane(kcp *v1beta1.K0sControlPlane) error {
if kcp.Spec.UpdateStrategy == v1beta1.UpdateRecreate {

// If the cluster is running in single mode, we can't use the Recreate strategy
if kcp.Spec.K0sConfigSpec.Args != nil {
for _, arg := range kcp.Spec.K0sConfigSpec.Args {
if arg == "--single" {
return fmt.Errorf("UpdateStrategy Recreate strategy is not allowed when the cluster is running in single mode")
}
}
}
}

return nil
}

// SetupK0sControlPlaneWebhookWithManager registers the webhook for K0sControlPlane in the manager.
func (v *K0sControlPlaneValidator) SetupK0sControlPlaneWebhookWithManager(mgr ctrl.Manager) error {
return ctrl.NewWebhookManagedBy(mgr).For(&v1beta1.K0sControlPlane{}).
WithValidator(&K0sControlPlaneValidator{}).
Complete()
}
Loading