-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
Copy pathreconcile.go
400 lines (364 loc) · 13.2 KB
/
reconcile.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
// Copyright 2018 The Operator-SDK Authors
//
// 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"
"encoding/json"
"errors"
"fmt"
"math/rand"
"os"
"strconv"
"strings"
"time"
ansiblestatus "github.com/operator-framework/operator-sdk/pkg/ansible/controller/status"
"github.com/operator-framework/operator-sdk/pkg/ansible/events"
"github.com/operator-framework/operator-sdk/pkg/ansible/metrics"
"github.com/operator-framework/operator-sdk/pkg/ansible/proxy/kubeconfig"
"github.com/operator-framework/operator-sdk/pkg/ansible/runner"
"github.com/operator-framework/operator-sdk/pkg/ansible/runner/eventapi"
v1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/types"
"sigs.k8s.io/controller-runtime/pkg/client"
logf "sigs.k8s.io/controller-runtime/pkg/log"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
)
const (
// ReconcilePeriodAnnotation - annotation used by a user to specify the reconciliation interval for the CR.
// To use create a CR with an annotation "ansible.operator-sdk/reconcile-period: 30s" or some other valid
// Duration. This will override the operators/or controllers reconcile period for that particular CR.
ReconcilePeriodAnnotation = "ansible.operator-sdk/reconcile-period"
)
// AnsibleOperatorReconciler - object to reconcile runner requests
type AnsibleOperatorReconciler struct {
GVK schema.GroupVersionKind
Runner runner.Runner
Client client.Client
APIReader client.Reader
EventHandlers []events.EventHandler
ReconcilePeriod time.Duration
ManageStatus bool
}
// Reconcile - handle the event.
func (r *AnsibleOperatorReconciler) Reconcile(request reconcile.Request) (reconcile.Result, error) {
u := &unstructured.Unstructured{}
u.SetGroupVersionKind(r.GVK)
err := r.Client.Get(context.TODO(), request.NamespacedName, u)
if apierrors.IsNotFound(err) {
return reconcile.Result{}, nil
}
if err != nil {
return reconcile.Result{}, err
}
ident := strconv.Itoa(rand.Int())
logger := logf.Log.WithName("reconciler").WithValues(
"job", ident,
"name", u.GetName(),
"namespace", u.GetNamespace(),
)
reconcileResult := reconcile.Result{RequeueAfter: r.ReconcilePeriod}
if ds, ok := u.GetAnnotations()[ReconcilePeriodAnnotation]; ok {
duration, err := time.ParseDuration(ds)
if err != nil {
// Should attempt to update to a failed condition
errmark := r.markError(u, request.NamespacedName,
fmt.Sprintf("Unable to parse reconcile period annotation: %v", err))
if errmark != nil {
logger.Error(errmark, "Unable to mark error annotation")
}
logger.Error(err, "Unable to parse reconcile period annotation")
return reconcileResult, err
}
reconcileResult.RequeueAfter = duration
}
deleted := u.GetDeletionTimestamp() != nil
finalizer, finalizerExists := r.Runner.GetFinalizer()
pendingFinalizers := u.GetFinalizers()
// If the resource is being deleted we don't want to add the finalizer again
if finalizerExists && !deleted && !contains(pendingFinalizers, finalizer) {
logger.V(1).Info("Adding finalizer to resource", "Finalizer", finalizer)
finalizers := append(pendingFinalizers, finalizer)
u.SetFinalizers(finalizers)
err := r.Client.Update(context.TODO(), u)
if err != nil {
logger.Error(err, "Unable to update cr with finalizer")
return reconcileResult, err
}
}
if !contains(pendingFinalizers, finalizer) && deleted {
logger.Info("Resource is terminated, skipping reconciliation")
return reconcile.Result{}, nil
}
spec := u.Object["spec"]
_, ok := spec.(map[string]interface{})
// Need to handle cases where there is no spec.
// We can add the spec to the object, which will allow
// everything to work, and will not get updated.
// Therefore we can now deal with the case of secrets and configmaps.
if !ok {
logger.V(1).Info("Spec was not found")
u.Object["spec"] = map[string]interface{}{}
}
if r.ManageStatus {
errmark := r.markRunning(u, request.NamespacedName)
if errmark != nil {
logger.Error(errmark, "Unable to update the status to mark cr as running")
return reconcileResult, errmark
}
}
ownerRef := metav1.OwnerReference{
APIVersion: u.GetAPIVersion(),
Kind: u.GetKind(),
Name: u.GetName(),
UID: u.GetUID(),
}
kc, err := kubeconfig.Create(ownerRef, "http://localhost:8888", u.GetNamespace())
if err != nil {
errmark := r.markError(u, request.NamespacedName, "Unable to run reconciliation")
if errmark != nil {
logger.Error(errmark, "Unable to mark error to run reconciliation")
}
logger.Error(err, "Unable to generate kubeconfig")
return reconcileResult, err
}
defer func() {
if err := os.Remove(kc.Name()); err != nil {
logger.Error(err, "Failed to remove generated kubeconfig file")
}
}()
result, err := r.Runner.Run(ident, u, kc.Name())
if err != nil {
errmark := r.markError(u, request.NamespacedName, "Unable to run reconciliation")
if errmark != nil {
logger.Error(errmark, "Unable to mark error to run reconciliation")
}
logger.Error(err, "Unable to run ansible runner")
return reconcileResult, err
}
// iterate events from ansible, looking for the final one
statusEvent := eventapi.StatusJobEvent{}
failureMessages := eventapi.FailureMessages{}
for event := range result.Events() {
for _, eHandler := range r.EventHandlers {
go eHandler.Handle(ident, u, event)
}
if event.Event == eventapi.EventPlaybookOnStats {
// convert to StatusJobEvent; would love a better way to do this
data, err := json.Marshal(event)
if err != nil {
printEventStats(statusEvent)
return reconcile.Result{}, err
}
err = json.Unmarshal(data, &statusEvent)
if err != nil {
printEventStats(statusEvent)
return reconcile.Result{}, err
}
}
if event.Event == eventapi.EventRunnerOnFailed && !event.IgnoreError() {
failureMessages = append(failureMessages, event.GetFailedPlaybookMessage())
}
}
// To print the stats of the task
printEventStats(statusEvent)
if statusEvent.Event == "" {
eventErr := errors.New("did not receive playbook_on_stats event")
stdout, err := result.Stdout()
if err != nil {
logger.Error(err, "Failed to get ansible-runner stdout")
return reconcileResult, err
}
logger.Error(eventErr, stdout)
return reconcileResult, eventErr
}
// Need to get the unstructured object after the Ansible runner finishes.
// This needs to hit the API server to retrieve updates.
err = r.APIReader.Get(context.TODO(), request.NamespacedName, u)
if err != nil {
if apierrors.IsNotFound(err) {
return reconcile.Result{}, nil
}
return reconcile.Result{}, err
}
// try to get the updated finalizers
pendingFinalizers = u.GetFinalizers()
// We only want to update the CustomResource once, so we'll track changes
// and do it at the end
runSuccessful := len(failureMessages) == 0
// The finalizer has run successfully, time to remove it
if deleted && finalizerExists && runSuccessful {
finalizers := []string{}
for _, pendingFinalizer := range pendingFinalizers {
if pendingFinalizer != finalizer {
finalizers = append(finalizers, pendingFinalizer)
}
}
u.SetFinalizers(finalizers)
err := r.Client.Update(context.TODO(), u)
if err != nil {
logger.Error(err, "Failed to remove finalizer")
return reconcileResult, err
}
}
if r.ManageStatus {
errmark := r.markDone(u, request.NamespacedName, statusEvent, failureMessages)
if errmark != nil {
logger.Error(errmark, "Failed to mark status done")
}
// re-trigger reconcile because of failures
if !runSuccessful {
return reconcileResult, errors.New("event runner on failed")
}
return reconcileResult, errmark
}
// re-trigger reconcile because of failures
if !runSuccessful {
return reconcileResult, errors.New("received failed task event")
}
return reconcileResult, nil
}
func printEventStats(statusEvent eventapi.StatusJobEvent) {
fmt.Printf("\n--------------------------- Ansible Task Status Event StdOut -----------------\n")
fmt.Println(statusEvent.StdOut)
fmt.Printf("\n-------------------------------------------------------------------------------\n")
}
func (r *AnsibleOperatorReconciler) markRunning(u *unstructured.Unstructured,
namespacedName types.NamespacedName) error {
// Get the latest resource to prevent updating a stale status.
if err := r.APIReader.Get(context.TODO(), namespacedName, u); err != nil {
return err
}
crStatus := getStatus(u)
// If there is no current status add that we are working on this resource.
errCond := ansiblestatus.GetCondition(crStatus, ansiblestatus.FailureConditionType)
if errCond != nil {
errCond.Status = v1.ConditionFalse
ansiblestatus.SetCondition(&crStatus, *errCond)
}
// If the condition is currently running, making sure that the values are correct.
// If they are the same a no-op, if they are different then it is a good thing we
// are updating it.
c := ansiblestatus.NewCondition(
ansiblestatus.RunningConditionType,
v1.ConditionTrue,
nil,
ansiblestatus.RunningReason,
ansiblestatus.RunningMessage,
)
ansiblestatus.SetCondition(&crStatus, *c)
u.Object["status"] = crStatus.GetJSONMap()
return r.Client.Status().Update(context.TODO(), u)
}
// markError - used to alert the user to the issues during the validation of a reconcile run.
// i.e Annotations that could be incorrect
func (r *AnsibleOperatorReconciler) markError(u *unstructured.Unstructured, namespacedName types.NamespacedName,
failureMessage string) error {
logger := logf.Log.WithName("markError")
// Immediately update metrics with failed reconciliation, since Get()
// may fail.
metrics.ReconcileFailed(r.GVK.String())
// Get the latest resource to prevent updating a stale status.
if err := r.APIReader.Get(context.TODO(), namespacedName, u); err != nil {
if apierrors.IsNotFound(err) {
logger.Info("Resource not found, assuming it was deleted")
return nil
}
return err
}
crStatus := getStatus(u)
sc := ansiblestatus.GetCondition(crStatus, ansiblestatus.RunningConditionType)
if sc != nil {
sc.Status = v1.ConditionFalse
ansiblestatus.SetCondition(&crStatus, *sc)
}
c := ansiblestatus.NewCondition(
ansiblestatus.FailureConditionType,
v1.ConditionTrue,
nil,
ansiblestatus.FailedReason,
failureMessage,
)
ansiblestatus.SetCondition(&crStatus, *c)
// This needs the status subresource to be enabled by default.
u.Object["status"] = crStatus.GetJSONMap()
return r.Client.Status().Update(context.TODO(), u)
}
func (r *AnsibleOperatorReconciler) markDone(u *unstructured.Unstructured, namespacedName types.NamespacedName,
statusEvent eventapi.StatusJobEvent, failureMessages eventapi.FailureMessages) error {
logger := logf.Log.WithName("markDone")
// Get the latest resource to prevent updating a stale status.
if err := r.APIReader.Get(context.TODO(), namespacedName, u); err != nil {
if apierrors.IsNotFound(err) {
logger.Info("Resource not found, assuming it was deleted")
return nil
}
return err
}
crStatus := getStatus(u)
runSuccessful := len(failureMessages) == 0
ansibleStatus := ansiblestatus.NewAnsibleResultFromStatusJobEvent(statusEvent)
if !runSuccessful {
metrics.ReconcileFailed(r.GVK.String())
sc := ansiblestatus.GetCondition(crStatus, ansiblestatus.RunningConditionType)
if sc != nil {
sc.Status = v1.ConditionFalse
ansiblestatus.SetCondition(&crStatus, *sc)
}
c := ansiblestatus.NewCondition(
ansiblestatus.FailureConditionType,
v1.ConditionTrue,
ansibleStatus,
ansiblestatus.FailedReason,
strings.Join(failureMessages, "\n"),
)
ansiblestatus.SetCondition(&crStatus, *c)
} else {
metrics.ReconcileSucceeded(r.GVK.String())
c := ansiblestatus.NewCondition(
ansiblestatus.RunningConditionType,
v1.ConditionTrue,
ansibleStatus,
ansiblestatus.SuccessfulReason,
ansiblestatus.SuccessfulMessage,
)
// Remove the failure condition if set, because this completed successfully.
ansiblestatus.RemoveCondition(&crStatus, ansiblestatus.FailureConditionType)
ansiblestatus.SetCondition(&crStatus, *c)
}
// This needs the status subresource to be enabled by default.
u.Object["status"] = crStatus.GetJSONMap()
return r.Client.Status().Update(context.TODO(), u)
}
func contains(l []string, s string) bool {
for _, elem := range l {
if elem == s {
return true
}
}
return false
}
// getStatus returns u's "status" block as a status.Status.
func getStatus(u *unstructured.Unstructured) ansiblestatus.Status {
statusInterface := u.Object["status"]
statusMap, ok := statusInterface.(map[string]interface{})
// If the map is not available create one.
if !ok {
statusMap = map[string]interface{}{}
}
return ansiblestatus.CreateFromMap(statusMap)
}