github.com/verrazzano/verrazzano@v1.7.0/application-operator/controllers/webhooks/multiclustersecret_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 // MultiClusterSecretValidator is a struct holding objects used during validation. 18 type MultiClusterSecretValidator struct { 19 client client.Client 20 decoder *admission.Decoder 21 } 22 23 // InjectClient injects the client. 24 func (v *MultiClusterSecretValidator) InjectClient(c client.Client) error { 25 v.client = c 26 return nil 27 } 28 29 // InjectDecoder injects the decoder. 30 func (v *MultiClusterSecretValidator) InjectDecoder(d *admission.Decoder) error { 31 v.decoder = d 32 return nil 33 } 34 35 // Handle performs validation of created or updated MultiClusterSecret resources. 36 func (v *MultiClusterSecretValidator) Handle(ctx context.Context, req admission.Request) admission.Response { 37 counterMetricObject, errorCounterMetricObject, handleDurationMetricObject, zapLogForMetrics, err := metricsexporter.ExposeControllerMetrics("MultiClusterSecretValidator", metricsexporter.MultiClusterSecretHandleCounter, metricsexporter.MultiClusterSecretHandleError, metricsexporter.MultiClusterSecretHandleDuration) 38 if err != nil { 39 return admission.Response{} 40 } 41 handleDurationMetricObject.TimerStart() 42 defer handleDurationMetricObject.TimerStop() 43 44 mcs := &v1alpha1.MultiClusterSecret{} 45 err = v.decoder.Decode(req, mcs) 46 if err != nil { 47 errorCounterMetricObject.Inc(zapLogForMetrics, err) 48 return admission.Errored(http.StatusBadRequest, err) 49 } 50 51 if mcs.ObjectMeta.DeletionTimestamp.IsZero() { 52 switch req.Operation { 53 case k8sadmission.Create, k8sadmission.Update: 54 err = validateMultiClusterResource(v.client, mcs) 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 }