2021-05-15 18:48:38 +05:30
package policychanges
import (
2022-11-28 11:30:14 +01:00
"context"
2021-05-15 18:48:38 +05:30
"fmt"
2021-06-14 13:42:57 -07:00
2022-05-17 13:12:43 +02:00
kyvernov1 "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
)
2022-04-06 20:14:13 +02:00
func registerPolicyChangesMetric (
2022-11-28 11:30:14 +01:00
ctx context . Context ,
2022-07-11 23:19:47 +05:30
m * metrics . MetricsConfig ,
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 = "-"
}
2022-07-11 23:19:47 +05:30
includeNamespaces , excludeNamespaces := m . Config . GetIncludeNamespaces ( ) , m . Config . GetExcludeNamespaces ( )
2022-04-04 17:31:33 +02:00
if ( policyNamespace != "" && policyNamespace != "-" ) && utils . ContainsString ( excludeNamespaces , policyNamespace ) {
2022-08-18 18:54:59 +05:30
m . Log . V ( 2 ) . 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-08-18 18:54:59 +05:30
m . Log . V ( 2 ) . 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
}
2022-07-11 23:19:47 +05:30
2022-11-28 11:30:14 +01:00
m . RecordPolicyChanges ( ctx , policyValidationMode , policyType , policyBackgroundMode , policyNamespace , policyName , string ( policyChangeType ) )
2022-07-11 23:19:47 +05:30
2021-05-15 18:48:38 +05:30
return nil
}
2022-11-28 11:30:14 +01:00
func RegisterPolicy ( ctx context . Context , m * metrics . MetricsConfig , policy kyvernov1 . PolicyInterface , policyChangeType PolicyChangeType ) error {
2022-04-06 20:14:13 +02:00
name , namespace , policyType , backgroundMode , validationMode , err := metrics . GetPolicyInfos ( policy )
if err != nil {
return err
2021-05-15 18:48:38 +05:30
}
2022-11-28 11:30:14 +01:00
if err = registerPolicyChangesMetric ( ctx , m , validationMode , policyType , backgroundMode , namespace , name , policyChangeType ) ; err != nil {
2022-04-06 20:14:13 +02:00
return err
}
return nil
2021-05-15 18:48:38 +05:30
}