forked from johnjohnsp1/capsule8
/
container.go
102 lines (86 loc) · 2.55 KB
/
container.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
// Copyright 2017 Capsule8, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package functional
import (
"os/exec"
"strings"
"testing"
"golang.org/x/net/context"
)
type Container struct {
t *testing.T
Path string
ImageID string
command *exec.Cmd
}
func (c *Container) dockerBuildArgs(quiet bool, buildargs []string) []string {
args := []string{"build"}
if quiet {
args = append(args, "-q")
}
args = append(args, buildargs...)
args = append(args, c.Path)
return args
}
func (c *Container) Build(buildargs ...string) error {
dockerArgs := c.dockerBuildArgs(false, buildargs)
docker := exec.Command("docker", dockerArgs...)
err := docker.Run()
if err != nil {
return err
}
dockerArgs = c.dockerBuildArgs(true, buildargs)
docker = exec.Command("docker", dockerArgs...)
dockerOutput, err := docker.Output()
if err != nil {
return err
}
trimmed := strings.TrimSpace(string(dockerOutput))
c.ImageID = strings.TrimPrefix(trimmed, "sha256:")
return nil
}
func (c *Container) dockerRunArgs(runargs []string) []string {
args := append([]string{"run", "--rm"}, runargs...)
args = append(args, c.ImageID)
return args
}
func (c *Container) Start(runargs ...string) error {
dockerArgs := c.dockerRunArgs(runargs)
c.command = exec.Command("docker", dockerArgs...)
return c.command.Start()
}
func (c *Container) StartContext(ctx context.Context, runargs ...string) error {
dockerArgs := c.dockerRunArgs(runargs)
c.command = exec.CommandContext(ctx, "docker", dockerArgs...)
return c.command.Start()
}
func (c *Container) Wait() error {
return c.command.Wait()
}
func (c *Container) Run(runargs ...string) error {
dockerArgs := c.dockerRunArgs(runargs)
c.command = exec.Command("docker", dockerArgs...)
return c.command.Run()
}
func (c *Container) RunContext(ctx context.Context, runargs ...string) error {
dockerArgs := c.dockerRunArgs(runargs)
c.command = exec.CommandContext(ctx, "docker", dockerArgs...)
return c.command.Run()
}
func NewContainer(t *testing.T, path string) *Container {
return &Container{
t: t,
Path: path,
}
}