From ae89aabb56cb0424c3645992d3d0ea3a1b610917 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Charles-Edouard=20Br=C3=A9t=C3=A9ch=C3=A9?= Date: Wed, 6 Apr 2022 14:41:08 +0200 Subject: [PATCH] refactor: webhooks metrics reporting (#3548) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit refactor: webhooks metrics reporting Signed-off-by: Charles-Edouard Brétéché --- pkg/metrics/admissionrequests/parsers.go | 17 -- .../admissionreviewduration/parsers.go | 17 -- pkg/metrics/parsers.go | 15 ++ .../policyexecutionduration/parsers.go | 17 -- pkg/metrics/policyresults/parsers.go | 17 -- pkg/webhooks/common.go | 44 ----- pkg/webhooks/generation.go | 27 +-- pkg/webhooks/metrics.go | 156 ++++++++---------- pkg/webhooks/mutation.go | 4 +- pkg/webhooks/validation.go | 12 +- 10 files changed, 98 insertions(+), 228 deletions(-) diff --git a/pkg/metrics/admissionrequests/parsers.go b/pkg/metrics/admissionrequests/parsers.go index 498171ed2f..e1fcdc7a6b 100644 --- a/pkg/metrics/admissionrequests/parsers.go +++ b/pkg/metrics/admissionrequests/parsers.go @@ -1,8 +1,6 @@ package admissionrequests import ( - "fmt" - "github.com/kyverno/kyverno/pkg/metrics" ) @@ -13,18 +11,3 @@ func ParsePromMetrics(pm metrics.PromMetrics) PromMetrics { func ParsePromConfig(pc metrics.PromConfig) PromConfig { return PromConfig(pc) } - -func ParseResourceRequestOperation(requestOperationStr string) (metrics.ResourceRequestOperation, error) { - switch requestOperationStr { - case "CREATE": - return metrics.ResourceCreated, nil - case "UPDATE": - return metrics.ResourceUpdated, nil - case "DELETE": - return metrics.ResourceDeleted, nil - case "CONNECT": - return metrics.ResourceConnected, nil - default: - return "", fmt.Errorf("unknown request operation made by resource: %s. Allowed requests: 'CREATE', 'UPDATE', 'DELETE', 'CONNECT'", requestOperationStr) - } -} diff --git a/pkg/metrics/admissionreviewduration/parsers.go b/pkg/metrics/admissionreviewduration/parsers.go index 4df1387461..bd0f79baab 100644 --- a/pkg/metrics/admissionreviewduration/parsers.go +++ b/pkg/metrics/admissionreviewduration/parsers.go @@ -1,8 +1,6 @@ package admissionreviewduration import ( - "fmt" - "github.com/kyverno/kyverno/pkg/metrics" ) @@ -13,18 +11,3 @@ func ParsePromMetrics(pm metrics.PromMetrics) PromMetrics { func ParsePromConfig(pc metrics.PromConfig) PromConfig { return PromConfig(pc) } - -func ParseResourceRequestOperation(requestOperationStr string) (metrics.ResourceRequestOperation, error) { - switch requestOperationStr { - case "CREATE": - return metrics.ResourceCreated, nil - case "UPDATE": - return metrics.ResourceUpdated, nil - case "DELETE": - return metrics.ResourceDeleted, nil - case "CONNECT": - return metrics.ResourceConnected, nil - default: - return "", fmt.Errorf("unknown request operation made by resource: %s. Allowed requests: 'CREATE', 'UPDATE', 'DELETE', 'CONNECT'", requestOperationStr) - } -} diff --git a/pkg/metrics/parsers.go b/pkg/metrics/parsers.go index 66810b76ee..d66e4e568a 100644 --- a/pkg/metrics/parsers.go +++ b/pkg/metrics/parsers.go @@ -37,3 +37,18 @@ func ParseRuleType(rule kyverno.Rule) RuleType { } return EmptyRuleType } + +func ParseResourceRequestOperation(requestOperationStr string) (ResourceRequestOperation, error) { + switch requestOperationStr { + case "CREATE": + return ResourceCreated, nil + case "UPDATE": + return ResourceUpdated, nil + case "DELETE": + return ResourceDeleted, nil + case "CONNECT": + return ResourceConnected, nil + default: + return "", fmt.Errorf("unknown request operation made by resource: %s. Allowed requests: 'CREATE', 'UPDATE', 'DELETE', 'CONNECT'", requestOperationStr) + } +} diff --git a/pkg/metrics/policyexecutionduration/parsers.go b/pkg/metrics/policyexecutionduration/parsers.go index 4de274201c..b7f2b9895f 100644 --- a/pkg/metrics/policyexecutionduration/parsers.go +++ b/pkg/metrics/policyexecutionduration/parsers.go @@ -1,8 +1,6 @@ package policyexecutionduration import ( - "fmt" - "github.com/kyverno/kyverno/pkg/engine/response" "github.com/kyverno/kyverno/pkg/metrics" ) @@ -27,18 +25,3 @@ func ParseRuleTypeFromEngineRuleResponse(rule response.RuleResponse) metrics.Rul return metrics.EmptyRuleType } } - -func ParseResourceRequestOperation(requestOperationStr string) (metrics.ResourceRequestOperation, error) { - switch requestOperationStr { - case "CREATE": - return metrics.ResourceCreated, nil - case "UPDATE": - return metrics.ResourceUpdated, nil - case "DELETE": - return metrics.ResourceDeleted, nil - case "CONNECT": - return metrics.ResourceConnected, nil - default: - return "", fmt.Errorf("unknown request operation made by resource: %s. Allowed requests: 'CREATE', 'UPDATE', 'DELETE', 'CONNECT'", requestOperationStr) - } -} diff --git a/pkg/metrics/policyresults/parsers.go b/pkg/metrics/policyresults/parsers.go index d90546cb6d..8bc8baee6d 100644 --- a/pkg/metrics/policyresults/parsers.go +++ b/pkg/metrics/policyresults/parsers.go @@ -1,8 +1,6 @@ package policyresults import ( - "fmt" - "github.com/kyverno/kyverno/pkg/engine/response" "github.com/kyverno/kyverno/pkg/metrics" ) @@ -27,18 +25,3 @@ func ParseRuleTypeFromEngineRuleResponse(rule response.RuleResponse) metrics.Rul return metrics.EmptyRuleType } } - -func ParseResourceRequestOperation(requestOperationStr string) (metrics.ResourceRequestOperation, error) { - switch requestOperationStr { - case "CREATE": - return metrics.ResourceCreated, nil - case "UPDATE": - return metrics.ResourceUpdated, nil - case "DELETE": - return metrics.ResourceDeleted, nil - case "CONNECT": - return metrics.ResourceConnected, nil - default: - return "", fmt.Errorf("unknown request operation made by resource: %s. Allowed requests: 'CREATE', 'UPDATE', 'DELETE', 'CONNECT'", requestOperationStr) - } -} diff --git a/pkg/webhooks/common.go b/pkg/webhooks/common.go index 012c86b7f5..022b8a68c5 100644 --- a/pkg/webhooks/common.go +++ b/pkg/webhooks/common.go @@ -14,8 +14,6 @@ import ( "github.com/pkg/errors" yamlv2 "gopkg.in/yaml.v2" "k8s.io/api/admission/v1beta1" - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "k8s.io/apimachinery/pkg/runtime/schema" ) // returns true -> if there is even one policy that blocks resource request @@ -142,48 +140,6 @@ func checkForRBACInfo(rule kyverno.Rule) bool { return false } -// extracts the new and old resource as unstructured -func extractResources(newRaw []byte, request *v1beta1.AdmissionRequest) (unstructured.Unstructured, unstructured.Unstructured, error) { - var emptyResource unstructured.Unstructured - - // New Resource - if newRaw == nil { - newRaw = request.Object.Raw - } - if newRaw == nil { - return emptyResource, emptyResource, fmt.Errorf("new resource is not defined") - } - - new, err := convertResource(newRaw, request.Kind.Group, request.Kind.Version, request.Kind.Kind, request.Namespace) - if err != nil { - return emptyResource, emptyResource, fmt.Errorf("failed to convert new raw to unstructured: %v", err) - } - - // Old Resource - Optional - oldRaw := request.OldObject.Raw - if oldRaw == nil { - return new, emptyResource, nil - } - - old, err := convertResource(oldRaw, request.Kind.Group, request.Kind.Version, request.Kind.Kind, request.Namespace) - if err != nil { - return emptyResource, emptyResource, fmt.Errorf("failed to convert old raw to unstructured: %v", err) - } - return new, old, err -} - -// convertResource converts raw bytes to an unstructured object -func convertResource(raw []byte, group, version, kind, namespace string) (unstructured.Unstructured, error) { - obj, err := engineutils.ConvertToUnstructured(raw) - if err != nil { - return unstructured.Unstructured{}, fmt.Errorf("failed to convert raw to unstructured: %v", err) - } - - obj.SetGroupVersionKind(schema.GroupVersionKind{Group: group, Version: version, Kind: kind}) - obj.SetNamespace(namespace) - return *obj, nil -} - func excludeKyvernoResources(kind string) bool { switch kind { case "ClusterPolicyReport": diff --git a/pkg/webhooks/generation.go b/pkg/webhooks/generation.go index fe4047d6d5..d628f0f8e0 100644 --- a/pkg/webhooks/generation.go +++ b/pkg/webhooks/generation.go @@ -23,9 +23,6 @@ import ( "github.com/kyverno/kyverno/pkg/engine/variables" "github.com/kyverno/kyverno/pkg/event" gen "github.com/kyverno/kyverno/pkg/generate" - "github.com/kyverno/kyverno/pkg/metrics" - policyExecutionDuration "github.com/kyverno/kyverno/pkg/metrics/policyexecutionduration" - policyResults "github.com/kyverno/kyverno/pkg/metrics/policyresults" kyvernoutils "github.com/kyverno/kyverno/pkg/utils" "github.com/kyverno/kyverno/pkg/webhooks/generate" "k8s.io/api/admission/v1beta1" @@ -40,8 +37,8 @@ func (ws *WebhookServer) applyGeneratePolicies(request *v1beta1.AdmissionRequest generateEngineResponsesSenderForAdmissionRequestsCountMetric := make(chan []*response.EngineResponse, 1) go ws.handleGenerate(request, policies, policyContext.JSONContext, policyContext.AdmissionInfo, ws.configHandler, ts, &admissionReviewCompletionLatencyChannel, &generateEngineResponsesSenderForAdmissionReviewDurationMetric, &generateEngineResponsesSenderForAdmissionRequestsCountMetric) - go registerAdmissionReviewDurationMetricGenerate(logger, *ws.promConfig, string(request.Operation), &admissionReviewCompletionLatencyChannel, &generateEngineResponsesSenderForAdmissionReviewDurationMetric) - go registerAdmissionRequestsMetricGenerate(logger, *ws.promConfig, string(request.Operation), &generateEngineResponsesSenderForAdmissionRequestsCountMetric) + go ws.registerAdmissionReviewDurationMetricGenerate(logger, string(request.Operation), &admissionReviewCompletionLatencyChannel, &generateEngineResponsesSenderForAdmissionReviewDurationMetric) + go ws.registerAdmissionRequestsMetricGenerate(logger, string(request.Operation), &generateEngineResponsesSenderForAdmissionRequestsCountMetric) } //handleGenerate handles admission-requests for policies with generate rules @@ -127,26 +124,6 @@ func (ws *WebhookServer) handleGenerate( *generateEngineResponsesSenderForAdmissionRequestsCountMetric <- engineResponses } -func (ws *WebhookServer) registerPolicyResultsMetricGeneration(logger logr.Logger, resourceRequestOperation string, policy kyverno.PolicyInterface, engineResponse response.EngineResponse) { - resourceRequestOperationPromAlias, err := policyResults.ParseResourceRequestOperation(resourceRequestOperation) - if err != nil { - logger.Error(err, "error occurred while registering kyverno_policy_results_total metrics for the above policy", "name", policy.GetName()) - } - if err := policyResults.ParsePromConfig(*ws.promConfig).ProcessEngineResponse(policy, engineResponse, metrics.AdmissionRequest, resourceRequestOperationPromAlias); err != nil { - logger.Error(err, "error occurred while registering kyverno_policy_results_total metrics for the above policy", "name", policy.GetName()) - } -} - -func (ws *WebhookServer) registerPolicyExecutionDurationMetricGenerate(logger logr.Logger, resourceRequestOperation string, policy kyverno.PolicyInterface, engineResponse response.EngineResponse) { - resourceRequestOperationPromAlias, err := policyExecutionDuration.ParseResourceRequestOperation(resourceRequestOperation) - if err != nil { - logger.Error(err, "error occurred while registering kyverno_policy_execution_duration_seconds metrics for the above policy", "name", policy.GetName()) - } - if err := policyExecutionDuration.ParsePromConfig(*ws.promConfig).ProcessEngineResponse(policy, engineResponse, metrics.AdmissionRequest, "", resourceRequestOperationPromAlias); err != nil { - logger.Error(err, "error occurred while registering kyverno_policy_execution_duration_seconds metrics for the above policy", "name", policy.GetName()) - } -} - //handleUpdatesForGenerateRules handles admission-requests for update func (ws *WebhookServer) handleUpdatesForGenerateRules(request *v1beta1.AdmissionRequest, policies []kyverno.PolicyInterface) { if request.Operation != v1beta1.Update { diff --git a/pkg/webhooks/metrics.go b/pkg/webhooks/metrics.go index 665f55550c..0029110926 100644 --- a/pkg/webhooks/metrics.go +++ b/pkg/webhooks/metrics.go @@ -1,6 +1,8 @@ package webhooks import ( + "fmt" + "github.com/go-logr/logr" kyverno "github.com/kyverno/kyverno/api/kyverno/v1" v1 "github.com/kyverno/kyverno/api/kyverno/v1" @@ -12,109 +14,97 @@ import ( policyResults "github.com/kyverno/kyverno/pkg/metrics/policyresults" ) -func registerAdmissionReviewDurationMetricMutate(logger logr.Logger, promConfig metrics.PromConfig, requestOperation string, engineResponses []*response.EngineResponse, admissionReviewLatencyDuration int64) { - resourceRequestOperationPromAlias, err := admissionReviewDuration.ParseResourceRequestOperation(requestOperation) - if err != nil { - logger.Error(err, "error occurred while registering kyverno_admission_review_duration_seconds metrics") - } - if err := admissionReviewDuration.ParsePromConfig(promConfig).ProcessEngineResponses(engineResponses, admissionReviewLatencyDuration, resourceRequestOperationPromAlias); err != nil { - logger.Error(err, "error occurred while registering kyverno_admission_review_duration_seconds metrics") +type reporterFunc func(metrics.ResourceRequestOperation) error + +func registerMetric(logger logr.Logger, m string, requestOperation string, r reporterFunc) { + if op, err := metrics.ParseResourceRequestOperation(requestOperation); err != nil { + logger.Error(err, fmt.Sprintf("error occurred while registering %s metrics", m)) + } else { + if err := r(op); err != nil { + logger.Error(err, fmt.Sprintf("error occurred while registering %s metrics", m)) + } } } -func registerAdmissionRequestsMetricMutate(logger logr.Logger, promConfig metrics.PromConfig, requestOperation string, engineResponses []*response.EngineResponse) { - resourceRequestOperationPromAlias, err := admissionReviewDuration.ParseResourceRequestOperation(requestOperation) - if err != nil { - logger.Error(err, "error occurred while registering kyverno_admission_requests_total metrics") - } - if err := admissionRequests.ParsePromConfig(promConfig).ProcessEngineResponses(engineResponses, resourceRequestOperationPromAlias); err != nil { - logger.Error(err, "error occurred while registering kyverno_admission_requests_total metrics") - } +// ADMISSION REVIEW + +func (ws *WebhookServer) registerAdmissionReviewDurationMetricMutate(logger logr.Logger, requestOperation string, engineResponses []*response.EngineResponse, admissionReviewLatencyDuration int64) { + registerMetric(logger, "kyverno_admission_review_duration_seconds", requestOperation, func(op metrics.ResourceRequestOperation) error { + return admissionReviewDuration.ParsePromConfig(*ws.promConfig).ProcessEngineResponses(engineResponses, admissionReviewLatencyDuration, op) + }) } -func registerAdmissionReviewDurationMetricGenerate(logger logr.Logger, promConfig metrics.PromConfig, requestOperation string, latencyReceiver *chan int64, engineResponsesReceiver *chan []*response.EngineResponse) { +func (ws *WebhookServer) registerAdmissionReviewDurationMetricGenerate(logger logr.Logger, requestOperation string, latencyReceiver *chan int64, engineResponsesReceiver *chan []*response.EngineResponse) { defer close(*latencyReceiver) defer close(*engineResponsesReceiver) - engineResponses := <-(*engineResponsesReceiver) - resourceRequestOperationPromAlias, err := admissionReviewDuration.ParseResourceRequestOperation(requestOperation) - if err != nil { - logger.Error(err, "error occurred while registering kyverno_admission_review_duration_seconds metrics") - } - // this goroutine will keep on waiting here till it doesn't receive the admission review latency int64 from the other goroutine i.e. ws.HandleGenerate - admissionReviewLatencyDuration := <-(*latencyReceiver) - if err := admissionReviewDuration.ParsePromConfig(promConfig).ProcessEngineResponses(engineResponses, admissionReviewLatencyDuration, resourceRequestOperationPromAlias); err != nil { - logger.Error(err, "error occurred while registering kyverno_admission_review_duration_seconds metrics") - } + registerMetric(logger, "kyverno_admission_review_duration_seconds", requestOperation, func(op metrics.ResourceRequestOperation) error { + return admissionReviewDuration.ParsePromConfig(*ws.promConfig).ProcessEngineResponses(<-(*engineResponsesReceiver), <-(*latencyReceiver), op) + }) } -func registerAdmissionRequestsMetricGenerate(logger logr.Logger, promConfig metrics.PromConfig, requestOperation string, engineResponsesReceiver *chan []*response.EngineResponse) { +func registerAdmissionReviewDurationMetricValidate(logger logr.Logger, promConfig *metrics.PromConfig, requestOperation string, engineResponses []*response.EngineResponse, admissionReviewLatencyDuration int64) { + registerMetric(logger, "kyverno_admission_review_duration_seconds", requestOperation, func(op metrics.ResourceRequestOperation) error { + return admissionReviewDuration.ParsePromConfig(*promConfig).ProcessEngineResponses(engineResponses, admissionReviewLatencyDuration, op) + }) +} + +// ADMISSION REQUEST + +func (ws *WebhookServer) registerAdmissionRequestsMetricMutate(logger logr.Logger, requestOperation string, engineResponses []*response.EngineResponse) { + registerMetric(logger, "kyverno_admission_requests_total", requestOperation, func(op metrics.ResourceRequestOperation) error { + return admissionRequests.ParsePromConfig(*ws.promConfig).ProcessEngineResponses(engineResponses, op) + }) +} + +func (ws *WebhookServer) registerAdmissionRequestsMetricGenerate(logger logr.Logger, requestOperation string, engineResponsesReceiver *chan []*response.EngineResponse) { defer close(*engineResponsesReceiver) - engineResponses := <-(*engineResponsesReceiver) - resourceRequestOperationPromAlias, err := admissionReviewDuration.ParseResourceRequestOperation(requestOperation) - if err != nil { - logger.Error(err, "error occurred while registering kyverno_admission_requests_total metrics") - } - if err := admissionRequests.ParsePromConfig(promConfig).ProcessEngineResponses(engineResponses, resourceRequestOperationPromAlias); err != nil { - logger.Error(err, "error occurred while registering kyverno_admission_requests_total metrics") - } + registerMetric(logger, "kyverno_admission_requests_total", requestOperation, func(op metrics.ResourceRequestOperation) error { + return admissionRequests.ParsePromConfig(*ws.promConfig).ProcessEngineResponses(<-(*engineResponsesReceiver), op) + }) } -func registerPolicyResultsMetricValidation(promConfig *metrics.PromConfig, logger logr.Logger, requestOperation string, policy v1.PolicyInterface, engineResponse response.EngineResponse) { - resourceRequestOperationPromAlias, err := policyResults.ParseResourceRequestOperation(requestOperation) - if err != nil { - logger.Error(err, "error occurred while registering kyverno_policy_results_total metrics for the above policy", "name", policy.GetName()) - } - if err := policyResults.ParsePromConfig(*promConfig).ProcessEngineResponse(policy, engineResponse, metrics.AdmissionRequest, resourceRequestOperationPromAlias); err != nil { - logger.Error(err, "error occurred while registering kyverno_policy_results_total metrics for the above policy", "name", policy.GetName()) - } +func registerAdmissionRequestsMetricValidate(logger logr.Logger, promConfig *metrics.PromConfig, requestOperation string, engineResponses []*response.EngineResponse) { + registerMetric(logger, "kyverno_admission_requests_total", requestOperation, func(op metrics.ResourceRequestOperation) error { + return admissionRequests.ParsePromConfig(*promConfig).ProcessEngineResponses(engineResponses, op) + }) } -func registerPolicyExecutionDurationMetricValidate(promConfig *metrics.PromConfig, logger logr.Logger, requestOperation string, policy v1.PolicyInterface, engineResponse response.EngineResponse) { - resourceRequestOperationPromAlias, err := policyExecutionDuration.ParseResourceRequestOperation(requestOperation) - if err != nil { - logger.Error(err, "error occurred while registering kyverno_policy_execution_duration_seconds metrics for the above policy", "name", policy.GetName()) - } - if err := policyExecutionDuration.ParsePromConfig(*promConfig).ProcessEngineResponse(policy, engineResponse, metrics.AdmissionRequest, "", resourceRequestOperationPromAlias); err != nil { - logger.Error(err, "error occurred while registering kyverno_policy_execution_duration_seconds metrics for the above policy", "name", policy.GetName()) - } +// POLICY RESULTS + +func (ws *WebhookServer) registerPolicyResultsMetricMutation(logger logr.Logger, requestOperation string, policy kyverno.PolicyInterface, engineResponse response.EngineResponse) { + registerMetric(logger, "kyverno_policy_results_total", requestOperation, func(op metrics.ResourceRequestOperation) error { + return policyResults.ParsePromConfig(*ws.promConfig).ProcessEngineResponse(policy, engineResponse, metrics.AdmissionRequest, op) + }) } -func registerAdmissionReviewDurationMetricValidate(promConfig *metrics.PromConfig, logger logr.Logger, requestOperation string, engineResponses []*response.EngineResponse, admissionReviewLatencyDuration int64) { - resourceRequestOperationPromAlias, err := admissionReviewDuration.ParseResourceRequestOperation(requestOperation) - if err != nil { - logger.Error(err, "error occurred while registering kyverno_admission_review_duration_seconds metrics") - } - if err := admissionReviewDuration.ParsePromConfig(*promConfig).ProcessEngineResponses(engineResponses, admissionReviewLatencyDuration, resourceRequestOperationPromAlias); err != nil { - logger.Error(err, "error occurred while registering kyverno_admission_review_duration_seconds metrics") - } +func registerPolicyResultsMetricValidation(logger logr.Logger, promConfig *metrics.PromConfig, requestOperation string, policy v1.PolicyInterface, engineResponse response.EngineResponse) { + registerMetric(logger, "kyverno_policy_results_total", requestOperation, func(op metrics.ResourceRequestOperation) error { + return policyResults.ParsePromConfig(*promConfig).ProcessEngineResponse(policy, engineResponse, metrics.AdmissionRequest, op) + }) } -func registerAdmissionRequestsMetricValidate(promConfig *metrics.PromConfig, logger logr.Logger, requestOperation string, engineResponses []*response.EngineResponse) { - resourceRequestOperationPromAlias, err := admissionRequests.ParseResourceRequestOperation(requestOperation) - if err != nil { - logger.Error(err, "error occurred while registering kyverno_admission_requests_total metrics") - } - if err := admissionRequests.ParsePromConfig(*promConfig).ProcessEngineResponses(engineResponses, resourceRequestOperationPromAlias); err != nil { - logger.Error(err, "error occurred while registering kyverno_admission_requests_total metrics") - } +func (ws *WebhookServer) registerPolicyResultsMetricGeneration(logger logr.Logger, requestOperation string, policy kyverno.PolicyInterface, engineResponse response.EngineResponse) { + registerMetric(logger, "kyverno_policy_results_total", requestOperation, func(op metrics.ResourceRequestOperation) error { + return policyResults.ParsePromConfig(*ws.promConfig).ProcessEngineResponse(policy, engineResponse, metrics.AdmissionRequest, op) + }) } -func (ws *WebhookServer) registerPolicyResultsMetricMutation(logger logr.Logger, resourceRequestOperation string, policy kyverno.PolicyInterface, engineResponse response.EngineResponse) { - resourceRequestOperationPromAlias, err := policyResults.ParseResourceRequestOperation(resourceRequestOperation) - if err != nil { - logger.Error(err, "error occurred while registering kyverno_policy_results_total metrics for the above policy", "name", policy.GetName()) - } - if err := policyResults.ParsePromConfig(*ws.promConfig).ProcessEngineResponse(policy, engineResponse, metrics.AdmissionRequest, resourceRequestOperationPromAlias); err != nil { - logger.Error(err, "error occurred while registering kyverno_policy_results_total metrics for the above policy", "name", policy.GetName()) - } +// POLICY EXECUTION + +func (ws *WebhookServer) registerPolicyExecutionDurationMetricMutate(logger logr.Logger, requestOperation string, policy kyverno.PolicyInterface, engineResponse response.EngineResponse) { + registerMetric(logger, "kyverno_policy_execution_duration_seconds", requestOperation, func(op metrics.ResourceRequestOperation) error { + return policyExecutionDuration.ParsePromConfig(*ws.promConfig).ProcessEngineResponse(policy, engineResponse, metrics.AdmissionRequest, "", op) + }) } -func (ws *WebhookServer) registerPolicyExecutionDurationMetricMutate(logger logr.Logger, resourceRequestOperation string, policy kyverno.PolicyInterface, engineResponse response.EngineResponse) { - resourceRequestOperationPromAlias, err := policyExecutionDuration.ParseResourceRequestOperation(resourceRequestOperation) - if err != nil { - logger.Error(err, "error occurred while registering kyverno_policy_execution_duration_seconds metrics for the above policy", "name", policy.GetName()) - } - if err := policyExecutionDuration.ParsePromConfig(*ws.promConfig).ProcessEngineResponse(policy, engineResponse, metrics.AdmissionRequest, "", resourceRequestOperationPromAlias); err != nil { - logger.Error(err, "error occurred while registering kyverno_policy_execution_duration_seconds metrics for the above policy", "name", policy.GetName()) - } +func registerPolicyExecutionDurationMetricValidate(logger logr.Logger, promConfig *metrics.PromConfig, requestOperation string, policy v1.PolicyInterface, engineResponse response.EngineResponse) { + registerMetric(logger, "kyverno_policy_execution_duration_seconds", requestOperation, func(op metrics.ResourceRequestOperation) error { + return policyExecutionDuration.ParsePromConfig(*promConfig).ProcessEngineResponse(policy, engineResponse, metrics.AdmissionRequest, "", op) + }) +} + +func (ws *WebhookServer) registerPolicyExecutionDurationMetricGenerate(logger logr.Logger, requestOperation string, policy kyverno.PolicyInterface, engineResponse response.EngineResponse) { + registerMetric(logger, "kyverno_policy_execution_duration_seconds", requestOperation, func(op metrics.ResourceRequestOperation) error { + return policyExecutionDuration.ParsePromConfig(*ws.promConfig).ProcessEngineResponse(policy, engineResponse, metrics.AdmissionRequest, "", op) + }) } diff --git a/pkg/webhooks/mutation.go b/pkg/webhooks/mutation.go index 0b205f854a..066e439884 100644 --- a/pkg/webhooks/mutation.go +++ b/pkg/webhooks/mutation.go @@ -26,8 +26,8 @@ func (ws *WebhookServer) applyMutatePolicies(request *v1beta1.AdmissionRequest, logger.V(6).Info("", "generated patches", string(mutatePatches)) admissionReviewLatencyDuration := int64(time.Since(time.Unix(ts, 0))) - go registerAdmissionReviewDurationMetricMutate(logger, *ws.promConfig, string(request.Operation), mutateEngineResponses, admissionReviewLatencyDuration) - go registerAdmissionRequestsMetricMutate(logger, *ws.promConfig, string(request.Operation), mutateEngineResponses) + go ws.registerAdmissionReviewDurationMetricMutate(logger, string(request.Operation), mutateEngineResponses, admissionReviewLatencyDuration) + go ws.registerAdmissionRequestsMetricMutate(logger, string(request.Operation), mutateEngineResponses) return mutatePatches } diff --git a/pkg/webhooks/validation.go b/pkg/webhooks/validation.go index 6da6a585a8..2ec4257738 100644 --- a/pkg/webhooks/validation.go +++ b/pkg/webhooks/validation.go @@ -65,9 +65,9 @@ func (v *validationHandler) handleValidation( } // registering the kyverno_policy_results_total metric concurrently - go registerPolicyResultsMetricValidation(promConfig, logger, string(request.Operation), policyContext.Policy, *engineResponse) + go registerPolicyResultsMetricValidation(logger, promConfig, string(request.Operation), policyContext.Policy, *engineResponse) // registering the kyverno_policy_execution_duration_seconds metric concurrently - go registerPolicyExecutionDurationMetricValidate(promConfig, logger, string(request.Operation), policyContext.Policy, *engineResponse) + go registerPolicyExecutionDurationMetricValidate(logger, promConfig, string(request.Operation), policyContext.Policy, *engineResponse) engineResponses = append(engineResponses, engineResponse) if !engineResponse.IsSuccessful() { @@ -101,9 +101,9 @@ func (v *validationHandler) handleValidation( logger.V(4).Info("resource blocked") //registering the kyverno_admission_review_duration_seconds metric concurrently admissionReviewLatencyDuration := int64(time.Since(time.Unix(admissionRequestTimestamp, 0))) - go registerAdmissionReviewDurationMetricValidate(promConfig, logger, string(request.Operation), engineResponses, admissionReviewLatencyDuration) + go registerAdmissionReviewDurationMetricValidate(logger, promConfig, string(request.Operation), engineResponses, admissionReviewLatencyDuration) //registering the kyverno_admission_requests_total metric concurrently - go registerAdmissionRequestsMetricValidate(promConfig, logger, string(request.Operation), engineResponses) + go registerAdmissionRequestsMetricValidate(logger, promConfig, string(request.Operation), engineResponses) return false, getEnforceFailureErrorMsg(engineResponses) } @@ -130,10 +130,10 @@ func (v *validationHandler) handleValidation( //registering the kyverno_admission_review_duration_seconds metric concurrently admissionReviewLatencyDuration := int64(time.Since(time.Unix(admissionRequestTimestamp, 0))) - go registerAdmissionReviewDurationMetricValidate(promConfig, logger, string(request.Operation), engineResponses, admissionReviewLatencyDuration) + go registerAdmissionReviewDurationMetricValidate(logger, promConfig, string(request.Operation), engineResponses, admissionReviewLatencyDuration) //registering the kyverno_admission_requests_total metric concurrently - go registerAdmissionRequestsMetricValidate(promConfig, logger, string(request.Operation), engineResponses) + go registerAdmissionRequestsMetricValidate(logger, promConfig, string(request.Operation), engineResponses) return true, "" }