-
Notifications
You must be signed in to change notification settings - Fork 24
/
watcher.go
267 lines (233 loc) · 8.72 KB
/
watcher.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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
package crwatcher
import (
"bytes"
"context"
"encoding/json"
"fmt"
"os"
"sync"
"time"
"github.com/cenkalti/backoff/v4"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
clientgoscheme "k8s.io/client-go/kubernetes/scheme"
"k8s.io/client-go/tools/record"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/event"
"sigs.k8s.io/controller-runtime/pkg/predicate"
languagev1 "github.com/fluxninja/aperture/v2/api/gen/proto/go/aperture/policy/language/v1"
"github.com/fluxninja/aperture/v2/operator/api"
policyv1alpha1 "github.com/fluxninja/aperture/v2/operator/api/policy/v1alpha1"
"github.com/fluxninja/aperture/v2/pkg/config"
"github.com/fluxninja/aperture/v2/pkg/log"
"github.com/fluxninja/aperture/v2/pkg/notifiers"
panichandler "github.com/fluxninja/aperture/v2/pkg/panic-handler"
"github.com/fluxninja/aperture/v2/pkg/policies/controlplane/iface"
)
// watcher holds the state of the watcher.
type watcher struct {
waitGroup sync.WaitGroup
notifiers.Trackers
policyDynamicConfigTrackers notifiers.Trackers
ctx context.Context
cancel context.CancelFunc
client.Client
scheme *runtime.Scheme
recorder record.EventRecorder
resourcesDeleted map[types.NamespacedName]bool
}
// Make sure Watcher implements notifiers.Watcher interface.
var _ notifiers.Watcher = &watcher{}
// NewWatcher prepares watcher instance for the Kuberneter Policy.
func NewWatcher(policyTrackers, policyDynamicConfigTrackers notifiers.Trackers) (*watcher, error) {
ctx, cancel := context.WithCancel(context.Background())
watcher := &watcher{
Trackers: policyTrackers,
policyDynamicConfigTrackers: policyDynamicConfigTrackers,
ctx: ctx,
cancel: cancel,
}
return watcher, nil
}
// Start starts the watcher go routines and handles Policy Custom resource events from Kubernetes.
func (w *watcher) Start() error {
w.waitGroup.Add(1)
panichandler.Go(func() {
defer w.waitGroup.Done()
operation := func() error {
scheme := runtime.NewScheme()
utilruntime.Must(clientgoscheme.AddToScheme(scheme))
utilruntime.Must(api.AddToScheme(scheme))
mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{
Scheme: scheme,
MetricsBindAddress: "0",
LeaderElection: false,
Namespace: os.Getenv("APERTURE_CONTROLLER_NAMESPACE"),
})
if err != nil {
log.Error().Err(err).Msg("Failed to create Kubernetes Reconciler for Policy")
return nil
}
w.Client = mgr.GetClient()
w.scheme = scheme
w.recorder = mgr.GetEventRecorderFor("aperture-policy")
if err = w.SetupWithManager(mgr); err != nil {
log.Error().Err(err).Msg("Failed to create Kubernetes controller for policy")
return nil
}
return mgr.Start(w.ctx)
}
boff := backoff.NewConstantBackOff(5 * time.Second)
_ = backoff.Retry(operation, backoff.WithContext(boff, w.ctx))
log.Info().Msg("Stopping kubernetes watcher for Policy")
})
return nil
}
// Stop stops the watcher go routines.
func (w *watcher) Stop() error {
w.cancel()
w.waitGroup.Wait()
return nil
}
// GetDynamicConfigWatcher returns the config watcher.
func (w *watcher) GetDynamicConfigWatcher() notifiers.Trackers {
return w.policyDynamicConfigTrackers
}
// Reconcile is part of the main kubernetes reconciliation loop which aims to
// move the current state of the cluster closer to the desired state.
// TODO(user): Modify the Reconcile function to compare the state specified by
// the Policy object against the actual cluster state, and then
// perform operations to make the cluster state reflect the state specified by
// the user.
//
// For more details, check Reconcile and its Result here:
// - https://pkg.go.dev/sigs.k8s.io/controller-runtime@v0.11.2/pkg/reconcile
func (w *watcher) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
if w.resourcesDeleted == nil {
w.resourcesDeleted = make(map[types.NamespacedName]bool)
}
instance := &policyv1alpha1.Policy{}
err := w.Get(ctx, req.NamespacedName, instance)
if err != nil && errors.IsNotFound(err) {
if !w.resourcesDeleted[req.NamespacedName] {
// Request object not found, could have been deleted after reconcile request.
// Owned objects are automatically garbage collected. For additional cleanup logic use finalizers.
// Return and do not requeue
log.Debug().Msg(fmt.Sprintf("Handling deletion of resources for Instance '%s' in Namespace '%s'", req.Name, req.Namespace))
instance.Name = req.Name
instance.Namespace = req.Namespace
w.deleteResources(ctx, instance.DeepCopy())
w.resourcesDeleted[req.NamespacedName] = true
log.Debug().Msg("Policy resource not found. Ignoring since object must be deleted")
}
return ctrl.Result{}, nil
} else if err != nil {
// Error reading the object - requeue the request.
log.Error().Err(err).Msg("failed to get Policy")
return ctrl.Result{}, err
}
// Handing delete operation
if instance.GetDeletionTimestamp() != nil {
log.Debug().Msg(fmt.Sprintf("Handling deletion of resources for Instance '%s' in Namespace '%s'", instance.GetName(), instance.GetNamespace()))
w.deleteResources(ctx, instance.DeepCopy())
w.resourcesDeleted[req.NamespacedName] = true
return ctrl.Result{}, nil
}
instance.Status.Status = "uploading"
if err := w.updateStatus(ctx, instance.DeepCopy()); err != nil {
return ctrl.Result{}, err
}
w.resourcesDeleted[req.NamespacedName] = false
if err := w.reconcilePolicy(ctx, instance); err != nil {
return ctrl.Result{}, err
}
instance.Status.Status = "uploaded"
if err := w.updateStatus(ctx, instance.DeepCopy()); err != nil {
return ctrl.Result{}, err
}
return ctrl.Result{}, nil
}
func (w *watcher) deleteResources(ctx context.Context, instance *policyv1alpha1.Policy) {
w.RemoveEvent(notifiers.Key(instance.GetName()))
w.policyDynamicConfigTrackers.RemoveEvent(notifiers.Key(instance.GetName()))
}
// updateResource updates the Aperture resource in Kubernetes.
func (w *watcher) updateStatus(ctx context.Context, instance *policyv1alpha1.Policy) error {
attempt := 5
status := instance.DeepCopy().Status
for attempt > 0 {
attempt -= 1
if err := w.Status().Update(ctx, instance); err != nil {
if errors.IsConflict(err) {
namespacesName := types.NamespacedName{
Namespace: instance.GetNamespace(),
Name: instance.GetName(),
}
if err = w.Get(ctx, namespacesName, instance); err != nil {
return err
}
instance.Status = status
continue
}
return err
}
}
return nil
}
// reconcilePolicy sends a write event to notifier to get it uploaded on the Etcd.
func (w *watcher) reconcilePolicy(ctx context.Context, instance *policyv1alpha1.Policy) error {
policySpec := &languagev1.Policy{}
unmarshalErr := config.UnmarshalYAML(instance.Spec.Raw, policySpec)
if unmarshalErr != nil {
log.Warn().Err(unmarshalErr).Msg("Failed to unmarshal policy")
return unmarshalErr
}
annotations := instance.GetObjectMeta().GetAnnotations()
policyMessage := &iface.PolicyMessage{
Policy: policySpec,
PolicyMetadata: &languagev1.PolicyMetadata{
Values: annotations["fluxninja.com/values"],
BlueprintsUri: annotations["fluxninja.com/blueprints-uri"],
BlueprintName: annotations["fluxninja.com/blueprint-name"],
},
}
bytes, err := json.Marshal(policyMessage)
if err != nil {
return err
}
w.WriteEvent(notifiers.Key(instance.GetName()), bytes)
w.policyDynamicConfigTrackers.WriteEvent(notifiers.Key(instance.GetName()), instance.DynamicConfig.Raw)
w.recorder.Eventf(instance, corev1.EventTypeWarning, "UploadSuccessful", "Uploaded policy to trackers.")
return nil
}
// eventFilters sets up a Predicate filter for the received events.
func eventFiltersForPolicy() predicate.Predicate {
return predicate.Funcs{
CreateFunc: func(create event.CreateEvent) bool {
_, ok := create.Object.(*policyv1alpha1.Policy)
return ok
},
UpdateFunc: func(update event.UpdateEvent) bool {
new, ok1 := update.ObjectNew.(*policyv1alpha1.Policy)
old, ok2 := update.ObjectOld.(*policyv1alpha1.Policy)
if !ok1 || !ok2 {
return false
}
return !bytes.Equal(old.Spec.Raw, new.Spec.Raw) || !bytes.Equal(old.DynamicConfig.Raw, new.DynamicConfig.Raw) || new.GetDeletionTimestamp() != nil
},
DeleteFunc: func(delete event.DeleteEvent) bool {
return !delete.DeleteStateUnknown
},
}
}
// SetupWithManager sets up the controller with the Manager.
func (w *watcher) SetupWithManager(mgr ctrl.Manager) error {
return ctrl.NewControllerManagedBy(mgr).
For(&policyv1alpha1.Policy{}).
WithEventFilter(eventFiltersForPolicy()).
Complete(w)
}