-
Notifications
You must be signed in to change notification settings - Fork 0
/
exec.go
69 lines (65 loc) · 2.03 KB
/
exec.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
package integration
import (
"context"
"errors"
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
)
// RunBinary runs a target binary with a set of arguments provided by the user
func RunBinary(binPath string, args ...string) (func(), error) {
abs, err := filepath.Abs(binPath)
if err != nil {
return nil, err
}
ctx, cancel := context.WithCancel(context.Background())
cmd := exec.CommandContext(ctx, abs, args...)
cmd.Stderr = os.Stderr
cmd.Stdout = os.Stdout
if err := cmd.Start(); err != nil {
return nil, err
}
return cancel, nil
}
// BuildSource builds a target Go package and gives the resulting binary
// some user-defined name
func BuildSource(packagePath, output string) (func() error, error) {
cmdBuild := exec.Command("go", "build", "-o", output, packagePath)
if out, err := cmdBuild.CombinedOutput(); err != nil {
return nil, errors.New(fmt.Sprintf("unable to build package: %v (%s)",
err, string(out),
))
}
return func() error {
return os.Remove(output)
}, nil
}
// RunContainer launches a detached docker container on the host machine. It
// takes an image name, a list of "docker run" arguments, and a list of
// arguments that get passed to the container runtime
func RunContainer(image string, dockerArgs, runtimeArgs []string) (func() error, error) {
// build a list of args to pass to cmd.Exec
execDocker := append([]string{"docker", "run", "-d"}, dockerArgs...)
execRuntime := append([]string{image}, runtimeArgs...)
execDocker = append(execDocker, execRuntime...)
// launch the container
out, err := exec.Command(execDocker[0], execDocker[1:]...).CombinedOutput()
if err != nil {
return nil, errors.New(
fmt.Sprintf("%s: %s", err.Error(), string(out)),
)
}
// get the uuid from the container after it starts. this gets used to kill
// the container
var uuid string
if split := strings.Split(string(out), "\n"); len(split) == 0 {
return nil, errors.New("unable to get container uuid")
} else {
uuid = split[0]
}
return func() error {
return exec.Command("docker", "kill", uuid).Run()
}, nil
}