forked from gardener/gardener
-
Notifications
You must be signed in to change notification settings - Fork 0
/
flow.go
195 lines (172 loc) · 5.34 KB
/
flow.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
// Copyright 2018 The Gardener 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 flow
import (
"fmt"
"time"
gardenv1beta1 "github.com/gardener/gardener/pkg/apis/garden/v1beta1"
utilerrors "github.com/gardener/gardener/pkg/operation/errors"
"github.com/gardener/gardener/pkg/utils"
"github.com/sirupsen/logrus"
)
// New creates a new Flow object.
func New(name string) *Flow {
return &Flow{
Name: name,
DoneCh: make(chan *Task),
ActiveTasks: TaskList{},
RootTasks: TaskList{},
ErrornousTasks: TaskList{},
}
}
// AddTask takes a <function> and a <retryDuration> and returns a pointer to a Task object.
func (f *Flow) AddTask(function func() error, retryDuration time.Duration, dependsOn ...*Task) *Task {
task := &Task{
Function: function,
RetryDuration: retryDuration,
TriggerTasks: TaskList{},
NumberOfPendingDependencies: len(dependsOn),
}
if len(dependsOn) == 0 {
f.RootTasks = append(f.RootTasks, task)
}
for _, t := range dependsOn {
t.TriggerTasks = append(t.TriggerTasks, task)
}
f.NumberOfExecutableTasks++
return task
}
// AddTaskConditional takes a <function> and a <retryDuration> and returns a pointer to a Task object.
// In case the <condition> is false, the task will be marked as "skipped".
func (f *Flow) AddTaskConditional(function func() error, retryDuration time.Duration, condition bool, dependsOn ...*Task) *Task {
task := f.AddTask(function, retryDuration, dependsOn...)
if !condition {
f.NumberOfExecutableTasks--
}
task.Skip = !condition
return task
}
// AddSyncPoint takes a list of tasks and returns a dummy task which can be used by others
// as dependency. With that, a long list of dependencies must only defined once.
func (f *Flow) AddSyncPoint(dependsOn ...*Task) *Task {
return f.AddTaskConditional(func() error { return nil }, 0, false, dependsOn...)
}
// SetProgressReporter will take a function <reporter> and store it on the Flow object. The
// function will be called whenever the state changes. It will receive the percentage of compeleted
// tasks of the Flow and the list of currently executed functions as arguments.
func (f *Flow) SetProgressReporter(reporter func(int, string)) *Flow {
f.ProgressReporterFunc = reporter
return f
}
// SetLogger will take a <logger> and store it on the Flow object. The logger will be used at the begin of each
// function invocation, and in case of errors.
func (f *Flow) SetLogger(logger *logrus.Entry) *Flow {
f.Logger = logger
return f
}
// Execute will execute all tasks in the flow.
func (f *Flow) Execute() *gardenv1beta1.LastError {
f.infof("Starting flow %s", f.Name)
for _, task := range f.RootTasks {
f.startTask(task)
}
f.handleFlow()
err := f.aggregateErrors()
if err != nil {
return err
}
f.infof("Completed flow %s successfully", f.Name)
return nil
}
func (f *Flow) handleFlow() {
for len(f.ActiveTasks) > 0 {
t := <-f.DoneCh
if !t.Skip {
f.NumberOfCompletedTasks++
}
f.removeFromActiveTasks(t)
if t.Error != nil {
f.errorf("An error occurred while executing %s: %s", t, t.Error.Description)
f.ErrornousTasks = append(f.ErrornousTasks, t)
} else {
f.triggerDependencies(t)
}
if f.ProgressReporterFunc != nil {
f.ProgressReporterFunc(100*f.NumberOfCompletedTasks/(f.NumberOfExecutableTasks), f.ActiveTasks.String())
}
}
close(f.DoneCh)
}
func (f *Flow) startTask(task *Task) {
f.ActiveTasks = append(f.ActiveTasks, task)
go func() {
if !task.Skip {
f.infof("Executing %s", task)
err := utils.Retry(f.Logger, task.RetryDuration, utils.RetryFunc(task.Function))
if err != nil {
task.Error = utilerrors.New(err)
}
} else {
f.infof("Skipped %s", task)
}
f.DoneCh <- task
}()
}
func (f *Flow) triggerDependencies(task *Task) {
for _, t := range task.TriggerTasks {
t.NumberOfPendingDependencies--
if t.NumberOfPendingDependencies == 0 {
f.startTask(t)
}
}
}
func (f *Flow) removeFromActiveTasks(task *Task) {
for i, t := range f.ActiveTasks {
if task == t {
f.ActiveTasks = append(f.ActiveTasks[:i], f.ActiveTasks[i+1:]...)
break
}
}
}
func (f *Flow) aggregateErrors() *gardenv1beta1.LastError {
if len(f.ErrornousTasks) == 0 {
return nil
}
var (
lastError = &gardenv1beta1.LastError{
Codes: []gardenv1beta1.ErrorCode{},
}
e = "Errors occurred during flow execution: "
sep = ""
)
for _, t := range f.ErrornousTasks {
if t.Error.Code != nil {
lastError.Codes = append(lastError.Codes, *(t.Error.Code))
}
e += sep + fmt.Sprintf("'%s' returned '%s'", t, t.Error.Description)
sep = ", "
}
lastError.Description = e
return lastError
}
func (f *Flow) infof(format string, args ...interface{}) {
if f.Logger != nil {
f.Logger.Infof(format, args...)
}
}
func (f *Flow) errorf(format string, args ...interface{}) {
if f.Logger != nil {
f.Logger.Errorf(format, args...)
}
}