github.com/verrazzano/verrazzano@v1.7.0/application-operator/controllers/webhooks/multiclustercomponent_webhook.go (about)

     1  // Copyright (c) 2021, 2022, Oracle and/or its affiliates.
     2  // Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl.
     3  
     4  package webhooks
     5  
     6  import (
     7  	"context"
     8  	"net/http"
     9  
    10  	"github.com/verrazzano/verrazzano/application-operator/apis/clusters/v1alpha1"
    11  	"github.com/verrazzano/verrazzano/application-operator/metricsexporter"
    12  	k8sadmission "k8s.io/api/admission/v1"
    13  	"sigs.k8s.io/controller-runtime/pkg/client"
    14  	"sigs.k8s.io/controller-runtime/pkg/webhook/admission"
    15  )
    16  
    17  // MultiClusterComponentValidator is a struct holding objects used during validation.
    18  type MultiClusterComponentValidator struct {
    19  	client  client.Client
    20  	decoder *admission.Decoder
    21  }
    22  
    23  // InjectClient injects the client.
    24  func (v *MultiClusterComponentValidator) InjectClient(c client.Client) error {
    25  	v.client = c
    26  	return nil
    27  }
    28  
    29  // InjectDecoder injects the decoder.
    30  func (v *MultiClusterComponentValidator) InjectDecoder(d *admission.Decoder) error {
    31  	v.decoder = d
    32  	return nil
    33  }
    34  
    35  // Handle performs validation of created or updated MultiClusterComponent resources.
    36  func (v *MultiClusterComponentValidator) Handle(ctx context.Context, req admission.Request) admission.Response {
    37  	counterMetricObject, errorCounterMetricObject, handleDurationMetricObject, zapLogForMetrics, err := metricsexporter.ExposeControllerMetrics("MultiClusterComponentValidator", metricsexporter.MultiClusterCompHandleCounter, metricsexporter.MultiClusterCompHandleError, metricsexporter.MultiClusterCompHandleDuration)
    38  	if err != nil {
    39  		return admission.Response{}
    40  	}
    41  	handleDurationMetricObject.TimerStart()
    42  	defer handleDurationMetricObject.TimerStop()
    43  
    44  	mcc := &v1alpha1.MultiClusterComponent{}
    45  	err = v.decoder.Decode(req, mcc)
    46  	if err != nil {
    47  		errorCounterMetricObject.Inc(zapLogForMetrics, err)
    48  		return admission.Errored(http.StatusBadRequest, err)
    49  	}
    50  
    51  	if mcc.ObjectMeta.DeletionTimestamp.IsZero() {
    52  		switch req.Operation {
    53  		case k8sadmission.Create, k8sadmission.Update:
    54  			err = validateMultiClusterResource(v.client, mcc)
    55  			if err != nil {
    56  				errorCounterMetricObject.Inc(zapLogForMetrics, err)
    57  				return admission.Denied(err.Error())
    58  			}
    59  		}
    60  	}
    61  	counterMetricObject.Inc(zapLogForMetrics, err)
    62  	return admission.Allowed("")
    63  }