2021-05-15 18:48:38 +05:30
package policychanges
import (
"fmt"
2021-06-14 13:42:57 -07:00
2021-10-29 18:13:20 +02:00
kyverno "github.com/kyverno/kyverno/api/kyverno/v1"
2021-05-15 18:48:38 +05:30
"github.com/kyverno/kyverno/pkg/metrics"
2022-04-04 17:31:33 +02:00
"github.com/kyverno/kyverno/pkg/utils"
2021-05-15 18:48:38 +05:30
prom "github.com/prometheus/client_golang/prometheus"
)
2022-04-06 20:14:13 +02:00
func registerPolicyChangesMetric (
pc * metrics . PromConfig ,
2021-05-15 18:48:38 +05:30
policyValidationMode metrics . PolicyValidationMode ,
policyType metrics . PolicyType ,
policyBackgroundMode metrics . PolicyBackgroundMode ,
policyNamespace , policyName string ,
policyChangeType PolicyChangeType ,
) error {
if policyType == metrics . Cluster {
policyNamespace = "-"
}
2021-09-11 03:09:12 +05:30
includeNamespaces , excludeNamespaces := pc . Config . GetIncludeNamespaces ( ) , pc . Config . GetExcludeNamespaces ( )
2022-04-04 17:31:33 +02:00
if ( policyNamespace != "" && policyNamespace != "-" ) && utils . ContainsString ( excludeNamespaces , policyNamespace ) {
2022-04-29 19:33:08 +02:00
metrics . Logger ( ) . Info ( fmt . Sprintf ( "Skipping the registration of kyverno_policy_changes_total metric as the operation belongs to the namespace '%s' which is one of 'namespaces.exclude' %+v in values.yaml" , policyNamespace , excludeNamespaces ) )
2021-09-11 03:09:12 +05:30
return nil
}
2022-04-04 17:31:33 +02:00
if ( policyNamespace != "" && policyNamespace != "-" ) && len ( includeNamespaces ) > 0 && ! utils . ContainsString ( includeNamespaces , policyNamespace ) {
2022-04-29 19:33:08 +02:00
metrics . Logger ( ) . Info ( fmt . Sprintf ( "Skipping the registration of kyverno_policy_changes_total metric as the operation belongs to the namespace '%s' which is not one of 'namespaces.include' %+v in values.yaml" , policyNamespace , includeNamespaces ) )
2021-09-11 03:09:12 +05:30
return nil
}
pc . Metrics . PolicyChanges . With ( prom . Labels {
2021-05-15 18:48:38 +05:30
"policy_validation_mode" : string ( policyValidationMode ) ,
"policy_type" : string ( policyType ) ,
"policy_background_mode" : string ( policyBackgroundMode ) ,
"policy_namespace" : policyNamespace ,
"policy_name" : policyName ,
"policy_change_type" : string ( policyChangeType ) ,
2021-07-23 21:46:50 +05:30
} ) . Inc ( )
2021-05-15 18:48:38 +05:30
return nil
}
2022-04-06 20:14:13 +02:00
func RegisterPolicy ( pc * metrics . PromConfig , policy kyverno . PolicyInterface , policyChangeType PolicyChangeType ) error {
name , namespace , policyType , backgroundMode , validationMode , err := metrics . GetPolicyInfos ( policy )
if err != nil {
return err
2021-05-15 18:48:38 +05:30
}
2022-04-06 20:14:13 +02:00
if err = registerPolicyChangesMetric ( pc , validationMode , policyType , backgroundMode , namespace , name , policyChangeType ) ; err != nil {
return err
}
return nil
2021-05-15 18:48:38 +05:30
}