forked from elemir/contman
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreceipt.go
101 lines (83 loc) · 1.7 KB
/
receipt.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
package contman
import (
"errors"
"os"
"time"
)
type Receipt struct {
Image string
Cmd string
Env map[string]string
InputCopy map[string]string
OutputCopy map[string]string
Timeout time.Duration
UseControlSocket bool
UseLocalImage bool
OnlyCreate bool
UseImageWorkingDir bool
}
func RunReceipt(cm Manager, receipt Receipt) error {
if !receipt.UseLocalImage {
err := cm.PullImage(receipt.Image)
if err != nil {
return err
}
}
mounts := []Mount{}
if receipt.UseControlSocket {
mounts = cm.GetSystemMounts()
}
wd, err := os.Getwd()
if err != nil {
return err
}
config := Config{
Image: receipt.Image,
Cmd: receipt.Cmd,
Env: receipt.Env,
Mounts: mounts,
}
if !receipt.UseImageWorkingDir {
config.WorkingDir = wd
}
cntr, err := cm.ContainerCreate(config)
if err != nil {
return err
}
defer func() {
isRunning, _ := cntr.IsRunning()
if isRunning {
cntr.Stop(receipt.Timeout)
}
cntr.Remove()
}()
if !receipt.OnlyCreate {
if err := startReceiptContainer(cntr, receipt); err != nil {
return err
}
}
for src, dest := range receipt.OutputCopy {
cntr.CopyFrom(src, dest)
}
return nil
}
func startReceiptContainer(cntr Container, receipt Receipt) error {
for src, dest := range receipt.InputCopy {
if _, err := os.Stat(src); err != nil {
continue
}
cntr.CopyTo(src, dest)
}
if err := cntr.Start(); err != nil {
return err
}
exitCode, err := cntr.Wait(true)
if err != nil {
return err
}
if exitCode != 0 {
cntr.GetLogger().Errorf("Container exited with non-zero code: %d", exitCode)
return errors.New("failed to run receipt")
}
return nil
}