|
| 1 | +package rsct |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + |
| 7 | + rsctv1alpha1 "github.com/ocp-power-automation/rsct-operator/api/v1alpha1" |
| 8 | + "k8s.io/apimachinery/pkg/runtime" |
| 9 | + ctrl "sigs.k8s.io/controller-runtime" |
| 10 | + "sigs.k8s.io/controller-runtime/pkg/client" |
| 11 | + "sigs.k8s.io/controller-runtime/pkg/webhook/admission" |
| 12 | +) |
| 13 | + |
| 14 | +type RSCTValidator struct { |
| 15 | + Client client.Client |
| 16 | +} |
| 17 | + |
| 18 | +// ValidateCreate implements admission.CustomValidator. |
| 19 | +func (r *RSCTValidator) ValidateCreate(ctx context.Context, obj runtime.Object) (admission.Warnings, error) { |
| 20 | + cr, ok := obj.(*rsctv1alpha1.RSCT) |
| 21 | + if !ok { |
| 22 | + return nil, fmt.Errorf("expected RSCT, got %T", obj) |
| 23 | + } |
| 24 | + |
| 25 | + var crList rsctv1alpha1.RSCTList |
| 26 | + if err := r.Client.List(ctx, &crList); err != nil { |
| 27 | + return nil, fmt.Errorf("cannot list RSCT: %w", err) |
| 28 | + } |
| 29 | + |
| 30 | + if len(crList.Items) > 0 { |
| 31 | + return nil, fmt.Errorf("only one RSCT instance is allowed (found %d), rejecting creation of %s", len(crList.Items), cr.Name) |
| 32 | + } |
| 33 | + |
| 34 | + return nil, nil |
| 35 | +} |
| 36 | + |
| 37 | +// ValidateDelete implements admission.CustomValidator. |
| 38 | +func (r *RSCTValidator) ValidateDelete(ctx context.Context, obj runtime.Object) (warnings admission.Warnings, err error) { |
| 39 | + return nil, nil |
| 40 | +} |
| 41 | + |
| 42 | +// ValidateUpdate implements admission.CustomValidator. |
| 43 | +func (r *RSCTValidator) ValidateUpdate(ctx context.Context, oldObj runtime.Object, newObj runtime.Object) (warnings admission.Warnings, err error) { |
| 44 | + return nil, nil |
| 45 | +} |
| 46 | + |
| 47 | +var _ admission.CustomValidator = &RSCTValidator{} |
| 48 | + |
| 49 | +// Register the webhook with the manager |
| 50 | +func RegisterWebhooks(mgr ctrl.Manager) error { |
| 51 | + return ctrl.NewWebhookManagedBy(mgr). |
| 52 | + For(&rsctv1alpha1.RSCT{}). |
| 53 | + WithValidator(&RSCTValidator{Client: mgr.GetClient()}). |
| 54 | + Complete() |
| 55 | +} |
0 commit comments