github.com/kotalco/kotal@v0.3.0/apis/bitcoin/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-bitcoin-kotal-io-v1alpha1-node,mutating=false,failurePolicy=fail,groups=bitcoin.kotal.io,resources=nodes,versions=v1alpha1,name=validate-bitcoin-v1alpha1-node.kb.io,sideEffects=None,admissionReviewVersions=v1 13 14 var _ webhook.Validator = &Node{} 15 16 // Validate is common create and update validation rules 17 func (n *Node) validate() field.ErrorList { 18 var nodeErrors field.ErrorList 19 20 // can't work in pruning and transaction index mode at the same time 21 if n.Spec.TransactionIndex && n.Spec.Pruning { 22 err := field.Invalid(field.NewPath("spec").Child("pruning"), n.Spec.Pruning, "must be false if transaction index is enabled") 23 nodeErrors = append(nodeErrors, err) 24 } 25 26 return nodeErrors 27 } 28 29 // ValidateCreate implements webhook.Validator so a webhook will be registered for the type 30 func (r *Node) ValidateCreate() (admission.Warnings, error) { 31 var allErrors field.ErrorList 32 33 nodelog.Info("validate create", "name", r.Name) 34 35 allErrors = append(allErrors, r.validate()...) 36 allErrors = append(allErrors, r.Spec.Resources.ValidateCreate()...) 37 38 if len(allErrors) == 0 { 39 return nil, nil 40 } 41 42 return nil, apierrors.NewInvalid(schema.GroupKind{}, r.Name, allErrors) 43 } 44 45 // ValidateUpdate implements webhook.Validator so a webhook will be registered for the type 46 func (r *Node) ValidateUpdate(old runtime.Object) (admission.Warnings, error) { 47 var allErrors field.ErrorList 48 oldNode := old.(*Node) 49 50 nodelog.Info("validate update", "name", r.Name) 51 52 allErrors = append(allErrors, r.validate()...) 53 allErrors = append(allErrors, r.Spec.Resources.ValidateUpdate(&oldNode.Spec.Resources)...) 54 55 if r.Spec.Network != oldNode.Spec.Network { 56 err := field.Invalid(field.NewPath("spec").Child("network"), r.Spec.Network, "field is immutable") 57 allErrors = append(allErrors, err) 58 } 59 60 if len(allErrors) == 0 { 61 return nil, nil 62 } 63 64 return nil, apierrors.NewInvalid(schema.GroupKind{}, r.Name, allErrors) 65 } 66 67 // ValidateDelete implements webhook.Validator so a webhook will be registered for the type 68 func (r *Node) ValidateDelete() (admission.Warnings, error) { 69 nodelog.Info("validate delete", "name", r.Name) 70 71 return nil, nil 72 }