-
Notifications
You must be signed in to change notification settings - Fork 3
/
dockrun.go
309 lines (270 loc) · 8.16 KB
/
dockrun.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
package main
import (
"fmt"
"io/ioutil"
"os"
"os/exec"
"os/signal"
"strconv"
"strings"
"syscall"
"time"
)
type cmdResult struct {
output string
exitCode int
err error
}
func getExitCode(err error) (int, error) {
exitCode := 0
if exiterr, ok := err.(*exec.ExitError); ok {
if procExit := exiterr.Sys().(syscall.WaitStatus); ok {
return procExit.ExitStatus(), nil
}
}
return exitCode, fmt.Errorf("failed to get exit code")
}
func runCommandWithOutput(cmd *exec.Cmd) (output string, exitCode int, err error) {
exitCode = 0
out, err := cmd.CombinedOutput()
if err != nil {
var exiterr error
if exitCode, exiterr = getExitCode(err); exiterr != nil {
// TODO: Fix this so we check the error's text.
// we've failed to retrieve exit code, so we set it to 127
exitCode = 127
}
}
output = string(out)
return
}
func runCommand(cmd *exec.Cmd) (exitCode int, err error) {
exitCode = 0
err = cmd.Run()
if err != nil {
var exiterr error
if exitCode, exiterr = getExitCode(err); exiterr != nil {
// TODO: Fix this so we check the error's text.
// we've failed to retrieve exit code, so we set it to 127
exitCode = 127
}
}
return
}
func startCommand(cmd *exec.Cmd) (exitCode int, err error) {
exitCode = 0
err = cmd.Start()
if err != nil {
var exiterr error
if exitCode, exiterr = getExitCode(err); exiterr != nil {
// TODO: Fix this so we check the error's text.
// we've failed to retrieve exit code, so we set it to 127
exitCode = 127
}
}
return
}
func runCommandWithOutputResult(cmd *exec.Cmd) cmdResult {
output, exitCode, err := runCommandWithOutput(cmd)
return cmdResult{output, exitCode, err}
}
func runCommandSendResult(cmd *exec.Cmd, c chan cmdResult) {
c <- runCommandWithOutputResult(cmd)
}
func waitForResult(containerID string, signals chan os.Signal, waitCmd chan cmdResult) cmdResult {
for {
select {
case sig := <-signals:
fmt.Printf("Received signal: %s; cleaning up\n", sig)
cmd := exec.Command("docker", "stop", "-t", "2", containerID)
out, _, err := runCommandWithOutput(cmd)
if err != nil || strings.Contains(out, "Error") {
fmt.Printf("stopping container via signal %s failed\n", sig)
}
case waitResult := <-waitCmd:
return waitResult
}
}
}
func validateArgs(args []string) {
failed := false
if len(args) < 1 {
fmt.Println("dockrun [OPTIONS] IMAGE [COMMAND]")
fmt.Println("OPTIONS - same options as docker run, without -a & -d")
failed = true
}
for _, val := range args {
if val == "-a" {
fmt.Printf("ERROR: dockrun doesn't support -a\n")
failed = true
}
}
if failed {
os.Exit(1)
}
}
func stringInArgs(args []string, target string) (bool, int) {
for key, value := range args {
if value == target {
return true, key
}
}
return false, -1
}
func filterSlice(s []string, fn func(int, string) bool) []string {
var newSlice []string
for k, v := range s {
if fn(k, v) {
newSlice = append(newSlice, v)
}
}
return newSlice
}
func filterNamedArgs(flagsToFilter []string, args []string) []string {
filteredArgs := filterSlice(args, func(k int, s string) bool {
shouldFilter, _ := stringInArgs(flagsToFilter, s)
return !shouldFilter
})
return filteredArgs
}
func filterArgsByPosition(flagsToFilter []int, args []string) []string {
var positions []string
for _, v := range flagsToFilter {
positions = append(positions, strconv.Itoa(v))
}
filteredArgs := filterSlice(args, func(k int, s string) bool {
shouldFilter, _ := stringInArgs(positions, strconv.Itoa(k))
return !shouldFilter
})
return filteredArgs
}
// WARNING: 'docker wait', 'docker logs', 'docker rm', 'docker kill' and 'docker stop'
// exit with status code 0 even if they've failed.
func main() {
var containerID string
var finalExitCode int
var repo string
defaultArgs := []string{"run", "-cidfile"}
args := os.Args[1:]
validateArgs(args)
flagsToFilter := []string{"-rm"}
autoRemoveContainer, _ := stringInArgs(args, "-rm")
commitContainer, commitArgPosition := stringInArgs(args, "-commit")
userCIDFile, userCIDFilePosition := stringInArgs(args, "-cidfile")
if commitContainer {
repoArgPosition := commitArgPosition + 1
repo = args[repoArgPosition]
argPositionsToFilter := []int{repoArgPosition, commitArgPosition}
args = filterArgsByPosition(argPositionsToFilter, args)
}
CIDFilename := ""
if userCIDFile {
namePosition := userCIDFilePosition + 1
CIDFilename = args[namePosition]
argPositionsToFilter := []int{namePosition, userCIDFilePosition}
args = filterArgsByPosition(argPositionsToFilter, args)
}
filteredArgs := filterNamedArgs(flagsToFilter, args)
if len(CIDFilename) == 0 {
getTempFilename := exec.Command("mktemp", "-u")
if out, exitCode, err := runCommandWithOutput(getTempFilename); err != nil {
fmt.Printf("mktemp failed: %s\n", CIDFilename)
fmt.Printf("ERROR mktemp failed with exit code: %d\n", exitCode)
os.Exit(1)
} else {
CIDFilename = strings.Trim(string(out), "\n")
}
}
defaultArgs = append(defaultArgs, CIDFilename)
finalArgs := append(defaultArgs, filteredArgs...)
startCmd := exec.Command("docker", finalArgs...)
startCmd.Stdout = os.Stdout
startCmd.Stdin = os.Stdin
startCmd.Stderr = os.Stderr
if exitCode, err := startCommand(startCmd); err != nil {
fmt.Printf("ERROR docker exited with exit code: %d\n", exitCode)
os.Exit(1)
}
for i := 0; i <= 10; i++ {
if out, err := ioutil.ReadFile(CIDFilename); err != nil {
if i == 10 {
fmt.Printf("ERROR couldn't read container ID from %s\n", CIDFilename)
os.Exit(1)
}
} else {
containerID = strings.Trim(string(out), "\n")
break
}
time.Sleep(100 * time.Millisecond)
}
if len(containerID) < 4 {
fmt.Printf("ERROR: docker container ID is too small, possibly invalid\n")
os.Exit(1)
}
// hack to handle signals & wait for "docker wait" to be finished
signals := make(chan os.Signal, 1)
signal.Notify(signals, syscall.SIGINT, syscall.SIGTERM)
waitCmdRes := make(chan cmdResult, 1)
waitCmd := exec.Command("docker", "wait", containerID)
go runCommandSendResult(waitCmd, waitCmdRes)
waitResult := waitForResult(containerID, signals, waitCmdRes)
waitOutput := waitResult.output
waiterr := waitResult.err
// try to run 'docker wait' again; this is needed when we receive a
// signal and 'docker wait' fails to retrieve the correct exit code
// of the container
if waiterr != nil {
waitCmd := exec.Command("docker", "wait", containerID)
waitOutput, _, waiterr = runCommandWithOutput(waitCmd)
}
// end hack
if waiterr != nil || strings.Contains(waitOutput, "Error") {
// docker wait failed
fmt.Printf("ERROR: docker wait: %s %s\n", waitOutput, waiterr)
fmt.Printf("ERROR: docker wait failed\n")
os.Exit(1)
}
waitOutput = strings.Trim(waitOutput, "\n")
finalExitCode, err := strconv.Atoi(waitOutput)
if err != nil {
fmt.Println(waitOutput)
fmt.Printf("ERROR: failed to convert exit code to int\n")
os.Exit(1)
}
if err = os.Remove(CIDFilename); err != nil {
fmt.Printf("WARNING: failed to remove container ID file\n")
}
if commitContainer && finalExitCode == 0 {
commitCmd := exec.Command("docker", "commit", containerID)
commitOutput, _, err := runCommandWithOutput(commitCmd)
if err != nil || strings.Contains(commitOutput, "Error") {
fmt.Printf("ERROR: docker commit failed: %s %s\n", commitOutput, err)
os.Exit(1)
}
var tagCmd *exec.Cmd
imageID := strings.Trim(string(commitOutput), "\n")
repoAndTag := strings.Split(repo, ":")
if len(repoAndTag) > 1 {
repoName := repoAndTag[0]
tag := repoAndTag[1]
tagCmd = exec.Command("docker", "tag", imageID, repoName, tag)
} else {
tagCmd = exec.Command("docker", "tag", imageID, repo)
}
tagOutput, _, err := runCommandWithOutput(tagCmd)
if err != nil || strings.Contains(tagOutput, "Error") {
fmt.Printf("ERROR: docker tag failed: %s %s\n", tagOutput, err)
os.Exit(1)
}
}
if autoRemoveContainer {
rmCmd := exec.Command("docker", "rm", containerID)
rmOutput, _, rmerr := runCommandWithOutput(rmCmd)
if rmerr != nil || strings.Contains(rmOutput, "Error") {
fmt.Printf("ERROR: docker rm: %s %s\n", rmOutput, rmerr)
fmt.Printf("ERROR: docker rm failed\n")
// fall through and let the return code of the container go through
}
}
os.Exit(finalExitCode)
}