-
Notifications
You must be signed in to change notification settings - Fork 0
/
runner.go
311 lines (260 loc) · 7.72 KB
/
runner.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
package job
import (
"bytes"
"context"
"errors"
"fmt"
"io/ioutil"
"net/http"
"os/exec"
"strings"
"text/template"
"time"
"github.com/mattn/go-shellwords"
log "github.com/sirupsen/logrus"
)
type JobRunner struct {
job *Job
meta Metadata
numberOfAttempts uint
currentRetries uint
currentStat *JobStat
}
var (
ErrJobDisabled = errors.New("Job cannot run, as it is disabled")
ErrJobDeleted = errors.New("Job cannot run, as it is deleted")
ErrCmdIsEmpty = errors.New("Job Command is empty.")
ErrJobTypeInvalid = errors.New("Job Type is not valid.")
ErrInvalidDelimiters = errors.New("Job has invalid templating delimiters.")
)
// Run calls the appropriate run function, collects metadata around the success
// or failure of the Job's execution, and schedules the next run.
func (j *JobRunner) Run(cache JobCache) (*JobStat, Metadata, error) {
j.job.lock.RLock()
defer j.job.lock.RUnlock()
j.meta.LastAttemptedRun = j.job.clk.Time().Now()
if !cache.Has(j.job.Id) {
log.Infof("Job %s with id %s tried to run, but exited early because its deleted", j.job.Name, j.job.Id)
return nil, j.meta, ErrJobDeleted
}
if j.job.Disabled {
log.Infof("Job %s tried to run, but exited early because its disabled.", j.job.Name)
return nil, j.meta, ErrJobDisabled
}
log.Infof("Job %s:%s started.", j.job.Name, j.job.Id)
j.runSetup()
var out string
for {
var err error
switch {
case j.job.succeedInstantly:
out = "Job succeeded instantly for test purposes."
case j.job.JobType == LocalJob:
out, err = j.LocalRun()
case j.job.JobType == RemoteJob:
out, err = j.RemoteRun()
default:
err = ErrJobTypeInvalid
}
if err != nil {
// Log Error in Metadata
// TODO - Error Reporting, email error
log.Errorln("Error running job:", j.currentStat.JobId)
log.Errorln(err)
j.meta.ErrorCount++
j.meta.LastError = j.job.clk.Time().Now()
// Handle retrying
if j.shouldRetry() {
j.currentRetries--
continue
}
j.collectStats(false)
j.meta.NumberOfFinishedRuns++
// TODO: Wrap error into something better.
return j.currentStat, j.meta, err
} else {
break
}
}
log.Infof("Job %s:%s finished.", j.job.Name, j.job.Id)
log.Debugf("Job %s:%s output: %s", j.job.Name, j.job.Id, out)
j.meta.SuccessCount++
j.meta.NumberOfFinishedRuns++
j.meta.LastSuccess = j.job.clk.Time().Now()
j.collectStats(true)
// Run Dependent Jobs
if len(j.job.DependentJobs) != 0 {
for _, id := range j.job.DependentJobs {
newJob, err := cache.Get(id)
if err != nil {
log.Errorf("Error retrieving dependent job with id of %s", id)
} else {
newJob.Run(cache)
}
}
}
return j.currentStat, j.meta, nil
}
// LocalRun executes the Job's local shell command
func (j *JobRunner) LocalRun() (string, error) {
return j.runCmd()
}
// RemoteRun sends a http request, and checks if the response is valid in time,
func (j *JobRunner) RemoteRun() (string, error) {
// Calculate a response timeout
timeout := j.responseTimeout()
ctx := context.Background()
if timeout > 0 {
var cncl func()
ctx, cncl = context.WithTimeout(ctx, timeout)
defer cncl()
}
// Get the actual url and body we're going to be using,
// including any necessary templating.
url, err := j.tryTemplatize(j.job.RemoteProperties.Url)
if err != nil {
return "", fmt.Errorf("Error templatizing url: %v", err)
}
body, err := j.tryTemplatize(j.job.RemoteProperties.Body)
if err != nil {
return "", fmt.Errorf("Error templatizing body: %v", err)
}
// Normalize the method passed by the user
method := strings.ToUpper(j.job.RemoteProperties.Method)
bodyBuffer := bytes.NewBufferString(body)
req, err := http.NewRequest(method, url, bodyBuffer)
if err != nil {
return "", err
}
// Set default or user's passed headers
j.setHeaders(req)
// Do the request
res, err := http.DefaultClient.Do(req.WithContext(ctx))
if err != nil {
return "", err
}
defer res.Body.Close()
b, err := ioutil.ReadAll(res.Body)
if err != nil {
return "", err
}
// Check if we got any of the status codes the user asked for
if j.checkExpected(res.StatusCode) {
return string(b), nil
} else {
return "", errors.New(res.Status + string(b))
}
}
func initShParser() *shellwords.Parser {
shParser := shellwords.NewParser()
shParser.ParseEnv = true
shParser.ParseBacktick = true
return shParser
}
func (j *JobRunner) runCmd() (string, error) {
j.numberOfAttempts++
// Get the actual command we're going to be running,
// including any necessary templating.
cmdText, err := j.tryTemplatize(j.job.Command)
if err != nil {
return "", fmt.Errorf("Error templatizing command: %v", err)
}
// Execute command
shParser := initShParser()
args, err := shParser.Parse(cmdText)
if err != nil {
return "", err
}
if len(args) == 0 {
return "", ErrCmdIsEmpty
}
cmd := exec.Command(args[0], args[1:]...) //nolint:gosec // That's the job description
out, err := cmd.CombinedOutput()
if err != nil {
return "", fmt.Errorf("%s: %s", err, strings.TrimSpace(string(out)))
}
return strings.TrimSpace(string(out)), nil
}
func (j *JobRunner) tryTemplatize(content string) (string, error) {
delims := j.job.TemplateDelimiters
if delims == "" {
return content, nil
}
split := strings.Split(delims, " ")
if len(split) != 2 { //nolint:gomnd
return "", ErrInvalidDelimiters
}
left, right := split[0], split[1]
if left == "" || right == "" {
return "", ErrInvalidDelimiters
}
t, err := template.New("tmpl").Delims(left, right).Parse(content)
if err != nil {
return "", fmt.Errorf("Error parsing template: %v", err)
}
b := bytes.NewBuffer(nil)
if err := t.Execute(b, j.job); err != nil {
return "", fmt.Errorf("Error executing template: %v", err)
}
return b.String(), nil
}
func (j *JobRunner) shouldRetry() bool {
// Check number of retries left
if j.currentRetries == 0 {
return false
}
// Check Epsilon
if j.job.Epsilon != "" && j.job.Schedule != "" {
if !j.job.epsilonDuration.IsZero() {
timeSinceStart := j.job.clk.Time().Now().Sub(j.job.NextRunAt)
timeLeftToRetry := j.job.epsilonDuration.RelativeTo(j.job.clk.Time().Now()) - timeSinceStart
if timeLeftToRetry < 0 {
return false
}
}
}
return true
}
func (j *JobRunner) runSetup() {
// Setup Job Stat
j.currentStat = NewJobStat(j.job.Id)
// Init retries
j.currentRetries = j.job.Retries
}
func (j *JobRunner) collectStats(success bool) {
j.currentStat.ExecutionDuration = j.job.clk.Time().Now().Sub(j.currentStat.RanAt)
j.currentStat.Success = success
j.currentStat.NumberOfRetries = j.job.Retries - j.currentRetries
}
func (j *JobRunner) checkExpected(statusCode int) bool {
// If no expected response codes passed, add 200 status code as expected
if len(j.job.RemoteProperties.ExpectedResponseCodes) == 0 {
j.job.RemoteProperties.ExpectedResponseCodes = append(j.job.RemoteProperties.ExpectedResponseCodes, 200)
}
for _, expected := range j.job.RemoteProperties.ExpectedResponseCodes {
if expected == statusCode {
return true
}
}
return false
}
// responseTimeout sets a default timeout if none specified
func (j *JobRunner) responseTimeout() time.Duration {
responseTimeout := j.job.RemoteProperties.Timeout
if responseTimeout == 0 {
// set default to 30 seconds
responseTimeout = 30
}
return time.Duration(responseTimeout) * time.Second
}
// setHeaders sets default and user specific headers to the http request
func (j *JobRunner) setHeaders(req *http.Request) {
if j.job.RemoteProperties.Headers == nil {
j.job.RemoteProperties.Headers = http.Header{}
}
// A valid assumption is that the user is sending something in json cause we're past 2017
if j.job.RemoteProperties.Headers["Content-Type"] == nil {
j.job.RemoteProperties.Headers["Content-Type"] = []string{"application/json"}
}
req.Header = j.job.RemoteProperties.Headers
}