forked from PolarGeospatialCenter/dockertest
/
docker.go
99 lines (81 loc) · 2.17 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
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
package docker
import (
"context"
"fmt"
"io/ioutil"
"time"
dockertypes "github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/api/types/network"
docker "github.com/docker/docker/client"
"github.com/docker/go-connections/nat"
)
type Container struct {
Image string
Cmd []string
containerID string
}
func (t *Container) Run(ctx context.Context) error {
cli, err := docker.NewEnvClient()
if err != nil {
return err
}
containerConfig := &container.Config{
Image: t.Image,
Cmd: t.Cmd,
}
hostConfig := &container.HostConfig{
PublishAllPorts: true,
}
networkConfig := &network.NetworkingConfig{}
status, err := cli.ImagePull(ctx, containerConfig.Image, dockertypes.ImagePullOptions{})
if err != nil {
return fmt.Errorf("unable to pull image: %v", err)
}
_, err = ioutil.ReadAll(status)
if err != nil {
return fmt.Errorf("unable to read status from image pull: %v", err)
}
status.Close()
c, err := cli.ContainerCreate(ctx, containerConfig, hostConfig, networkConfig, nil, "")
if err != nil {
return fmt.Errorf("unable to create container: %v", err)
}
t.containerID = c.ID
err = cli.ContainerStart(ctx, c.ID, dockertypes.ContainerStartOptions{})
if err != nil {
return err
}
return nil
}
func (t *Container) GetPort(ctx context.Context, port string) (string, error) {
cli, err := docker.NewEnvClient()
if err != nil {
return "", err
}
data, err := cli.ContainerInspect(ctx, t.containerID)
if err != nil {
return "", err
}
fmt.Println(data.NetworkSettings)
ports := data.NetworkSettings.Ports
fmt.Println(ports)
hostPort := ports[nat.Port(port)][0].HostPort
return hostPort, nil
}
func (t *Container) Stop(ctx context.Context) error {
cli, err := docker.NewEnvClient()
if err != nil {
return err
}
timeout := 5 * time.Second
err = cli.ContainerStop(ctx, t.containerID, &timeout)
if err != nil {
return fmt.Errorf("error killing container %s: %v", t.containerID, err)
}
err = cli.ContainerRemove(ctx, t.containerID, dockertypes.ContainerRemoveOptions{})
if err != nil {
return fmt.Errorf("error removing container %s: %v", t.containerID, err)
}
return nil
}