generated from giantswarm/template-app
/
policyexception_controller.go
183 lines (152 loc) · 6.13 KB
/
policyexception_controller.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
/*
Copyright 2023.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package controller
import (
"context"
"fmt"
"k8s.io/apimachinery/pkg/api/errors"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
kyvernov2beta1 "github.com/kyverno/kyverno/api/kyverno/v2beta1"
"k8s.io/apimachinery/pkg/types"
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
giantswarmPolicy "github.com/giantswarm/kyverno-policy-operator/api/v1alpha1"
"github.com/go-logr/logr"
"k8s.io/apimachinery/pkg/runtime"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/log"
)
// PolicyExceptionReconciler reconciles a PolicyException object
type PolicyExceptionReconciler struct {
client.Client
Scheme *runtime.Scheme
Log logr.Logger
DestinationNamespace string
Background bool
}
//+kubebuilder:rbac:groups=policy.giantswarm.io,resources=policyexceptions,verbs=get;list;watch;create;update;patch;delete
//+kubebuilder:rbac:groups=policy.giantswarm.io,resources=policyexceptions/status,verbs=get;update;patch
//+kubebuilder:rbac:groups=policy.giantswarm.io,resources=policyexceptions/finalizers,verbs=update
func (r *PolicyExceptionReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
_ = log.FromContext(ctx)
_ = r.Log.WithValues("policyexception", req.NamespacedName)
var gsPolicyException giantswarmPolicy.PolicyException
if err := r.Get(ctx, req.NamespacedName, &gsPolicyException); err != nil {
// Error fetching the report
// Check if the PolicyException was deleted
if apierrors.IsNotFound(err) {
// Ignore
return ctrl.Result{}, nil
}
log.Log.Error(err, "unable to fetch PolicyException")
return ctrl.Result{}, client.IgnoreNotFound(err)
}
// Define namespace
var namespace string
if r.DestinationNamespace == "" {
namespace = gsPolicyException.Namespace
} else {
namespace = r.DestinationNamespace
}
// Create Kyverno exception
// Create a policy map for storing cluster policies to extract rules later
// TODO: Take this block out and move it to utils
policyMap := make(map[string]kyvernov1.ClusterPolicy)
for _, policy := range gsPolicyException.Spec.Policies {
var kyvernoPolicy kyvernov1.ClusterPolicy
if err := r.Get(ctx, types.NamespacedName{Namespace: "", Name: policy}, &kyvernoPolicy); err != nil {
// Error fetching the report
log.Log.Error(err, "unable to fetch Kyverno Policy")
return ctrl.Result{}, client.IgnoreNotFound(err)
}
policyMap[policy] = kyvernoPolicy
}
// Translate GiantSwarm PolicyException to Kyverno's PolicyException schema
policyException := kyvernov2beta1.PolicyException{}
// Set namespace
policyException.Namespace = namespace
// Set name
policyException.Name = gsPolicyException.Name
// Set labels
policyException.Labels = make(map[string]string)
policyException.Labels["app.kubernetes.io/managed-by"] = "kyverno-policy-operator"
// Set ownerReferences
if err := controllerutil.SetControllerReference(&gsPolicyException, &policyException, r.Scheme); err != nil {
return ctrl.Result{}, err
}
// Create PolicyException
if op, err := controllerutil.CreateOrUpdate(ctx, r.Client, &policyException, func() error {
// Set Background behaviour
policyException.Spec.Background = &r.Background
// Set .Spec.Match.Any targets
policyException.Spec.Match.Any = translateTargetsToResourceFilters(gsPolicyException)
// Set .Spec.Exceptions
newExceptions := translatePoliciesToExceptions(policyMap)
if !unorderedEqual(policyException.Spec.Exceptions, newExceptions) {
policyException.Spec.Exceptions = newExceptions
}
return nil
}); err != nil {
log.Log.Error(err, fmt.Sprintf("Reconciliation failed for PolicyException %s", policyException.Name))
return ctrl.Result{}, err
} else {
log.Log.Info(fmt.Sprintf("PolicyException %s: %s", policyException.Name, op))
}
return ctrl.Result{}, nil
}
// CreateOrUpdate attempts first to patch the object given but if an IsNotFound error
// is returned it instead creates the resource.
func (r *PolicyExceptionReconciler) CreateOrUpdate(ctx context.Context, obj client.Object) error {
existingObj := unstructured.Unstructured{}
existingObj.SetGroupVersionKind(obj.GetObjectKind().GroupVersionKind())
err := r.Get(ctx, client.ObjectKeyFromObject(obj), &existingObj)
switch {
case err == nil:
// Update:
obj.SetResourceVersion(existingObj.GetResourceVersion())
obj.SetUID(existingObj.GetUID())
return r.Patch(ctx, obj, client.MergeFrom(existingObj.DeepCopy()))
case errors.IsNotFound(err):
// Create:
return r.Create(ctx, obj)
default:
return err
}
}
// generateKinds creates the subresources necessary for top level controllers like Deployment or StatefulSet
func generateExceptionKinds(resourceKind string) []string {
// Adds the subresources to the exception list for each Kind
var exceptionKinds []string
exceptionKinds = append(exceptionKinds, resourceKind)
// Append ReplicaSets
if resourceKind == "Deployment" {
exceptionKinds = append(exceptionKinds, "ReplicaSet")
// Append Jobs
} else if resourceKind == "CronJob" {
exceptionKinds = append(exceptionKinds, "Job")
}
// Always append Pods except if they are the initial resource Kind
if resourceKind != "Pod" {
exceptionKinds = append(exceptionKinds, "Pod")
}
return exceptionKinds
}
// SetupWithManager sets up the controller with the Manager.
func (r *PolicyExceptionReconciler) SetupWithManager(mgr ctrl.Manager) error {
return ctrl.NewControllerManagedBy(mgr).
For(&giantswarmPolicy.PolicyException{}).
Owns(&kyvernov2beta1.PolicyException{}).
Complete(r)
}