github.com/kotalco/kotal@v0.3.0/apis/filecoin/v1alpha1/node_validation_webhook.go (about)

     1  package v1alpha1
     2  
     3  import (
     4  	apierrors "k8s.io/apimachinery/pkg/api/errors"
     5  	"k8s.io/apimachinery/pkg/runtime"
     6  	"k8s.io/apimachinery/pkg/runtime/schema"
     7  	"k8s.io/apimachinery/pkg/util/validation/field"
     8  	"sigs.k8s.io/controller-runtime/pkg/webhook"
     9  	"sigs.k8s.io/controller-runtime/pkg/webhook/admission"
    10  )
    11  
    12  // +kubebuilder:webhook:verbs=create;update,path=/validate-filecoin-kotal-io-v1alpha1-node,mutating=false,failurePolicy=fail,groups=filecoin.kotal.io,resources=nodes,versions=v1alpha1,name=validate-filecoin-v1alpha1-node.kb.io,sideEffects=None,admissionReviewVersions=v1
    13  
    14  var _ webhook.Validator = &Node{}
    15  
    16  // ValidateCreate implements webhook.Validator so a webhook will be registered for the type
    17  func (n *Node) ValidateCreate() (admission.Warnings, error) {
    18  	nodelog.Info("validate create", "name", n.Name)
    19  
    20  	var allErrors field.ErrorList
    21  
    22  	allErrors = append(allErrors, n.Spec.Resources.ValidateCreate()...)
    23  
    24  	if len(allErrors) == 0 {
    25  		return nil, nil
    26  	}
    27  
    28  	return nil, apierrors.NewInvalid(schema.GroupKind{}, n.Name, allErrors)
    29  }
    30  
    31  // ValidateUpdate implements webhook.Validator so a webhook will be registered for the type
    32  func (n *Node) ValidateUpdate(old runtime.Object) (admission.Warnings, error) {
    33  	nodelog.Info("validate update", "name", n.Name)
    34  
    35  	var allErrors field.ErrorList
    36  
    37  	oldNode := old.(*Node)
    38  
    39  	// validate network is immutable
    40  	if oldNode.Spec.Network != n.Spec.Network {
    41  		err := field.Invalid(field.NewPath("spec").Child("network"), n.Spec.Network, "field is immutable")
    42  		allErrors = append(allErrors, err)
    43  	}
    44  
    45  	allErrors = append(allErrors, n.Spec.Resources.ValidateUpdate(&oldNode.Spec.Resources)...)
    46  
    47  	if len(allErrors) == 0 {
    48  		return nil, nil
    49  	}
    50  
    51  	return nil, apierrors.NewInvalid(schema.GroupKind{}, n.Name, allErrors)
    52  
    53  }
    54  
    55  // ValidateDelete implements webhook.Validator so a webhook will be registered for the type
    56  func (n *Node) ValidateDelete() (admission.Warnings, error) {
    57  	nodelog.Info("validate delete", "name", n.Name)
    58  
    59  	return nil, nil
    60  }