kubernetes-sigs / controller-runtime

Repo for the controller-runtime subproject of kubebuilder (sig-apimachinery)
Apache License 2.0
2.44k stars 1.13k forks source link

Check if the other resources referenced by an object exist within a webhook #2968

Open zhixiongdu027 opened 2 days ago

zhixiongdu027 commented 2 days ago

I want to check if the other resources referenced by an object exist within a webhook. Could someone please help me complete the logic in the following code example? Thank you very much.

// SetupWebhookWithManager will setup the manager to manage the webhooks
func (r *Pool) SetupWebhookWithManager(mgr ctrl.Manager) error {
    return ctrl.NewWebhookManagedBy(mgr).
        For(r).
        Complete()
}

var _ webhook.Validator = &Pool{}

func (r *Pool) Validate() error {
    var allErrs field.ErrorList

    model := r.Spec.Model

    /*
        check model is exist here;
    */

    if len(allErrs) == 0 {
        return nil
    }

    return apierrors.NewInvalid(schema.GroupKind{Group: GroupVersion.Group, Kind: "Pool"}, r.Name, allErrs)
}

// ValidateCreate implements webhook.Validator so a webhook will be registered for the type
func (r *Pool) ValidateCreate() (admission.Warnings, error) {
    poollog.Info("validate create", "name", r.Name)

    // TODO(user): fill in your validation logic upon object creation.
    return nil, r.Validate()
}
### Tasks
sbueringer commented 1 day ago

You can implement a CustomValidator and then set a Client on the struct that implements it. Here's an example https://github.com/kubernetes-sigs/cluster-api/blob/main/internal/webhooks/cluster.go#L75

sbueringer commented 1 day ago

/transfer controller-runtime

zhixiongdu027 commented 1 day ago

I will try,Many tks

sbueringer commented 1 day ago

Please also note that Validator has been removed and won't exist in the next CR release (xref https://github.com/kubernetes-sigs/controller-runtime/pull/2877)