-
Notifications
You must be signed in to change notification settings - Fork 168
/
handler.go
327 lines (280 loc) · 10.7 KB
/
handler.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
package workflowrun
import (
"bytes"
"encoding/json"
"net/http"
"reflect"
"time"
log "github.com/sirupsen/logrus"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/util/retry"
"github.com/caicloud/cyclone/pkg/apis/cyclone/v1alpha1"
"github.com/caicloud/cyclone/pkg/k8s/clientset"
"github.com/caicloud/cyclone/pkg/meta"
utilhttp "github.com/caicloud/cyclone/pkg/util/http"
"github.com/caicloud/cyclone/pkg/workflow/common"
"github.com/caicloud/cyclone/pkg/workflow/controller"
"github.com/caicloud/cyclone/pkg/workflow/controller/handlers"
"github.com/caicloud/cyclone/pkg/workflow/workflowrun"
)
// Handler handles changes of WorkflowRun CR.
type Handler struct {
Client clientset.Interface
TimeoutProcessor *workflowrun.TimeoutProcessor
GCProcessor *workflowrun.GCProcessor
LimitedQueues *workflowrun.LimitedQueues
ParallelismController workflowrun.ParallelismController
}
// Ensure *Handler has implemented handlers.Interface interface.
var _ handlers.Interface = (*Handler)(nil)
// ObjectCreated handles a newly created WorkflowRun
func (h *Handler) ObjectCreated(obj interface{}) {
originWfr, ok := obj.(*v1alpha1.WorkflowRun)
if !ok {
log.Warning("unknown resource type")
return
}
log.WithField("name", originWfr.Name).Debug("Start to process WorkflowRun create")
if !validate(originWfr) {
return
}
// AddOrRefresh adds a WorkflowRun to its corresponding queue, if the queue size exceed the
// maximum size, the oldest one would be deleted. And if the WorkflowRun already exists in
// the queue, its 'refresh' time field would be refreshed.
h.LimitedQueues.AddOrRefresh(originWfr)
// Add the WorkflowRun object to GC processor, it will be checked before actually added to
// the GC queue.
h.GCProcessor.Add(originWfr)
// If the WorkflowRun has already been terminated or waiting for external events, skip it.
if originWfr.Status.Overall.Phase == v1alpha1.StatusSucceeded ||
originWfr.Status.Overall.Phase == v1alpha1.StatusFailed ||
originWfr.Status.Overall.Phase == v1alpha1.StatusWaiting {
return
}
// If the WorkflowRun has not yet be started to execute, check the parallelism constraints to determine
// whether to execute it.
if originWfr.Status.Overall.Phase == "" {
switch h.ParallelismController.AttemptNew(originWfr.Namespace, originWfr.Spec.WorkflowRef.Name, originWfr.Name) {
case workflowrun.AttemptActionQueued:
log.WithField("wfr", originWfr.Name).Infof("Too many WorkflowRun are running, stay pending in queue, will retry in %s", common.ResyncPeriod.String())
return
case workflowrun.AttemptActionFailed:
if err := h.SetStatus(originWfr.Namespace, originWfr.Name, &v1alpha1.Status{
Phase: v1alpha1.StatusFailed,
Reason: "TooManyWaiting",
LastTransitionTime: metav1.Time{Time: time.Now()},
}); err != nil {
log.WithField("wfr", originWfr.Name).Error("Set status to Failed error, ", err)
return
}
}
}
// Add this WorkflowRun to timeout processor, so that it would be cleaned up when time expired.
err := h.TimeoutProcessor.Add(originWfr)
if err != nil {
log.WithField("wfr", originWfr.Name).Warn("add wfr to timeout processor failed: ", err)
}
wfr := originWfr.DeepCopy()
clusterClient := common.GetExecutionClusterClient(wfr)
if clusterClient == nil {
log.WithField("wfr", wfr.Name).Error("Execution cluster client not found")
return
}
operator, err := workflowrun.NewOperator(clusterClient, h.Client, wfr, wfr.Namespace)
if err != nil {
log.WithField("wfr", wfr.Name).Error("Failed to create workflowrun operator: ", err)
return
}
operator.ResolveGlobalVariables()
if err := operator.Reconcile(); err != nil {
log.WithField("wfr", wfr.Name).Error("Reconcile error: ", err)
}
}
// ObjectUpdated handles a updated WorkflowRun
func (h *Handler) ObjectUpdated(old, new interface{}) {
originWfr, ok := new.(*v1alpha1.WorkflowRun)
if !ok {
log.Warning("unknown resource type")
return
}
if !validate(originWfr) {
log.WithField("wfr", originWfr.Name).Warning("Invalid wfr")
return
}
// Refresh updates 'refresh' time field of the WorkflowRun in the queue.
h.LimitedQueues.Refresh(originWfr)
// If the WorkflowRun has not yet be started to execute, check the parallelism constraints to determine
// whether to execute it.
var toRun bool
if originWfr.Status.Overall.Phase == "" {
log.WithField("wfr", originWfr.Name).Info("Attempt to run WorkflowRun")
switch h.ParallelismController.AttemptNew(originWfr.Namespace, originWfr.Spec.WorkflowRef.Name, originWfr.Name) {
case workflowrun.AttemptActionQueued:
log.WithField("wfr", originWfr.Name).Infof("Too many WorkflowRun are running, stay pending in queue, will retry in %s", common.ResyncPeriod.String())
return
case workflowrun.AttemptActionFailed:
if err := h.SetStatus(originWfr.Namespace, originWfr.Name, &v1alpha1.Status{
Phase: v1alpha1.StatusFailed,
Reason: "TooManyWaiting",
LastTransitionTime: metav1.Time{Time: time.Now()},
}); err != nil {
log.WithField("wfr", originWfr.Name).Error("Set status to Failed error, ", err)
return
}
case workflowrun.AttemptActionStart:
toRun = true
}
}
if !toRun && reflect.DeepEqual(old, new) {
return
}
log.WithField("name", originWfr.Name).Debug("Start to process WorkflowRun update")
// Add the WorkflowRun object to GC processor, it will be checked before actually added to
// the GC queue.
h.GCProcessor.Add(originWfr)
// If the WorkflowRun has already been terminated(Completed, Failed, Cancelled), send notifications if necessary,
// otherwise directly skip it.
if workflowrun.IsWorkflowRunTerminated(originWfr) {
// If the WorkflowRun already terminated, mark it in the ParallelismController.
h.ParallelismController.MarkFinished(originWfr.Namespace, originWfr.Spec.WorkflowRef.Name, originWfr.Name)
// Send notification after workflowrun terminated.
err := h.sendNotification(originWfr)
if err != nil {
log.WithField("wfr", originWfr.Name).Warn("send notification failed", err)
}
return
}
// If the WorkflowRun has already been terminated or waiting for external events, skip it.
if originWfr.Status.Overall.Phase == v1alpha1.StatusSucceeded ||
originWfr.Status.Overall.Phase == v1alpha1.StatusFailed ||
originWfr.Status.Overall.Phase == v1alpha1.StatusWaiting {
return
}
wfr := originWfr.DeepCopy()
clusterClient := common.GetExecutionClusterClient(wfr)
if clusterClient == nil {
log.WithField("wfr", wfr.Name).Error("Execution cluster client not found")
return
}
operator, err := workflowrun.NewOperator(clusterClient, h.Client, wfr, wfr.Namespace)
if err != nil {
log.WithField("wfr", wfr.Name).Error("Failed to create workflowrun operator: ", err)
return
}
if err := operator.Reconcile(); err != nil {
log.WithField("wfr", wfr.Name).Error("Reconcile error: ", err)
}
}
// ObjectDeleted handles the case when a WorkflowRun get deleted. It will perform GC immediately for this WorkflowRun.
func (h *Handler) ObjectDeleted(obj interface{}) {
originWfr, ok := obj.(*v1alpha1.WorkflowRun)
if !ok {
log.Warning("unknown resource type")
return
}
log.WithField("name", originWfr.Name).Debug("Start to GC for WorkflowRun delete")
// Mark the WorkflowRun terminated in ParallelismController
defer func() {
h.ParallelismController.MarkFinished(originWfr.Namespace, originWfr.Name, originWfr.Spec.WorkflowRef.Name)
}()
wfr := originWfr.DeepCopy()
clusterClient := common.GetExecutionClusterClient(wfr)
if clusterClient == nil {
log.WithField("wfr", wfr.Name).Error("Execution cluster client not found")
return
}
operator, err := workflowrun.NewOperator(clusterClient, h.Client, wfr, wfr.Namespace)
if err != nil {
log.WithField("wfr", wfr.Name).Error("Failed to create workflowrun operator: ", err)
return
}
err = operator.GC(true, true)
if err != nil {
log.WithField("wfr", wfr.Name).Warn("GC failed", err)
}
}
// sendNotification sends notifications for workflowruns when:
// * notification endpoint is configured
// * without notification sent label
func (h *Handler) sendNotification(wfr *v1alpha1.WorkflowRun) error {
// Get latest WorkflowRun.
latestWfr, err := h.Client.CycloneV1alpha1().WorkflowRuns(wfr.Namespace).Get(wfr.Name, metav1.GetOptions{})
if err != nil {
return err
}
if meta.LabelExists(latestWfr.Labels, meta.LabelWorkflowRunNotificationSent) {
return nil
}
sent := false
defer func() {
// Update WorkflowRun notification status with retry.
err := retry.RetryOnConflict(retry.DefaultRetry, func() error {
// Get latest WorkflowRun.
latest, err := h.Client.CycloneV1alpha1().WorkflowRuns(wfr.Namespace).Get(wfr.Name, metav1.GetOptions{})
if err != nil {
return err
}
latest.Labels = meta.AddNotificationSentLabel(latest.Labels, sent)
_, err = h.Client.CycloneV1alpha1().WorkflowRuns(wfr.Namespace).Update(latest)
return err
})
if err != nil {
log.WithField("name", wfr.Name).Error("Update workflowrun notification sent label error: ", err)
}
}()
url := controller.Config.NotificationURL
if url != "" {
// Send notifications with workflowrun.
bodyBytes, err := json.Marshal(wfr)
if err != nil {
log.WithField("wfr", wfr.Name).Errorf("Failed to marshal workflowrun: %v", err)
return err
}
body := bytes.NewReader(bodyBytes)
req, err := http.NewRequest(http.MethodPost, url, body)
if err != nil {
log.WithField("wfr", wfr.Name).Errorf("Failed to new notification request: %v", err)
return err
}
// Set Json content type in Http header.
req.Header.Set(utilhttp.HeaderContentType, utilhttp.HeaderContentTypeJSON)
resp, err := http.DefaultClient.Do(req)
if err != nil {
log.WithField("wfr", wfr.Name).Errorf("Failed to send notification: %v", err)
return err
}
log.WithField("wfr", wfr.Name).Infof("Status code of notification: %d", resp.StatusCode)
sent = true
}
return nil
}
// SetStatus sets workflowRun status
func (h *Handler) SetStatus(ns, wfr string, status *v1alpha1.Status) error {
return retry.RetryOnConflict(retry.DefaultRetry, func() error {
latest, err := h.Client.CycloneV1alpha1().WorkflowRuns(ns).Get(wfr, metav1.GetOptions{})
if err != nil {
return err
}
if latest.Status.Overall.Phase == status.Phase {
return nil
}
toUpdate := latest.DeepCopy()
toUpdate.Status.Overall = *status
_, err = h.Client.CycloneV1alpha1().WorkflowRuns(latest.Namespace).Update(toUpdate)
if err == nil {
log.WithField("wfr", toUpdate.Name).
WithField("status", status.Phase).
Info("WorkflowRun status updated successfully.")
}
return err
})
}
// validate workflow run
func validate(wfr *v1alpha1.WorkflowRun) bool {
// check workflowRef can not be nil
if wfr.Spec.WorkflowRef == nil {
log.WithField("name", wfr.Name).Error("WorkflowRef is nil")
return false
}
return true
}