-
Notifications
You must be signed in to change notification settings - Fork 776
/
Copy pathconstrainttemplatestatus_controller.go
217 lines (189 loc) Β· 7.57 KB
/
constrainttemplatestatus_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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
/*
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 constrainttemplatestatus
import (
"context"
"encoding/json"
"fmt"
"sort"
"github.com/go-logr/logr"
constrainttemplatev1beta1 "github.com/open-policy-agent/frameworks/constraint/pkg/apis/templates/v1beta1"
constraintclient "github.com/open-policy-agent/frameworks/constraint/pkg/client"
"github.com/open-policy-agent/gatekeeper/v3/apis/status/v1beta1"
"github.com/open-policy-agent/gatekeeper/v3/pkg/logging"
"github.com/open-policy-agent/gatekeeper/v3/pkg/operations"
"github.com/open-policy-agent/gatekeeper/v3/pkg/util"
"github.com/open-policy-agent/gatekeeper/v3/pkg/watch"
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller"
"sigs.k8s.io/controller-runtime/pkg/handler"
logf "sigs.k8s.io/controller-runtime/pkg/log"
"sigs.k8s.io/controller-runtime/pkg/manager"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
"sigs.k8s.io/controller-runtime/pkg/source"
)
var log = logf.Log.WithName("controller").WithValues(logging.Process, "constraint_template_status_controller")
type Adder struct {
CfClient *constraintclient.Client
WatchManager *watch.Manager
}
// Add creates a new Constraint Status Controller and adds it to the Manager. The Manager will set fields on the Controller
// and Start it when the Manager is Started.
func (a *Adder) Add(mgr manager.Manager) error {
if !operations.IsAssigned(operations.Status) {
return nil
}
r := newReconciler(mgr)
return add(mgr, r)
}
// newReconciler returns a new reconcile.Reconciler.
func newReconciler(
mgr manager.Manager,
) reconcile.Reconciler {
return &ReconcileConstraintStatus{
// Separate reader and writer because manager's default client bypasses the cache for unstructured resources.
writer: mgr.GetClient(),
statusClient: mgr.GetClient(),
reader: mgr.GetCache(),
scheme: mgr.GetScheme(),
log: log,
}
}
// PodStatusToConstraintTemplateMapper correlates a ConstraintTemplatePodStatus with its corresponding constraint template
// `selfOnly` tells the mapper to only map statuses corresponding to the current pod.
func PodStatusToConstraintTemplateMapper(selfOnly bool) handler.TypedMapFunc[*v1beta1.ConstraintTemplatePodStatus] {
return func(_ context.Context, obj *v1beta1.ConstraintTemplatePodStatus) []reconcile.Request {
labels := obj.GetLabels()
name, ok := labels[v1beta1.ConstraintTemplateNameLabel]
if !ok {
log.Error(fmt.Errorf("constraint template status resource with no mapping label: %s", obj.GetName()), "missing label while attempting to map a constraint template status resource")
return nil
}
if selfOnly {
pod, ok := labels[v1beta1.PodLabel]
if !ok {
log.Error(fmt.Errorf("constraint template status resource with no pod label: %s", obj.GetName()), "missing label while attempting to map a constraint template status resource")
}
// Do not attempt to reconcile the resource when other pods have changed their status
if pod != util.GetPodName() {
return nil
}
}
return []reconcile.Request{{NamespacedName: types.NamespacedName{Name: name}}}
}
}
// add adds a new Controller to mgr with r as the reconcile.Reconciler.
func add(mgr manager.Manager, r reconcile.Reconciler) error {
// Create a new controller
c, err := controller.New("constraint-template-status-controller", mgr, controller.Options{Reconciler: r})
if err != nil {
return err
}
// Watch for changes to ConstraintTemplateStatus
err = c.Watch(
source.Kind(mgr.GetCache(), &v1beta1.ConstraintTemplatePodStatus{}, handler.TypedEnqueueRequestsFromMapFunc(PodStatusToConstraintTemplateMapper(false))))
if err != nil {
return err
}
// Watch for changes to the provided constraint
// Watch for changes to ConstraintTemplate
err = c.Watch(source.Kind(mgr.GetCache(), &constrainttemplatev1beta1.ConstraintTemplate{}, &handler.TypedEnqueueRequestForObject[*constrainttemplatev1beta1.ConstraintTemplate]{}))
if err != nil {
return err
}
return nil
}
var _ reconcile.Reconciler = &ReconcileConstraintStatus{}
// ReconcileConstraintStatus reconciles an arbitrary constraint object described by Kind.
type ReconcileConstraintStatus struct {
reader client.Reader
writer client.Writer
statusClient client.StatusClient
scheme *runtime.Scheme
log logr.Logger
}
// +kubebuilder:rbac:groups=constraints.gatekeeper.sh,resources=*,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=status.gatekeeper.sh,resources=*,verbs=get;list;watch;create;update;patch;delete
// Reconcile reads that state of the cluster for a constraint object and makes changes based on the state read
// and what is in the constraint.Spec.
func (r *ReconcileConstraintStatus) Reconcile(ctx context.Context, request reconcile.Request) (reconcile.Result, error) {
template := &unstructured.Unstructured{}
gv := constrainttemplatev1beta1.SchemeGroupVersion
template.SetGroupVersionKind(gv.WithKind("ConstraintTemplate"))
if err := r.reader.Get(ctx, request.NamespacedName, template); err != nil {
// If the template does not exist, we are done
if errors.IsNotFound(err) {
return reconcile.Result{}, nil
}
return reconcile.Result{}, err
}
r.log.Info("handling constraint template status update", "instance", template)
sObjs := &v1beta1.ConstraintTemplatePodStatusList{}
if err := r.reader.List(
ctx,
sObjs,
client.MatchingLabels{v1beta1.ConstraintTemplateNameLabel: request.Name},
client.InNamespace(util.GetNamespace()),
); err != nil {
return reconcile.Result{}, err
}
statusObjs := make(sortableStatuses, len(sObjs.Items))
copy(statusObjs, sObjs.Items)
sort.Sort(statusObjs)
var s []interface{}
// created is true if at least one Pod hasn't reported any errors
var created bool
for i := range statusObjs {
// Don't report status if it's not for the correct object. This can happen
// if a watch gets interrupted, causing the constraint status to be deleted
// out from underneath it
if statusObjs[i].Status.TemplateUID != template.GetUID() {
continue
}
if len(statusObjs[i].Status.Errors) == 0 {
created = true
}
j, err := json.Marshal(statusObjs[i].Status)
if err != nil {
return reconcile.Result{}, err
}
var o map[string]interface{}
if err := json.Unmarshal(j, &o); err != nil {
return reconcile.Result{}, err
}
s = append(s, o)
}
if err := unstructured.SetNestedSlice(template.Object, s, "status", "byPod"); err != nil {
return reconcile.Result{}, err
}
if err := unstructured.SetNestedField(template.Object, created, "status", "created"); err != nil {
return reconcile.Result{}, err
}
if err := r.statusClient.Status().Update(ctx, template); err != nil {
return reconcile.Result{Requeue: true}, nil
}
return reconcile.Result{}, nil
}
type sortableStatuses []v1beta1.ConstraintTemplatePodStatus
func (s sortableStatuses) Len() int {
return len(s)
}
func (s sortableStatuses) Less(i, j int) bool {
return s[i].Status.ID < s[j].Status.ID
}
func (s sortableStatuses) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}