-
Notifications
You must be signed in to change notification settings - Fork 2
/
environment_controller.go
481 lines (412 loc) · 14 KB
/
environment_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
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
/*
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 controllers
import (
"context"
"fmt"
"github.com/go-logr/logr"
"github.com/imdario/mergo"
"github.com/mmlt/environment-operator/pkg/cloud"
"github.com/mmlt/environment-operator/pkg/plan"
"github.com/mmlt/environment-operator/pkg/source"
"github.com/mmlt/environment-operator/pkg/step"
"github.com/mmlt/environment-operator/pkg/util"
"github.com/robfig/cron/v3"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime"
"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/predicate"
"time"
v1 "github.com/mmlt/environment-operator/api/v1"
)
// EnvironmentReconciler reconciles a Environment object.
type EnvironmentReconciler struct {
client.Client
Scheme *runtime.Scheme
Recorder record.EventRecorder
// LabelSet are the labels that resources must have to be handled by this reconciler.
// Resources created this resconciler also have these labels.
// An empty set matches all resources.
LabelSet labels.Set
// Cloud provides generic cloud access functions.
Cloud cloud.Cloud
// Sources fetches tf or yaml source code.
Sources *source.Sources
// Planner decides on the next step to execute based on Environment.
Planner *plan.Planner
// Environ are the environment variables presented to the steps.
Environ map[string]string
// Invocation counters
reconTally int
}
// TimeNow for testing.
var timeNow = time.Now
// +kubebuilder:rbac:groups=clusterops.mmlt.nl,resources=environments,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=clusterops.mmlt.nl,resources=environments/status,verbs=get;update;patch
// Reconcile takes an Environment custom resource and attempts to converge the target environment to the desired state.
// The status of the k8s resource is updated to match the observed state of the Envirnoment.
func (r *EnvironmentReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
var (
noRequeue = ctrl.Result{}
requeueNow = ctrl.Result{Requeue: true}
requeueSoon = ctrl.Result{RequeueAfter: 10 * time.Second}
)
log := logr.FromContext(ctx).WithName("Reconcile")
ctx = logr.NewContext(ctx, log)
r.reconTally++
log.V(1).Info("Start Reconcile", "tally", r.reconTally)
defer log.V(1).Info("End Reconcile", "tally", r.reconTally)
// Get Environment Custom Resource (deep copy).
cr := &v1.Environment{}
if err := r.Get(ctx, req.NamespacedName, cr); err != nil {
log.V(2).Info("unable to get kind Environment (retried)", "error", err)
return requeueSoon, ignoreNotFound(err)
}
// Ignore when not within time schedule.
ok, err := inSchedule(cr.Spec.Infra.Schedule, timeNow())
if err != nil {
// Schedule contains error (needs user to fix it first so do noy retry).
r.Recorder.Event(cr, "Warning", "Config", "infra.schedule:"+err.Error())
return noRequeue, fmt.Errorf("spec.infra.schedule: %w", err)
}
if !ok {
log.V(2).Info("outside schedule", "schedule", cr.Spec.Infra.Schedule)
return noRequeue, nil
}
if hasStepState(cr.Status.Steps, v1.StateError) {
// Needs step state reset to continue.
return noRequeue, nil
}
// Plan work.
stp, err := r.nextStep(cr, req, log)
// save planned steps (some steps might need to be re-executed)
err = r.saveStatus2(ctx, cr)
if err != nil {
return requeueNow, fmt.Errorf("save status: %w", err)
}
// Execute work.
if stp != nil {
stp.SetOnUpdate(func(meta step.Meta) {
log1 := logr.FromContext(ctx).WithName("OnUpdate")
ctx1 := logr.NewContext(ctx, log)
e := meta.GetLastError()
m := meta.GetMsg()
if e != nil {
log.Error(e, m)
}
s := meta.GetState()
log1.Info("callback", "msg", m, "state", s, "id", meta.GetID().ShortName())
r.update(ctx1, cr, meta)
})
env := util.KVSliceFromMap(r.Environ)
stp.Execute(ctx, env)
}
return noRequeue, nil
}
// NextStep fetches sources, makes a plan, updates cr and returns the next step.
// Return nil if there is nothing to do.
func (r *EnvironmentReconciler) nextStep(cr *v1.Environment, req ctrl.Request, log logr.Logger) (step.Step, error) {
// Get ClusterSpecs with defaults.
cspec, err := flattenedClusterSpec(cr.Spec)
if err != nil {
// Spec contains error (needs user to fix it first so do noy retry).
r.Recorder.Event(cr, "Warning", "Config", err.Error())
return nil, fmt.Errorf("spec: %w", err)
}
// Replace references to secret values with the value from vault.
ispec, err := vaultInfraValues(cr.Spec.Infra, r.Cloud)
if err != nil {
return nil, fmt.Errorf("vault ref: %w", err)
}
cspec, err = vaultClusterValues(cspec, r.Cloud)
if err != nil {
return nil, fmt.Errorf("vault ref: %w", err)
}
// Register and fetch sources.
err = r.Sources.Register(req.NamespacedName, "", ispec.Source)
if err != nil {
return nil, fmt.Errorf("source: register infra: %w", err)
}
for _, sp := range cspec {
err = r.Sources.Register(req.NamespacedName, sp.Name, sp.Addons.Source)
if err != nil {
return nil, fmt.Errorf("source: register cluster: %w", err)
}
}
err = r.Sources.FetchAll()
if err != nil {
log.Error(err, "source: fetch")
}
// update workspaces
_, err = r.Sources.Get(req.NamespacedName, "")
if err != nil {
return nil, fmt.Errorf("source: get infra: %w", err)
}
for _, sp := range cspec {
_, err = r.Sources.Get(req.NamespacedName, sp.Name)
if err != nil {
return nil, fmt.Errorf("source: get cluster: %w", err)
}
}
// Make a plan
pln, err := r.Planner.Plan(req.NamespacedName, r.Sources, cr.Spec.Destroy, ispec, cspec)
if err != nil {
return nil, fmt.Errorf("plan: %w", err)
}
stp, err := getStepAndSyncStatusWithPlan(&cr.Status, pln, log)
if err != nil {
return nil, fmt.Errorf("sync status with plan: %w", err)
}
return stp, nil
}
// InSchedule returns true when time now is in CRON schedule or the schedule is empty.
//
// Field name | Mandatory? | Allowed values | Allowed special characters
// ---------- | ---------- | -------------- | --------------------------
// Minutes | Yes | 0-59 | * / , -
// Hours | Yes | 0-23 | * / , -
// Day of month | Yes | 1-31 | * / , - ?
// Month | Yes | 1-12 or JAN-DEC | * / , -
// Day of week | Yes | 0-6 or SUN-SAT | * / , - ?
//
// Special characters:
// * always
// / interval, for example */5 is every 5m
// , list, for example MON,FRI in DayOfWeek field
// - range, for example 20-04 in hour field
// See https://godoc.org/github.com/robfig/cron#Parser
func inSchedule(schedule string, now time.Time) (bool, error) {
if schedule == "" {
return true, nil
}
p := cron.NewParser(cron.Minute | cron.Hour | cron.Dom | cron.Month | cron.Dow)
sc, err := p.Parse(schedule)
if err != nil {
return false, err
}
next := sc.Next(now)
ok := next.Sub(now).Minutes() < 10.0
return ok, nil
}
// getStepAndSyncStatusWithPlan update status.steps with plan and returns the next step to execute.
// Return nil if no step is to be executed.
func getStepAndSyncStatusWithPlan(status *v1.EnvironmentStatus, plan []step.Step, log logr.Logger) (step.Step, error) {
if status.Steps == nil {
status.Steps = make(map[string]v1.StepStatus)
}
var r step.Step
for _, stp := range plan {
shortName := stp.GetID().ShortName()
// Get status step state.
stStp, ok := status.Steps[shortName]
if !ok {
// first time this step is seen.
stStp = v1.StepStatus{
Message: "new",
LastTransitionTime: metav1.Time{Time: timeNow()},
}
}
if stStp.Hash == stp.GetHash() {
// step is at desired state.
if stStp.State != v1.StateReady {
// state is inconsistent, fix it
log.Info("inconsistency in status: step state with matching hash should have State=Ready", "step", stStp)
stStp.State = v1.StateReady
}
continue
}
if r == nil {
// the first step in the plan with a non-matching hash.
r = stp
}
if stStp.State == v1.StateReady {
// clear state of a step that needs to be run again because its hash has changed.
stStp.State = ""
// Consider also doing to reverse: set stStepSate = v1.StateReady when hashes match.
// For example in the following sequence of events a step will run again even it's not strictly necessary;
// 1. step source or parameter are changed
// 2. stStp.State is cleared because the hashes don't match anymore
// 3. changes from 1 are undone
}
status.Steps[shortName] = stStp
}
// status consistency checks
if r == nil {
// if no step is selected to be run all steps must be Ready
for _, stStp := range status.Steps {
if stStp.State != v1.StateReady {
log.Info("inconsistency in status: if no step is to be run all states must be Ready", "step", stStp)
}
}
}
return r, nil
}
// SaveStatus writes the status to the API server.
func (r *EnvironmentReconciler) saveStatus2(ctx context.Context, cr *v1.Environment) error {
// clean-up steps (consider moving to getStepAndSyncStatusWithPlan)
p := r.Planner.PossibleSteps(cr.Spec.Clusters)
for n := range cr.Status.Steps {
if _, ok := p[n]; ok {
continue
}
delete(cr.Status.Steps, n)
}
updateStatusConditions(&cr.Status)
log := logr.FromContext(ctx)
log.Info("saveStatus", "status", cr.Status)
// TODO consider retry (might be faster then waiting for another reconcile)
// also see client-go retry.RetryOnConflict()
return r.Status().Update(ctx, cr)
}
// UpdateStatusConditions updates Status.Conditions to reflect steps state.
// Ready = True when all steps are in their final state, Reason is Ready or Failed.
// Ready = False when a step is running, Reason is Running.
// Ready = Unknown when no steps are present.
func updateStatusConditions(status *v1.EnvironmentStatus) {
var runningCnt, readyCnt, errorCnt, totalCnt int
var latestTime metav1.Time
for _, st := range status.Steps {
totalCnt++
switch st.State {
case v1.StateRunning:
runningCnt++
case v1.StateReady:
readyCnt++
case v1.StateError:
errorCnt++
}
if st.LastTransitionTime.After(latestTime.Time) {
latestTime = st.LastTransitionTime
}
}
c := v1.EnvironmentCondition{
Type: "Ready", //TODO define in API types
}
switch {
case errorCnt > 0:
c.Status = metav1.ConditionTrue
c.Reason = v1.ReasonFailed
case runningCnt > 0:
c.Status = metav1.ConditionFalse
c.Reason = v1.ReasonRunning
case readyCnt == totalCnt && totalCnt > 0:
c.Status = metav1.ConditionTrue
c.Reason = v1.ReasonReady
default:
c.Status = metav1.ConditionUnknown
c.Reason = ""
}
c.Message = fmt.Sprintf("%d/%d ready, %d running, %d error(s)", readyCnt, totalCnt, runningCnt, errorCnt)
if latestTime.IsZero() {
latestTime = metav1.Time{Time: timeNow()}
}
c.LastTransitionTime = latestTime
// update condition
ci := -1
for i, v := range status.Conditions {
if v.Type == c.Type {
ci = i
break
}
}
if ci >= 0 {
x := status.Conditions[ci]
if x.Status == c.Status &&
x.Reason == c.Reason &&
x.Message == c.Message {
// no change in condition
return
}
status.Conditions[ci] = c
} else {
status.Conditions = append(status.Conditions, c)
}
}
// Update updates cr.Status with meta, writes the status to the API Server and records an Event.
func (r *EnvironmentReconciler) update(ctx context.Context, cr *v1.Environment, meta step.Meta) {
log := logr.FromContext(ctx)
shortname := meta.GetID().ShortName()
r.Recorder.Event(cr, "Normal", shortname+string(meta.GetState()), meta.GetMsg())
// copy meta to step
ss := cr.Status.Steps[shortname]
ss.State = meta.GetState()
ss.Message = meta.GetMsg()
ss.LastTransitionTime = metav1.Time{Time: timeNow()}
if ss.State == v1.StateReady {
// step has completed.
ss.Hash = meta.GetHash()
}
cr.Status.Steps[shortname] = ss
err := r.saveStatus2(ctx, cr)
if err != nil {
// failing to save a final state will result in re-execution of the step
log.Error(err, "saveStatus")
}
}
// SetupWithManager initializes the receiver and adds it to mgr.
func (r *EnvironmentReconciler) SetupWithManager(mgr ctrl.Manager) error {
selector := r.LabelSet.AsSelector()
lp := predicate.NewPredicateFuncs(
func(o client.Object) bool {
return selector.Matches(labels.Set(o.GetLabels()))
},
)
return ctrl.NewControllerManagedBy(mgr).
For(&v1.Environment{}).
WithEventFilter(lp).
Complete(r)
}
// IgnoreNotFound makes NotFound errors disappear.
// We generally want to ignore (not requeue) NotFound errors, since we'll get a
// reconciliation request once the object exists, and re-queuing in the meantime
// won't help.
func ignoreNotFound(err error) error {
if apierrors.IsNotFound(err) {
return nil
}
return err
}
// FlattenedClusterSpec returns []ClusterSpec merged with default values.
// Return an error on spec validation issues.
func flattenedClusterSpec(in v1.EnvironmentSpec) ([]v1.ClusterSpec, error) {
err := validateSpec(&in)
if err != nil {
return nil, fmt.Errorf("validate spec: %w", err)
}
var r []v1.ClusterSpec
for _, c := range in.Clusters {
cs := in.Defaults.DeepCopy()
err = mergo.Merge(cs, c, mergo.WithOverride)
if err != nil {
return nil, fmt.Errorf("merge spec.cluster %s: %w", c.Name, err)
}
err = validateClusterSpec(cs)
if err != nil {
return nil, fmt.Errorf("validate spec.cluster %s: %w", c.Name, err)
}
r = append(r, *cs)
}
return r, nil
}
// HasStepState returns true when one of the stps is in state.
func hasStepState(stps map[string]v1.StepStatus, state v1.StepState) bool {
for _, stp := range stps {
if stp.State == state {
return true
}
}
return false
}