2022-11-16 18:41:33 +05:30
|
|
|
package admission
|
2022-11-14 15:13:32 +05:30
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"fmt"
|
|
|
|
|
2023-08-02 20:17:40 +05:30
|
|
|
"github.com/kyverno/kyverno/api/kyverno"
|
2022-12-08 12:45:47 +01:00
|
|
|
kyvernov2alpha1 "github.com/kyverno/kyverno/api/kyverno/v2alpha1"
|
2022-11-14 15:13:32 +05:30
|
|
|
admissionv1 "k8s.io/api/admission/v1"
|
|
|
|
)
|
|
|
|
|
2022-12-08 12:45:47 +01:00
|
|
|
func UnmarshalCleanupPolicy(kind string, raw []byte) (kyvernov2alpha1.CleanupPolicyInterface, error) {
|
2022-11-14 15:13:32 +05:30
|
|
|
if kind == "CleanupPolicy" {
|
2022-12-08 12:45:47 +01:00
|
|
|
var policy *kyvernov2alpha1.CleanupPolicy
|
2022-11-14 15:13:32 +05:30
|
|
|
if err := json.Unmarshal(raw, &policy); err != nil {
|
2022-11-16 18:41:33 +05:30
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return policy, nil
|
|
|
|
} else if kind == "ClusterCleanupPolicy" {
|
2022-12-08 12:45:47 +01:00
|
|
|
var policy *kyvernov2alpha1.ClusterCleanupPolicy
|
2022-11-16 18:41:33 +05:30
|
|
|
if err := json.Unmarshal(raw, &policy); err != nil {
|
|
|
|
return nil, err
|
2022-11-14 15:13:32 +05:30
|
|
|
}
|
|
|
|
return policy, nil
|
|
|
|
}
|
2022-11-16 18:41:33 +05:30
|
|
|
return nil, fmt.Errorf("admission request does not contain a cleanuppolicy")
|
2022-11-14 15:13:32 +05:30
|
|
|
}
|
|
|
|
|
2023-04-04 07:11:18 +02:00
|
|
|
func GetCleanupPolicies(request admissionv1.AdmissionRequest) (kyvernov2alpha1.CleanupPolicyInterface, kyvernov2alpha1.CleanupPolicyInterface, error) {
|
2022-12-08 12:45:47 +01:00
|
|
|
var emptypolicy kyvernov2alpha1.CleanupPolicyInterface
|
2022-11-14 15:13:32 +05:30
|
|
|
policy, err := UnmarshalCleanupPolicy(request.Kind.Kind, request.Object.Raw)
|
|
|
|
if err != nil {
|
|
|
|
return policy, emptypolicy, err
|
|
|
|
}
|
|
|
|
if request.Operation == admissionv1.Update {
|
|
|
|
oldPolicy, err := UnmarshalCleanupPolicy(request.Kind.Kind, request.OldObject.Raw)
|
|
|
|
return policy, oldPolicy, err
|
|
|
|
}
|
|
|
|
return policy, emptypolicy, nil
|
|
|
|
}
|
2023-08-02 20:17:40 +05:30
|
|
|
|
|
|
|
// UnmarshalTTLLabel extracts the cleanup.kyverno.io/ttl label value from the raw admission request.
|
|
|
|
func GetTtlLabel(raw []byte) (string, error) {
|
|
|
|
var resourceObj map[string]interface{}
|
|
|
|
if err := json.Unmarshal(raw, &resourceObj); err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
|
|
|
|
metadata, found := resourceObj["metadata"].(map[string]interface{})
|
|
|
|
if !found {
|
|
|
|
return "", fmt.Errorf("resource has no metadata field")
|
|
|
|
}
|
|
|
|
|
|
|
|
labels, found := metadata["labels"].(map[string]interface{})
|
|
|
|
if !found {
|
|
|
|
return "", fmt.Errorf("resource has no labels field")
|
|
|
|
}
|
|
|
|
|
|
|
|
ttlValue, found := labels[kyverno.LabelCleanupTtl].(string)
|
|
|
|
if !found {
|
|
|
|
return "", fmt.Errorf("resource has no %s label", kyverno.LabelCleanupTtl)
|
|
|
|
}
|
|
|
|
|
|
|
|
return ttlValue, nil
|
|
|
|
}
|