/
workflow.go
330 lines (273 loc) · 7.53 KB
/
workflow.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
package utils
import (
"bytes"
"context"
"errors"
"fmt"
"html/template"
"io"
"io/ioutil"
"sync"
"time"
"github.com/hashicorp/go-multierror"
"github.com/sirupsen/logrus"
"github.com/spf13/viper"
"github.com/thanhpk/randstr"
"golang.org/x/sync/semaphore"
"gopkg.in/yaml.v2"
)
// WorkflowOptions provides options for a workflow
type WorkflowOptions struct {
Notifier func(ctx context.Context, logger *logrus.Logger, event *Event) error
Concurrency int
Timeout time.Duration
Metadata map[string]string
}
// Workflow is the internal object to hold a workflow file
type Workflow struct {
Version string `yaml:"version" json:"version"`
Metadata map[string]string `yaml:"metadata" json:"metadata"`
Steps []*Step `yaml:"steps" json:"steps"`
Logger *LogDefinition `yaml:"logger" json:"logger"`
options *WorkflowOptions
logger *logrus.Logger
gatekeeper *semaphore.Weighted
signal *sync.Mutex
stopFlag bool
sessionID string
}
// LoadWorkflowFromBytes loads a workflow from bytes
func LoadWorkflowFromBytes(ctx context.Context, options *WorkflowOptions, buff []byte) (*Workflow, error) {
var workflow *Workflow
err := yaml.Unmarshal(buff, &workflow)
if err != nil {
return nil, err
}
if options == nil {
panic("no options")
}
if options.Notifier == nil {
panic("no notifier")
}
if workflow.Version != "1" {
return nil, errors.New("invalid workflow version")
}
workflow.sessionID = randstr.String(8)
workflow.gatekeeper = semaphore.NewWeighted(int64(options.Concurrency))
workflow.options = options
workflow.stopFlag = false
workflow.signal = &sync.Mutex{}
// merge options metadata with yaml
workflow.Metadata = mergeMaps(workflow.Metadata, workflow.options.Metadata, true)
logger, err := NewLogger(workflow.Logger, NewLoggingContext(workflow, nil))
if err != nil {
return nil, err
}
workflow.logger = logger
// validate depends on and link them to the step
// TODO: check for circular dependencies
for idx, step := range workflow.Steps {
workflow.Steps[idx].SessionID = workflow.SessionID()
workflow.Steps[idx].workflow = workflow
for _, priorStepName := range step.DependsOn {
priorStep := workflow.findStepByName(priorStepName)
if priorStep == nil {
return nil, fmt.Errorf("invalid step name in depends_on for step %s (%s)", step.Name, priorStepName)
}
workflow.Steps[idx].dependsOn = append(workflow.Steps[idx].dependsOn, priorStep)
}
// setup logging for this step
if step.Logger == nil {
logger, err = NewLogger(workflow.Logger, NewLoggingContext(workflow, step))
if err != nil {
return nil, err
}
} else {
logger, err = NewLogger(step.Logger, NewLoggingContext(workflow, step))
if err != nil {
return nil, err
}
}
step.logger = logger
}
if err = workflow.EnrichWorkflow(ctx); err != nil {
return workflow, err
}
return workflow, nil
}
// LoadWorkflowFromReader loads a workflow from an io reader
func LoadWorkflowFromReader(ctx context.Context, options *WorkflowOptions, reader io.Reader) (*Workflow, error) {
buff, err := ioutil.ReadAll(reader)
if err != nil {
return nil, err
}
return LoadWorkflowFromBytes(ctx, options, buff)
}
// SessionID returns the session id of this run for the workflow
func (w *Workflow) SessionID() string {
return w.sessionID
}
func (w *Workflow) preflights(ctx context.Context) (preflights []*Preflight) {
for kdx, step := range w.Steps {
for idx := range step.Preflights {
step.Preflights[idx].step = w.Steps[kdx]
preflights = append(preflights, &step.Preflights[idx])
}
}
return preflights
}
func (w *Workflow) preflightChecks(ctx context.Context) error {
for _, preflight := range w.preflights(ctx) {
err := preflight.Run(ctx)
if err != nil {
if preflight.Message != "" {
// dump the message
w.logger.WithField(FldStep, fmt.Sprintf("%s.preflight", preflight.step.Name)).Error(preflight.Message)
}
return err
}
}
return nil
}
// Run runs the entire workflow
func (w *Workflow) Run(ctx context.Context) (runErrors error, stepErrors error) {
// if w.Logger is null, it's going to use the defaults which should be the same as with the app
// since the default values from from the same place
w.logger.Infof("Running Workflow with Session ID %s", w.sessionID)
w.logger.Info("Running Preflight checks")
err := w.preflightChecks(ctx)
if err != nil {
return err, nil
}
w.logger.Info("Preflight checks complete")
joiner := sync.WaitGroup{}
// Run all that can run
for {
if w.shouldStop(ctx) {
return nil, stepErrors
}
if w.allDone() {
break
}
step := w.nextToRun(ctx)
if step == nil {
continue
}
w.logger.WithField(FldStep, step.Name).Trace("Next to run")
err := w.gatekeeper.Acquire(ctx, 1)
if err != nil {
return err, nil
}
if w.shouldStop(ctx) {
return
}
joiner.Add(1)
go func(toRun *Step) {
if w.shouldStop(ctx) {
return
}
defer func() {
w.logger.WithField(FldStep, toRun.Name).Trace("Done running")
w.gatekeeper.Release(1)
joiner.Done()
}()
w.logger.WithField(FldStep, toRun.Name).Trace("Preparing to run")
if toRun.ShowCommand {
w.logger.WithField(FldStep, toRun.Name).Info(toRun.Command)
}
if !toRun.Disabled && toRun.AskToProceed && !viper.GetBool("confirm.yes") {
// we need an interactive permission for this
if !confirm(fmt.Sprintf("Run %s?", toRun.Name), 1) {
w.logger.WithField(FldStep, toRun.Name).Info("Stopping execution")
w.stop(ctx)
}
}
err := toRun.Run(ctx)
if err != nil {
stepErrors = multierror.Append(err, stepErrors)
// run failed in some way that the whole workflow should stop
w.logger.WithField(FldStep, toRun.Name).Error(err)
w.logger.WithField(FldStep, toRun.Name).Error("Calling a stop to run")
w.stop(ctx)
}
}(step)
}
joiner.Wait()
return nil, stepErrors
}
// nextToRun returns the next step that can run
func (w *Workflow) nextToRun(ctx context.Context) *Step {
// using a universal lock per workflow to pick the next step to run
w.signal.Lock()
defer w.signal.Unlock()
for idx, step := range w.Steps {
if step.shouldRun() {
w.Steps[idx].MarkAsPending()
return w.Steps[idx]
}
}
return nil
}
func (w *Workflow) allDone() bool {
w.signal.Lock()
defer w.signal.Unlock()
for _, step := range w.Steps {
if !step.isDone() {
return false
}
}
return true
}
func (w *Workflow) findStepByName(name string) *Step {
for idx, step := range w.Steps {
if step.Name == name {
return w.Steps[idx]
}
}
return nil
}
func (w *Workflow) stop(ctx context.Context) {
w.signal.Lock()
defer w.signal.Unlock()
w.stopFlag = true
}
func (w *Workflow) shouldStop(ctx context.Context) bool {
w.signal.Lock()
defer w.signal.Unlock()
return w.stopFlag
}
// EnrichWorkflow parses and replaces any placeholders in the workflow
func (w *Workflow) EnrichWorkflow(ctx context.Context) error {
var err error
// meta data first
if w.Metadata != nil {
for idx, metadata := range w.Metadata {
if w.Metadata[idx], err = w.parseAttribute(ctx, metadata); err != nil {
return err
}
}
}
if w.Metadata != nil {
for idx, metadata := range w.Metadata {
if w.Metadata[idx], err = ExpandEnvVars(ctx, metadata); err != nil {
return err
}
}
}
return nil
}
func (w *Workflow) parseAttribute(ctx context.Context, value string) (string, error) {
if value == "" {
return "", nil
}
buf := &bytes.Buffer{}
tmpl, err := template.New("workflow").Parse(value)
if err != nil {
return "", err
}
err = tmpl.Execute(buf, w)
if err != nil {
return "", err
}
return buf.String(), nil
}