...

Source file src/edge-infra.dev/pkg/edge/webhooks/edge-injector/deviceclass.go

Documentation: edge-infra.dev/pkg/edge/webhooks/edge-injector

     1  package edgeinjector
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  
     7  	"k8s.io/apimachinery/pkg/runtime"
     8  	"sigs.k8s.io/controller-runtime/pkg/webhook/admission"
     9  
    10  	"edge-infra.dev/pkg/lib/fog"
    11  	dsv1 "edge-infra.dev/pkg/sds/devices/k8s/apis/v1"
    12  )
    13  
    14  var (
    15  	DeviceClass = "device-class"
    16  )
    17  
    18  type DeviceClassWebhook struct{}
    19  
    20  type Validator interface {
    21  	Validate() error
    22  	Name() string
    23  }
    24  
    25  func (c *DeviceClassWebhook) ValidateCreate(ctx context.Context, obj runtime.Object) (warnings admission.Warnings, err error) {
    26  	return validateDeviceObject(ctx, obj)
    27  }
    28  
    29  func (c *DeviceClassWebhook) ValidateUpdate(ctx context.Context, _, obj runtime.Object) (admission.Warnings, error) {
    30  	return validateDeviceObject(ctx, obj)
    31  }
    32  
    33  func (c *DeviceClassWebhook) ValidateDelete(_ context.Context, _ runtime.Object) (admission.Warnings, error) {
    34  	return nil, nil
    35  }
    36  
    37  func validateDeviceObject(ctx context.Context, obj runtime.Object) (warnings admission.Warnings, err error) {
    38  	log := fog.FromContext(ctx).WithValues("name", "DeviceClassWebhook")
    39  
    40  	args := []any{"group", obj.GetObjectKind().GroupVersionKind().Group, "kind", obj.GetObjectKind().GroupVersionKind().Kind}
    41  	deviceObject, err := convertObjectToDeviceSystemValidator(obj)
    42  	if err != nil {
    43  		log.Error(err, "invalid device class", args...)
    44  		return warnings, err
    45  	}
    46  
    47  	args = append(args, "name", deviceObject.Name())
    48  	if err := deviceObject.Validate(); err != nil {
    49  		log.Error(err, "invalid device resource", args...)
    50  		return warnings, err
    51  	}
    52  	return warnings, nil
    53  }
    54  
    55  func convertObjectToDeviceSystemValidator(obj runtime.Object) (Validator, error) {
    56  	devClass, ok := obj.(*dsv1.DeviceClass)
    57  	if ok {
    58  		return devClass, nil
    59  	}
    60  	devSet, ok := obj.(*dsv1.DeviceSet)
    61  	if ok {
    62  		return devSet, nil
    63  	}
    64  	return nil, fmt.Errorf("invalid object %s", obj.GetObjectKind().GroupVersionKind().String())
    65  }
    66  

View as plain text