1
0
Fork 0
mirror of https://github.com/kyverno/kyverno.git synced 2025-03-09 09:26:54 +00:00
kyverno/pkg/policyviolation/builder.go

80 lines
2.2 KiB
Go
Raw Normal View History

2019-11-26 18:07:15 -08:00
package policyviolation
import (
"fmt"
kyverno "github.com/nirmata/kyverno/pkg/api/kyverno/v1"
client "github.com/nirmata/kyverno/pkg/dclient"
)
// Builder builds Policy Violation struct
// this is base type of namespaced and cluster policy violation
type Builder interface {
2019-12-12 16:35:37 -08:00
generate(info Info) []kyverno.PolicyViolationTemplate
build(policy, kind, namespace, name string, rules []kyverno.ViolatedRule) *kyverno.PolicyViolationTemplate
2019-11-26 18:07:15 -08:00
}
type pvBuilder struct {
// dynamic client
dclient *client.Client
}
func newPvBuilder(dclient *client.Client) *pvBuilder {
pvb := pvBuilder{
dclient: dclient,
}
return &pvb
}
2019-12-12 16:35:37 -08:00
func (pvb *pvBuilder) generate(info Info) []kyverno.PolicyViolationTemplate {
2019-11-26 18:07:15 -08:00
var owners []kyverno.ResourceSpec
2019-12-03 17:15:50 -08:00
// get the owners if the resource is blocked or
2019-12-11 11:18:38 -08:00
// TODO: https://github.com/nirmata/kyverno/issues/535
if info.Blocked {
2019-11-26 18:07:15 -08:00
// get resource owners
owners = GetOwners(pvb.dclient, info.Resource)
}
pvs := pvb.buildPolicyViolations(owners, info)
return pvs
}
2019-12-12 16:35:37 -08:00
func (pvb *pvBuilder) buildPolicyViolations(owners []kyverno.ResourceSpec, info Info) []kyverno.PolicyViolationTemplate {
var pvs []kyverno.PolicyViolationTemplate
2019-11-26 18:07:15 -08:00
if len(owners) != 0 {
// there are resource owners
// generate PV on them
for _, resource := range owners {
2019-12-02 17:15:47 -08:00
pv := pvb.build(info.PolicyName, resource.Kind, resource.Namespace, resource.Name, info.Rules)
2019-11-26 18:07:15 -08:00
pvs = append(pvs, *pv)
}
} else {
// generate PV on resource
pv := pvb.build(info.PolicyName, info.Resource.GetKind(), info.Resource.GetNamespace(), info.Resource.GetName(), info.Rules)
pvs = append(pvs, *pv)
}
return pvs
}
2019-12-12 16:35:37 -08:00
func (pvb *pvBuilder) build(policy, kind, namespace, name string, rules []kyverno.ViolatedRule) *kyverno.PolicyViolationTemplate {
pv := &kyverno.PolicyViolationTemplate{
2019-11-26 18:07:15 -08:00
Spec: kyverno.PolicyViolationSpec{
Policy: policy,
ResourceSpec: kyverno.ResourceSpec{
Kind: kind,
Name: name,
Namespace: namespace,
},
ViolatedRules: rules,
},
}
labelMap := map[string]string{
"policy": pv.Spec.Policy,
"resource": pv.Spec.ToKey(),
}
pv.SetLabels(labelMap)
2019-12-02 17:15:47 -08:00
if namespace != "" {
pv.SetNamespace(namespace)
}
2019-11-26 18:07:15 -08:00
pv.SetGenerateName(fmt.Sprintf("%s-", policy))
return pv
}