-
Notifications
You must be signed in to change notification settings - Fork 6
/
run.go
529 lines (470 loc) · 14 KB
/
run.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
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
package main
import (
"context"
"encoding/base64"
"encoding/json"
"fmt"
"os"
"path"
"strings"
"github.com/cyverse-de/messaging"
"github.com/cyverse-de/model"
"github.com/cyverse-de/road-runner/dcompose"
"github.com/cyverse-de/road-runner/fs"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"github.com/spf13/viper"
)
// logrusProxyWriter will prevent
// "Error while reading from Writer: bufio.Scanner: token too long" errors
// if a docker command generates a lot of output
// (from pulling many input containers at once, for example)
// and Logrus attempts to log all of that output in one log line.
type logrusProxyWriter struct {
entry *logrus.Entry
}
func (w *logrusProxyWriter) Write(b []byte) (int, error) {
return fmt.Fprint(w.entry.Writer(), string(b))
}
var logWriter = &logrusProxyWriter{
entry: log,
}
// JobRunner provides the functionality needed to run jobs.
type JobRunner struct {
client JobUpdatePublisher
exit chan messaging.StatusCode
job *model.Job
status messaging.StatusCode
cfg *viper.Viper
logsDir string
volumeDir string
workingDir string
projectName string
tmpDir string
}
// NewJobRunner creates a new JobRunner
func NewJobRunner(client JobUpdatePublisher, job *model.Job, cfg *viper.Viper, exit chan messaging.StatusCode) (*JobRunner, error) {
cwd, err := os.Getwd()
if err != nil {
return nil, err
}
runner := &JobRunner{
client: client,
exit: exit,
job: job,
cfg: cfg,
status: messaging.Success,
workingDir: cwd,
volumeDir: path.Join(cwd, dcompose.VOLUMEDIR),
logsDir: path.Join(cwd, dcompose.VOLUMEDIR, "logs"),
tmpDir: path.Join(cwd, dcompose.TMPDIR),
}
return runner, nil
}
// Init will initialize the state for a JobRunner. The volumeDir and logsDir
// will get created.
func (r *JobRunner) Init() error {
err := os.MkdirAll(r.logsDir, 0755)
if err != nil {
return err
}
err = os.MkdirAll(r.tmpDir, 0755)
if err != nil {
return err
}
// Set world-write perms on volumeDir, so non-root users can create job outputs.
err = os.Chmod(r.volumeDir, 0777)
if err != nil {
// Log error and continue.
log.Error(err)
}
// Set world-write perms on tmpDir, so non-root users can create temp outputs.
err = os.Chmod(r.tmpDir, 0777)
if err != nil {
// Log error and continue.
log.Error(err)
}
// Copy docker-compose file to the log dir for debugging purposes.
err = fs.CopyFile(fs.FS, "docker-compose.yml", path.Join(r.logsDir, "docker-compose.yml"))
if err != nil {
// Log error and continue.
log.Error(err)
}
// Copy upload exclude list to the log dir for debugging purposes.
err = fs.CopyFile(fs.FS, dcompose.UploadExcludesFilename, path.Join(r.logsDir, dcompose.UploadExcludesFilename))
if err != nil {
// Log error and continue.
log.Error(err)
}
// Copy input path list to the log dir for debugging purposes.
if r.job.InputPathListFile != "" {
err = fs.CopyFile(fs.FS, r.job.InputPathListFile, path.Join(r.logsDir, r.job.InputPathListFile))
if err != nil {
// Log error and continue.
log.Error(err)
}
}
transferTrigger, err := os.Create(path.Join(r.logsDir, "de-transfer-trigger.log"))
if err != nil {
return err
}
defer transferTrigger.Close()
_, err = transferTrigger.WriteString("This is only used to force HTCondor to transfer files.")
if err != nil {
return err
}
if _, err = os.Stat("iplant.cmd"); err != nil {
if err = os.Rename("iplant.cmd", path.Join(r.logsDir, "iplant.cmd")); err != nil {
return err
}
}
return nil
}
// GetDockerCreds will obtain a list of Docker credentials for the current job. This function assumes that there will be
// at most one set of credentials for each Docker registry. The result is a map from docker registry to credentials.
func (r *JobRunner) getDockerCreds() (map[string]*authInfo, error) {
result := make(map[string]*authInfo)
// Check each step in the job for credentials.
for _, step := range r.job.Steps {
container := step.Component.Container
// Add any credentials for the tool container.
if container.Image.Auth != "" {
repo := parseRepo(container.Image.Name)
creds, err := parse(container.Image.Auth)
if err != nil {
return nil, err
}
result[repo] = creds
}
// Add any credentials for data containers.
for _, dataContainer := range container.VolumesFrom {
if dataContainer.Auth != "" {
repo := parseRepo(dataContainer.Name)
creds, err := parse(dataContainer.Auth)
if err != nil {
return nil, err
}
result[repo] = creds
}
}
}
return result, nil
}
// DockerLogin will run "docker login" with credentials sent with the job.
func (r *JobRunner) DockerLogin(ctx context.Context) error {
var err error
// Get credentials for each registry that requires authentication.
creds, err := r.getDockerCreds()
if err != nil {
return err
}
// Log in to the docker registres so that images can be pulled.
for registry, cred := range creds {
authCommand := DockerCommandContext(
r.cfg,
ctx,
"login",
"--username",
cred.Username,
"--password",
cred.Password,
registry,
)
authCommand.Env = os.Environ()
authCommand.Stderr = logWriter
authCommand.Stdout = logWriter
if err = authCommand.Run(); err != nil {
return errors.Wrapf(err, "failed to log into Docker registry %s", registry)
}
}
return nil
}
// JobUpdatePublisher is the interface for types that need to publish a job
// update.
type JobUpdatePublisher interface {
PublishJobUpdate(m *messaging.UpdateMessage) error
}
func (r *JobRunner) createDataContainers(ctx context.Context) (messaging.StatusCode, error) {
var (
err error
)
for stepIndex, step := range r.job.Steps {
for dcIndex := range step.Component.Container.VolumesFrom {
svcname := fmt.Sprintf("data_%d_%d", stepIndex, dcIndex)
running(r.client, r.job, fmt.Sprintf("creating data container %s", svcname))
dataCommand := DockerComposeCommandContext(
r.cfg,
ctx,
"-p",
r.projectName,
"-f",
"docker-compose.yml",
"up",
"--abort-on-container-exit",
"--exit-code-from", svcname,
"--no-color",
svcname,
)
dataCommand.Env = os.Environ()
dataCommand.Stderr = logWriter
dataCommand.Stdout = logWriter
if err = dataCommand.Run(); err != nil {
running(r.client, r.job, fmt.Sprintf("error creating data container %s: %s", svcname, err.Error()))
return messaging.StatusDockerCreateFailed, errors.Wrapf(err, "failed to create data container %s", svcname)
}
running(r.client, r.job, fmt.Sprintf("finished creating data container %s", svcname))
}
}
return messaging.Success, nil
}
func (r *JobRunner) downloadInputs(ctx context.Context) (messaging.StatusCode, error) {
env := os.Environ()
if job.InputPathListFile != "" {
return r.downloadInputStep(ctx, "download_inputs", job.InputPathListFile, env)
}
for index, input := range r.job.Inputs() {
svcname := fmt.Sprintf("input_%d", index)
if status, err := r.downloadInputStep(ctx, svcname, input.IRODSPath(), env); err != nil {
return status, err
}
}
return messaging.Success, nil
}
func (r *JobRunner) downloadInputStep(ctx context.Context, svcname, inputPath string, env []string) (messaging.StatusCode, error) {
var (
exitCode int64
)
running(r.client, r.job, fmt.Sprintf("Downloading %s", inputPath))
stderr, err := os.Create(path.Join(r.logsDir, fmt.Sprintf("logs-stderr-%s", svcname)))
if err != nil {
log.Error(err)
}
defer stderr.Close()
stdout, err := os.Create(path.Join(r.logsDir, fmt.Sprintf("logs-stdout-%s", svcname)))
if err != nil {
log.Error(err)
}
defer stdout.Close()
downloadCommand := DockerComposeCommandContext(
r.cfg,
ctx,
"-p", r.projectName,
"-f", "docker-compose.yml",
"up",
"--no-color",
"--abort-on-container-exit",
"--exit-code-from", svcname,
svcname,
)
downloadCommand.Env = env
downloadCommand.Stderr = stderr
downloadCommand.Stdout = stdout
if err = downloadCommand.Run(); err != nil {
running(r.client, r.job, fmt.Sprintf("error downloading %s: %s", inputPath, err.Error()))
return messaging.StatusInputFailed, errors.Wrapf(err, "failed to download %s with an exit code of %d", inputPath, exitCode)
}
stdout.Close()
stderr.Close()
running(r.client, r.job, fmt.Sprintf("finished downloading %s", inputPath))
return messaging.Success, nil
}
type authInfo struct {
Username string
Password string
}
func parse(b64 string) (*authInfo, error) {
jsonstring, err := base64.StdEncoding.DecodeString(b64)
if err != nil {
return nil, err
}
a := &authInfo{}
err = json.Unmarshal(jsonstring, a)
return a, err
}
func (r *JobRunner) runAllSteps(ctx context.Context) (messaging.StatusCode, error) {
var err error
for idx, step := range r.job.Steps {
running(r.client, r.job,
fmt.Sprintf(
"Running tool container %s:%s with arguments: %s",
step.Component.Container.Image.Name,
step.Component.Container.Image.Tag,
strings.Join(step.Arguments(), " "),
),
)
stdout, err := os.Create(path.Join(r.logsDir, fmt.Sprintf("docker-compose-step-stdout-%d", idx)))
if err != nil {
log.Error(err)
}
defer stdout.Close()
stderr, err := os.Create(path.Join(r.logsDir, fmt.Sprintf("docker-compose-step-stderr-%d", idx)))
if err != nil {
log.Error(err)
}
defer stderr.Close()
svcname := fmt.Sprintf("step_%d", idx)
runCommand := DockerComposeCommandContext(
r.cfg,
ctx,
"-p", r.projectName,
"-f", "docker-compose.yml",
"up",
"--abort-on-container-exit",
"--exit-code-from", svcname,
"--no-color",
svcname,
)
runCommand.Env = os.Environ()
runCommand.Stdout = stdout
runCommand.Stderr = stderr
err = runCommand.Run()
if err != nil {
running(r.client, r.job,
fmt.Sprintf(
"Error running tool container %s:%s with arguments '%s': %s",
step.Component.Container.Image.Name,
step.Component.Container.Image.Tag,
strings.Join(step.Arguments(), " "),
err.Error(),
),
)
return messaging.StatusStepFailed, err
}
running(r.client, r.job,
fmt.Sprintf("Tool container %s:%s with arguments '%s' finished successfully",
step.Component.Container.Image.Name,
step.Component.Container.Image.Tag,
strings.Join(step.Arguments(), " "),
),
)
// stdout.Close()
// stderr.Close()
}
return messaging.Success, err
}
func (r *JobRunner) uploadOutputs() (messaging.StatusCode, error) {
var err error
stdout, err := os.Create(path.Join(r.logsDir, "logs-stdout-output"))
if err != nil {
log.Error(err)
}
defer stdout.Close()
stderr, err := os.Create(path.Join(r.logsDir, "logs-stderr-output"))
if err != nil {
log.Error(err)
}
defer stderr.Close()
outputCommand := DockerComposeCommand(
r.cfg,
"-p", r.projectName,
"-f", "docker-compose.yml",
"up",
"--no-color",
"--abort-on-container-exit",
"--exit-code-from", "upload_outputs",
"upload_outputs",
)
outputCommand.Stdout = stdout
outputCommand.Stderr = stderr
err = outputCommand.Run()
if err != nil {
running(r.client, r.job, fmt.Sprintf("Error uploading outputs to %s: %s", r.job.OutputDirectory(), err.Error()))
return messaging.StatusOutputFailed, errors.Wrapf(err, "failed to upload outputs to %s", r.job.OutputDirectory())
}
running(r.client, r.job, fmt.Sprintf("Done uploading outputs to %s", r.job.OutputDirectory()))
return messaging.Success, nil
}
func parseRepo(imagename string) string {
if strings.Contains(imagename, "/") {
parts := strings.Split(imagename, "/")
return parts[0]
}
return ""
}
// Run executes the job, and returns the exit code on the exit channel.
func Run(ctx context.Context, client JobUpdatePublisher, job *model.Job, cfg *viper.Viper, exit chan messaging.StatusCode) {
host, err := os.Hostname()
if err != nil {
log.Error(err)
host = "UNKNOWN"
}
runner, err := NewJobRunner(client, job, cfg, exit)
if err != nil {
log.Error(err)
}
err = runner.Init()
if err != nil {
log.Error(err)
}
runner.projectName = strings.Replace(runner.job.InvocationID, "-", "", -1)
// let everyone know the job is running
running(runner.client, runner.job, fmt.Sprintf("Job %s is running on host %s", runner.job.InvocationID, host))
if err = runner.DockerLogin(ctx); err != nil {
log.Error(err)
}
pullCommand := DockerComposeCommandContext(
cfg,
ctx,
"-p",
runner.projectName,
"-f",
"docker-compose.yml",
"pull",
"--parallel",
)
pullCommand.Env = os.Environ()
pullCommand.Dir = runner.workingDir
pullCommand.Stdout = logWriter
pullCommand.Stderr = logWriter
err = pullCommand.Run()
if err != nil {
log.Error(err)
runner.status = messaging.StatusDockerPullFailed
}
if err = fs.WriteJobSummary(fs.FS, runner.logsDir, job); err != nil {
log.Error(err)
}
if err = fs.WriteJobParameters(fs.FS, runner.logsDir, job); err != nil {
log.Error(err)
}
if runner.status == messaging.Success {
if runner.status, err = runner.createDataContainers(ctx); err != nil {
log.Error(err)
}
}
// If pulls didn't succeed then we can't guarantee that we've got the
// correct versions of the tools. Don't bother pulling in data in that case,
// things are already screwed up.
if runner.status == messaging.Success {
if runner.status, err = runner.downloadInputs(ctx); err != nil {
log.Error(err)
}
}
// Only attempt to run the steps if the input downloads succeeded. No reason
// to run the steps if there's no/corrupted data to operate on.
if runner.status == messaging.Success {
if runner.status, err = runner.runAllSteps(ctx); err != nil {
log.Error(err)
}
}
// Always attempt to transfer outputs. There might be logs that can help
// debug issues when the job fails.
var outputStatus messaging.StatusCode
running(runner.client, runner.job, fmt.Sprintf("Beginning to upload outputs to %s", runner.job.OutputDirectory()))
if outputStatus, err = runner.uploadOutputs(); err != nil {
log.Error(err)
}
if outputStatus != messaging.Success {
runner.status = outputStatus
}
// Always inform upstream of the job status.
if runner.status != messaging.Success {
err = fail(runner.client, runner.job, fmt.Sprintf("Job exited with a status of %d", runner.status))
} else {
err = success(runner.client, runner.job)
}
if err != nil {
log.Error(err)
}
exit <- runner.status
}