Skip to content

Create a validation webhook #348

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

Merged
Merged
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
4 changes: 2 additions & 2 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -97,11 +97,11 @@ help: ## Display this help.

.PHONY: manifests
manifests: controller-gen ## Generate WebhookConfiguration, ClusterRole and CustomResourceDefinition objects.
$(CONTROLLER_GEN) crd paths="./api/..." output:crd:artifacts:config=config/crd/bases
$(CONTROLLER_GEN) crd webhook paths="./api/..." output:crd:artifacts:config=config/crd/bases
$(CONTROLLER_GEN) rbac:roleName=manager-role paths="./controllers" output:rbac:artifacts:config=config/rbac

# Hub
$(CONTROLLER_GEN) crd paths="./api-hub/..." output:crd:artifacts:config=config/crd-hub/bases
$(CONTROLLER_GEN) crd webhook paths="./api-hub/..." output:crd:artifacts:config=config/crd-hub/bases
$(CONTROLLER_GEN) rbac:roleName=manager-role paths="./controllers/hub" output:rbac:artifacts:config=config/rbac-hub

.PHONY: generate
Expand Down
3 changes: 3 additions & 0 deletions PROJECT
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@ resources:
kind: Module
path: github.com/kubernetes-sigs/kernel-module-management/api/v1beta1
version: v1beta1
webhooks:
validation: true
webhookVersion: v1
- api:
crdVersion: v1
namespaced: false
Expand Down
111 changes: 111 additions & 0 deletions api/v1beta1/module_webhook.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
/*
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 v1beta1

import (
"errors"
"fmt"
"k8s.io/apimachinery/pkg/runtime"
"regexp"
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 modulelog = logf.Log.WithName("module-resource")

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

//+kubebuilder:webhook:path=/validate-kmm-sigs-x-k8s-io-v1beta1-module,mutating=false,failurePolicy=fail,sideEffects=None,groups=kmm.sigs.x-k8s.io,resources=modules,verbs=create;update,versions=v1beta1,name=vmodule.kb.io,admissionReviewVersions=v1

var _ webhook.Validator = &Module{}

// ValidateCreate implements webhook.Validator so a webhook will be registered for the type
func (m *Module) ValidateCreate() error {
modulelog.Info("Validating Module creation", "name", m.Name, "namespace", m.Namespace)

if err := m.validateKernelMapping(); err != nil {
return fmt.Errorf("failed to validate kernel mappings: %v", err)
}

return m.validateModprobe()
}

// ValidateUpdate implements webhook.Validator so a webhook will be registered for the type
func (m *Module) ValidateUpdate(_ runtime.Object) error {
modulelog.Info("Validating Module update", "name", m.Name, "namespace", m.Namespace)

if err := m.validateKernelMapping(); err != nil {
return fmt.Errorf("failed to validate kernel mappings: %v", err)
}

return m.validateModprobe()
}

// ValidateDelete implements webhook.Validator so a webhook will be registered for the type
func (m *Module) ValidateDelete() error {
return nil
}

func (m *Module) validateKernelMapping() error {
container := m.Spec.ModuleLoader.Container

for idx, km := range container.KernelMappings {
if km.Regexp != "" && km.Literal != "" {
return fmt.Errorf("regexp and literal are mutually exclusive properties at kernelMappings[%d]", idx)
}

if km.Regexp == "" && km.Literal == "" {
return fmt.Errorf("regexp or literal must be set at kernelMappings[%d]", idx)
}

if _, err := regexp.Compile(km.Regexp); err != nil {
return fmt.Errorf("invalid regexp at index %d: %v", idx, err)
}

if container.ContainerImage == "" && km.ContainerImage == "" {
return fmt.Errorf("missing spec.moduleLoader.container.kernelMappings[%d].containerImage", idx)
}
}

return nil
}

func (m *Module) validateModprobe() error {
modprobe := m.Spec.ModuleLoader.Container.Modprobe
moduleNameDefined := modprobe.ModuleName != ""
rawLoadArgsDefined := modprobe.RawArgs != nil && len(modprobe.RawArgs.Load) > 0
rawUnloadArgsDefined := modprobe.RawArgs != nil && len(modprobe.RawArgs.Unload) > 0

if moduleNameDefined {
if rawLoadArgsDefined || rawUnloadArgsDefined {
return errors.New("rawArgs cannot be set when moduleName is set")
}
return nil
}

if !rawLoadArgsDefined || !rawUnloadArgsDefined {
return errors.New("load and unload rawArgs must be set when moduleName is unset")
}

return nil
}
Loading