forked from elastic/beats
-
Notifications
You must be signed in to change notification settings - Fork 0
/
docker.go
55 lines (45 loc) · 1.24 KB
/
docker.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
package docker
import (
"context"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/client"
)
// Client for Docker
type Client struct {
cli *client.Client
}
// NewClient builds and returns a docker Client
func NewClient() (Client, error) {
c, err := client.NewEnvClient()
return Client{cli: c}, err
}
// ContainerStart pulls and starts the given container
func (c Client) ContainerStart(image string, cmd ...string) (string, error) {
ctx := context.Background()
if _, err := c.cli.ImagePull(ctx, image, types.ImagePullOptions{}); err != nil {
return "", err
}
resp, err := c.cli.ContainerCreate(ctx, &container.Config{
Image: image,
Cmd: cmd,
}, nil, nil, "")
if err != nil {
return "", err
}
if err := c.cli.ContainerStart(ctx, resp.ID, types.ContainerStartOptions{}); err != nil {
return "", err
}
return resp.ID, nil
}
// ContainerWait waits for a container to finish
func (c Client) ContainerWait(ID string) error {
ctx := context.Background()
_, err := c.cli.ContainerWait(ctx, ID)
return err
}
// ContainerKill kills the given container
func (c Client) ContainerKill(ID string) error {
ctx := context.Background()
return c.cli.ContainerKill(ctx, ID, "KILL")
}