-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
385 lines (325 loc) · 8.17 KB
/
main.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
/*
* docker-run-app run an arbitrary command and forward signals to said command.
* Copyright (c) 2014 Justin Charette <[email protected]> (@boxofrox)
* All Rights Reserved
*
* This program is free software. It comes without any warranty, to
* the extent permitted by applicable law. You can redistribute it
* and/or modify it under the terms of the Do What the Fuck You Want
* to Public License, Version 2, as published by Sam Hocevar. See
* http://www.wtfpl.net/ for more details.
*
*
* Usage: docker-run-app [-h] [--init-log FILE] [--] COMMAND
*
* COMMAND - app and args to execute. app requires full path.
* -- - args after this flag are reserved for COMMAND.
* -h, --help - print this help message.
* --init-log FILE - write docker-run-app output to FILE.
* -V, --version - print version info.
*/
package main
import (
"fmt"
"io"
"log"
"os"
"os/exec"
"os/signal"
"path"
"strings"
"syscall"
"time"
)
var (
VERSION string
BUILD_DATE string
)
const (
SIG_TIMEOUT = time.Second * 2
)
const (
OK AppError = iota
AppStoppedWithError
CannotStartApp
FailedToKillApp
MissingArgument
InsufficientSignalError
InvalidCommand
BadFlag
)
const (
FlagFound FlagError = iota
FlagNotFound
FlagHasTooFewParams
)
type AppError int
type FlagError int
type ParamList []string
func main() {
var (
args []string
err AppError = OK
file *os.File
fileErr error
options map[string]string
)
options, args = parseFlags(os.Args[1:])
if options["init-log"] != "" {
if file, fileErr = os.OpenFile(options["init-log"], os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0664); fileErr != nil {
log.Printf("Cannot open log file (%s). Using stderr.", options["init-log"])
} else {
log.SetOutput(file)
}
}
// has command?
if len(args) == 0 {
usage()
log.Println("missing <command>. ")
err = MissingArgument
} else {
cmd := args[0]
if len(args) > 1 {
args = args[1:]
} else {
args = nil
}
err = runCommand(exec.Command(cmd, args...))
}
if file != nil {
file.Close()
}
os.Exit(int(err))
}
// eatFlag
//
// Search argument array for one flag and possibly one or more parameters.
// The flag can be one or more representations of the same flag (e.g. -h, --help).
// return the file and the remaining options in a new array.
//
func eatFlag(args []string, flags []string, paramCount int) (params ParamList, remaining []string, err FlagError) {
var (
a, b int
)
hasFlag := func(arg string) bool {
for i := range flags {
if flags[i] == arg {
return true
}
}
return false
}
if len(args) == 0 {
params, remaining, err = ParamList{}, args, FlagNotFound
return
}
remaining = make([]string, len(args))
params = ParamList{}
err = FlagNotFound
ArgLoop:
for a, b = 0, 0; a < len(args); a++ {
if "--" == args[a] {
// stop processing flags
a++
break ArgLoop
} else if hasFlag(args[a]) {
a++
availCount := len(args) - a // make sure our attempt to grab parameters does not exceeed arg array bounds.
// can we eat all the params this flag needs?
if availCount < paramCount {
params, remaining, err = ParamList{}, args, FlagHasTooFewParams
return
}
params = make(ParamList, paramCount)
for c := 0; c < availCount; c++ {
// only eat params, don't eat potential flags
if !strings.HasPrefix(args[a], "-") {
params[c] = args[a]
a++
} else {
params, remaining, err = ParamList{}, args, FlagHasTooFewParams
return
}
}
err = FlagFound
break ArgLoop
} else {
// copy unused arguments
remaining[b] = args[a]
b++
}
}
// copy remaining arguments
for ; a < len(args); a++ {
remaining[b] = args[a]
b++
}
return
}
func envOr(name string, def string) string {
if val := os.Getenv(name); val != "" {
return val
}
return def
}
func parseFlags(args []string) (options map[string]string, remaining []string) {
var (
flagErr FlagError
params ParamList
)
remaining = args
// VERSION. eat flag. exit if found.
if _, remaining, flagErr = eatFlag(remaining, []string{"-V", "--version"}, 0); flagErr == FlagFound {
version()
os.Exit(int(OK))
}
// HELP. eat flag. exit if found.
if _, remaining, flagErr = eatFlag(remaining, []string{"-h", "--help"}, 0); flagErr == FlagFound {
usage()
os.Exit(int(OK))
}
// we now have potential flags to return
options = make(map[string]string)
// INIT LOG. eat flag, 1 param. exit if error.
if params, remaining, flagErr = eatFlag(remaining, []string{"--init-log"}, 1); flagErr == FlagHasTooFewParams {
log.Println("Error: flag --init-log is missing an argument.")
usage()
os.Exit(int(BadFlag))
} else {
options["init-log"] = params.getOr(0, "")
}
return
}
func runCommand(cmd *exec.Cmd) AppError {
sigs := make(chan os.Signal, 1)
done := make(chan error, 1)
// listen for signals from docker daemon
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
// run the app from goroutine, so we can monitor signals and app
// termination
go func() {
stdout, err := cmd.StdoutPipe()
if err != nil {
log.Println("Cannot open pipe to app's stdout: ", err)
}
stderr, err := cmd.StderrPipe()
if err != nil {
log.Println("Cannot open pipe to app's stderr: ", err)
}
err = cmd.Start()
if err != nil {
log.Fatal(err)
done <- err
return
}
log.Println("App started.")
// redirect apps's stdout/stderr to our stdout/stderr, respectively
go io.Copy(os.Stdout, stdout)
go io.Copy(os.Stderr, stderr)
err = cmd.Wait()
done <- err
}()
// monitor termination of app or signals from docker
select {
case err := <-done:
if err == nil {
log.Println("App stopped.")
return OK
} else {
log.Printf("App stopped with error (%v)", err)
return AppStoppedWithError
}
case sig := <-sigs:
log.Printf("Received signal (%v).", sig)
sigSuccess, err := stopProcess(cmd.Process, sig, syscall.SIGTERM, syscall.SIGHUP)
if err != OK {
log.Println(err)
return err
}
log.Printf("App stopped with signal (%v).\n", sigSuccess)
// did app stop with the expected signal?
switch sigSuccess {
case sig:
return OK
case syscall.SIGINT:
return OK
default:
return InsufficientSignalError
}
}
return OK
}
/** stopProcess
*
* given a process and an ordered list of signals, send the first signal and
* delay. if the process did not stop, then repeat with subsequent signals
* until the app responds, or we run out of signals.
*/
func stopProcess(p *os.Process, sigs ...os.Signal) (os.Signal, AppError) {
if len(sigs) == 0 {
if err := p.Kill(); err != nil {
log.Fatal("Failed to kill app: ", err)
}
return nil, FailedToKillApp
}
c := make(chan error, 1)
go func() {
log.Printf("Attempting to stop app with signal (%v).", sigs[0])
c <- p.Signal(sigs[0])
}()
select {
case err := <-c:
if err == nil {
return sigs[0], OK
} else {
return stopProcess(p, sigs[1:]...)
}
case _ = <-time.After(SIG_TIMEOUT):
return stopProcess(p, sigs[1:]...)
}
}
func usage() {
prog := path.Base(os.Args[0])
fmt.Printf("Usage: %s [-h] [--init-log FILE] [--] COMMAND\n", prog)
fmt.Println()
fmt.Println("Commands:")
fmt.Println()
fmt.Println(" COMMAND - app and args to execute. app requires full path.")
fmt.Println(" -- - args after this flag are reserved for COMMAND.")
fmt.Println(" -h, --help - print this help message.")
fmt.Printf(" --init-log FILE - write %s output to FILE.\n", prog)
fmt.Println(" -V, --version - print version info.")
fmt.Println()
}
func version() {
fmt.Printf("%s: version %s, build %s\n", os.Args[0], VERSION, BUILD_DATE)
fmt.Println()
}
func (err AppError) Error() string {
switch err {
case MissingArgument:
return "missing argument"
case InsufficientSignalError:
return "SIGINT insufficient to stop app"
default:
return "unknown error"
}
}
func (err FlagError) Error() string {
switch err {
case FlagFound:
return "flag found"
case FlagNotFound:
return "flag not found"
case FlagHasTooFewParams:
return "flag is missing required parameters"
default:
return "unknown error"
}
}
func (p *ParamList) getOr(index int, def string) string {
if index < 0 || index >= len(*p) {
return def
}
return (*p)[index]
}