-
Notifications
You must be signed in to change notification settings - Fork 211
/
revision_controller.go
372 lines (334 loc) · 13.8 KB
/
revision_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
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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
package revisioncontroller
import (
"context"
"fmt"
"strconv"
"strings"
"k8s.io/klog/v2"
operatorv1 "github.com/openshift/api/operator/v1"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/equality"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/informers"
corev1client "k8s.io/client-go/kubernetes/typed/core/v1"
"github.com/openshift/library-go/pkg/controller/factory"
"github.com/openshift/library-go/pkg/operator/condition"
"github.com/openshift/library-go/pkg/operator/events"
"github.com/openshift/library-go/pkg/operator/management"
"github.com/openshift/library-go/pkg/operator/resource/resourceapply"
"github.com/openshift/library-go/pkg/operator/v1helpers"
)
// LatestRevisionClient is an operator client for an operator status with a latest revision field.
type LatestRevisionClient interface {
v1helpers.OperatorClient
// GetLatestRevisionState returns the spec, status and latest revision.
GetLatestRevisionState() (spec *operatorv1.OperatorSpec, status *operatorv1.OperatorStatus, rev int32, rv string, err error)
// UpdateLatestRevisionOperatorStatus updates the status with the given latestAvailableRevision and the by applying the given updateFuncs.
UpdateLatestRevisionOperatorStatus(ctx context.Context, latestAvailableRevision int32, updateFuncs ...v1helpers.UpdateStatusFunc) (*operatorv1.OperatorStatus, bool, error)
}
// RevisionController is a controller that watches a set of configmaps and secrets and them against a revision snapshot
// of them. If the original resources changes, the revision counter is increased, stored in LatestAvailableRevision
// field of the operator config and new snapshots suffixed by the revision are created.
type RevisionController struct {
targetNamespace string
// configMaps is the list of configmaps that are directly copied.A different actor/controller modifies these.
// the first element should be the configmap that contains the static pod manifest
configMaps []RevisionResource
// secrets is a list of secrets that are directly copied for the current values. A different actor/controller modifies these.
secrets []RevisionResource
operatorClient LatestRevisionClient
configMapGetter corev1client.ConfigMapsGetter
secretGetter corev1client.SecretsGetter
}
type RevisionResource struct {
Name string
Optional bool
}
// NewRevisionController create a new revision controller.
func NewRevisionController(
targetNamespace string,
configMaps []RevisionResource,
secrets []RevisionResource,
kubeInformersForTargetNamespace informers.SharedInformerFactory,
operatorClient LatestRevisionClient,
configMapGetter corev1client.ConfigMapsGetter,
secretGetter corev1client.SecretsGetter,
eventRecorder events.Recorder,
) factory.Controller {
c := &RevisionController{
targetNamespace: targetNamespace,
configMaps: configMaps,
secrets: secrets,
operatorClient: operatorClient,
configMapGetter: configMapGetter,
secretGetter: secretGetter,
}
return factory.New().WithInformers(
operatorClient.Informer(),
kubeInformersForTargetNamespace.Core().V1().ConfigMaps().Informer(),
kubeInformersForTargetNamespace.Core().V1().Secrets().Informer()).WithSync(c.sync).ToController("RevisionController", eventRecorder)
}
// createRevisionIfNeeded takes care of creating content for the static pods to use.
// returns whether or not requeue and if an error happened when updating status. Normally it updates status itself.
func (c RevisionController) createRevisionIfNeeded(ctx context.Context, recorder events.Recorder, latestAvailableRevision int32, resourceVersion string) (bool, error) {
isLatestRevisionCurrent, requiredIsNotFound, reason := c.isLatestRevisionCurrent(ctx, latestAvailableRevision)
// check to make sure that the latestRevision has the exact content we expect. No mutation here, so we start creating the next Revision only when it is required
if isLatestRevisionCurrent {
klog.V(4).Infof("Returning early, %d triggered and up to date", latestAvailableRevision)
return false, nil
}
nextRevision := latestAvailableRevision + 1
var createdNewRevision bool
var err error
// check to make sure no new revision is created when a required object is missing
if requiredIsNotFound {
err = fmt.Errorf("%v", reason)
} else {
recorder.Eventf("StartingNewRevision", "new revision %d triggered by %q", nextRevision, reason)
createdNewRevision, err = c.createNewRevision(ctx, recorder, nextRevision, reason)
}
if err != nil {
cond := operatorv1.OperatorCondition{
Type: "RevisionControllerDegraded",
Status: operatorv1.ConditionTrue,
Reason: "ContentCreationError",
Message: err.Error(),
}
if _, _, updateError := v1helpers.UpdateStatus(ctx, c.operatorClient, v1helpers.UpdateConditionFn(cond)); updateError != nil {
recorder.Warningf("RevisionCreateFailed", "Failed to create revision %d: %v", nextRevision, err.Error())
return true, updateError
}
return true, nil
}
if !createdNewRevision {
klog.V(4).Infof("Revision %v not created", nextRevision)
return false, nil
}
recorder.Eventf("RevisionTriggered", "new revision %d triggered by %q", nextRevision, reason)
cond := operatorv1.OperatorCondition{
Type: "RevisionControllerDegraded",
Status: operatorv1.ConditionFalse,
}
if _, updated, updateError := c.operatorClient.UpdateLatestRevisionOperatorStatus(ctx, nextRevision, v1helpers.UpdateConditionFn(cond)); updateError != nil {
return true, updateError
} else if updated {
recorder.Eventf("RevisionCreate", "Revision %d created because %s", nextRevision, reason)
}
return false, nil
}
func nameFor(name string, revision int32) string {
return fmt.Sprintf("%s-%d", name, revision)
}
// isLatestRevisionCurrent returns whether the latest revision is up to date and an optional reason
func (c RevisionController) isLatestRevisionCurrent(ctx context.Context, revision int32) (bool, bool, string) {
configChanges := []string{}
for _, cm := range c.configMaps {
requiredData := map[string]string{}
existingData := map[string]string{}
required, err := c.configMapGetter.ConfigMaps(c.targetNamespace).Get(ctx, cm.Name, metav1.GetOptions{})
if apierrors.IsNotFound(err) && !cm.Optional {
return false, true, err.Error()
}
existing, err := c.configMapGetter.ConfigMaps(c.targetNamespace).Get(ctx, nameFor(cm.Name, revision), metav1.GetOptions{})
if apierrors.IsNotFound(err) && !cm.Optional {
return false, false, err.Error()
}
if required != nil {
requiredData = required.Data
}
if existing != nil {
existingData = existing.Data
}
if !equality.Semantic.DeepEqual(existingData, requiredData) {
if klog.V(4).Enabled() {
klog.Infof("configmap %q changes for revision %d: %s", cm.Name, revision, resourceapply.JSONPatchNoError(existing, required))
}
// "configmap/foo has changed" when there is actual change in data
// "configmap/foo has been created" when the existing configmap was empty (iow. the configmap is optional)
verb := "changed"
if len(existingData) == 0 {
verb = "been created"
}
req := "required"
if cm.Optional {
req = "optional"
}
configChanges = append(configChanges, fmt.Sprintf("%s configmap/%s has %s", req, cm.Name, verb))
}
}
secretChanges := []string{}
for _, s := range c.secrets {
requiredData := map[string][]byte{}
existingData := map[string][]byte{}
required, err := c.secretGetter.Secrets(c.targetNamespace).Get(ctx, s.Name, metav1.GetOptions{})
if apierrors.IsNotFound(err) && !s.Optional {
return false, true, err.Error()
}
existing, err := c.secretGetter.Secrets(c.targetNamespace).Get(ctx, nameFor(s.Name, revision), metav1.GetOptions{})
if apierrors.IsNotFound(err) && !s.Optional {
return false, false, err.Error()
}
if required != nil {
requiredData = required.Data
}
if existing != nil {
existingData = existing.Data
}
if !equality.Semantic.DeepEqual(existingData, requiredData) {
if klog.V(4).Enabled() {
klog.Infof("Secret %q changes for revision %d: %s", s.Name, revision, resourceapply.JSONPatchSecretNoError(existing, required))
}
// "configmap/foo has changed" when there is actual change in data
// "configmap/foo has been created" when the existing configmap was empty (iow. the configmap is optional)
verb := "changed"
if len(existingData) == 0 {
verb = "been created"
}
req := "required"
if s.Optional {
req = "optional"
}
secretChanges = append(secretChanges, fmt.Sprintf("%s secret/%s has %s", req, s.Name, verb))
}
}
if len(secretChanges) > 0 || len(configChanges) > 0 {
return false, false, strings.Join(append(secretChanges, configChanges...), ",")
}
return true, false, ""
}
// returns true if we created a revision
func (c RevisionController) createNewRevision(ctx context.Context, recorder events.Recorder, revision int32, reason string) (bool, error) {
// Create a new InProgress status configmap
desiredStatusConfigMap := &corev1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Namespace: c.targetNamespace,
Name: nameFor("revision-status", revision),
Annotations: map[string]string{
"operator.openshift.io/revision-ready": "false",
},
},
Data: map[string]string{
"revision": fmt.Sprintf("%d", revision),
"reason": reason,
},
}
createdStatus, err := c.configMapGetter.ConfigMaps(desiredStatusConfigMap.Namespace).Create(ctx, desiredStatusConfigMap, metav1.CreateOptions{})
switch {
case apierrors.IsAlreadyExists(err):
if createdStatus == nil || len(createdStatus.UID) == 0 {
createdStatus, err = c.configMapGetter.ConfigMaps(desiredStatusConfigMap.Namespace).Get(ctx, desiredStatusConfigMap.Name, metav1.GetOptions{})
if err != nil {
return false, err
}
}
// take a live GET here to get current status to check the annotation
if createdStatus.Annotations["operator.openshift.io/revision-ready"] == "true" {
// no work to do because our cache is out of date and when we're updated, we will be able to see the result
klog.Infof("down the branch indicating that our cache was out of date and we're trying to recreate a revision.")
return false, nil
}
// update the sync and continue
case err != nil:
return false, err
}
ownerRefs := []metav1.OwnerReference{{
APIVersion: "v1",
Kind: "ConfigMap",
Name: createdStatus.Name,
UID: createdStatus.UID,
}}
for _, cm := range c.configMaps {
obj, _, err := resourceapply.SyncConfigMap(ctx, c.configMapGetter, recorder, c.targetNamespace, cm.Name, c.targetNamespace, nameFor(cm.Name, revision), ownerRefs)
if err != nil {
return false, err
}
if obj == nil && !cm.Optional {
return false, apierrors.NewNotFound(corev1.Resource("configmaps"), cm.Name)
}
}
for _, s := range c.secrets {
obj, _, err := resourceapply.SyncSecret(ctx, c.secretGetter, recorder, c.targetNamespace, s.Name, c.targetNamespace, nameFor(s.Name, revision), ownerRefs)
if err != nil {
return false, err
}
if obj == nil && !s.Optional {
return false, apierrors.NewNotFound(corev1.Resource("secrets"), s.Name)
}
}
createdStatus.Annotations["operator.openshift.io/revision-ready"] = "true"
if _, err := c.configMapGetter.ConfigMaps(createdStatus.Namespace).Update(ctx, createdStatus, metav1.UpdateOptions{}); err != nil {
return false, err
}
return true, nil
}
// getLatestAvailableRevision returns the latest known revision to the operator
// This is determined by checking revision status configmaps.
func (c RevisionController) getLatestAvailableRevision(ctx context.Context) (int32, error) {
// this appears to use a cached getter. I conceded that past-David should have explicitly used Listers
configMaps, err := c.configMapGetter.ConfigMaps(c.targetNamespace).List(ctx, metav1.ListOptions{})
if err != nil {
return 0, err
}
var latestRevision int32
for _, configMap := range configMaps.Items {
if !strings.HasPrefix(configMap.Name, "revision-status-") {
continue
}
if revision, ok := configMap.Data["revision"]; ok {
revisionNumber, err := strconv.Atoi(revision)
if err != nil {
return 0, err
}
if int32(revisionNumber) > latestRevision {
latestRevision = int32(revisionNumber)
}
}
}
// If there are no configmaps, then this should actually be revision 0
return latestRevision, nil
}
func (c RevisionController) sync(ctx context.Context, syncCtx factory.SyncContext) error {
operatorSpec, _, latestAvailableRevisionSeenByOperator, resourceVersion, err := c.operatorClient.GetLatestRevisionState()
if err != nil {
return err
}
if !management.IsOperatorManaged(operatorSpec.ManagementState) {
return nil
}
// If the operator status's latest available revision is not the same as the observed latest revision, update the operator.
latestObservedRevision, err := c.getLatestAvailableRevision(ctx)
if err != nil {
return err
}
if latestObservedRevision != 0 && latestAvailableRevisionSeenByOperator != latestObservedRevision {
// Then make sure that revision number is what's in the operator status
_, _, err := c.operatorClient.UpdateLatestRevisionOperatorStatus(ctx, latestObservedRevision)
if err != nil {
return err
}
// regardless of whether we made a change, requeue to rerun the sync with updated status
return factory.SyntheticRequeueError
}
requeue, syncErr := c.createRevisionIfNeeded(ctx, syncCtx.Recorder(), latestAvailableRevisionSeenByOperator, resourceVersion)
if requeue && syncErr == nil {
return factory.SyntheticRequeueError
}
err = syncErr
// update failing condition
cond := operatorv1.OperatorCondition{
Type: condition.RevisionControllerDegradedConditionType,
Status: operatorv1.ConditionFalse,
}
if err != nil {
cond.Status = operatorv1.ConditionTrue
cond.Reason = "Error"
cond.Message = err.Error()
}
if _, _, updateError := v1helpers.UpdateStatus(ctx, c.operatorClient, v1helpers.UpdateConditionFn(cond)); updateError != nil {
if err == nil {
return updateError
}
}
return err
}