/
docker.go
196 lines (161 loc) · 4.51 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
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
package docker
import (
"bytes"
"errors"
"fmt"
"io"
"io/ioutil"
"os"
"os/exec"
"strings"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/api/types/filters"
"github.com/docker/docker/api/types/network"
"github.com/docker/docker/client"
log "github.com/sirupsen/logrus"
"golang.org/x/net/context"
)
// Docker stands as a docker service client.
type Docker struct {
ctx context.Context
*client.Client
}
// NewDockerClient returns a new Docker service client.
func NewDockerClient() *Docker {
SetAPIVersion()
cli, err := client.NewClientWithOpts(client.FromEnv)
if err != nil {
panic(err)
}
return &Docker{context.Background(), cli}
}
// PullImage pulls image from docker registry
func (d *Docker) PullImage(image string) error {
out, err := d.ImagePull(d.ctx, image, types.ImagePullOptions{})
if err != nil {
return err
}
_, err = io.Copy(ioutil.Discard, out)
return err
}
// Exec executes commands inside a running container
func (d *Docker) Exec(containerName string, execConfig types.ExecConfig) error {
resp, err := d.ContainerExecCreate(d.ctx, containerName, execConfig)
if err != nil {
return err
}
_ = d.ContainerExecStart(d.ctx, resp.ID,
types.ExecStartCheck{Detach: true, Tty: false})
ins, err := d.ContainerExecInspect(d.ctx, resp.ID)
for ins.Running || err != nil {
ins, err = d.ContainerExecInspect(d.ctx, resp.ID)
}
return err
}
// Create creates a new docker container
func (d *Docker) Create(containerConfig *container.Config, hostConfig *container.HostConfig,
networkConfig *network.NetworkingConfig, name string) (string, error) {
if !d.ImageExists(containerConfig.Image) {
log.Printf("Pulling %v image", containerConfig.Image)
err := d.PullImage(containerConfig.Image)
if err != nil {
return "", err
}
}
resp, err := d.ContainerCreate(d.ctx, containerConfig, hostConfig,
networkConfig, nil, name)
return resp.ID, err
}
// Start starts a previously created container.
func (d *Docker) Start(id, name string) error {
if id == "" {
container, err := d.Search(name)
if err != nil {
return err
}
id = container.ID
}
return d.ContainerStart(d.ctx, id, types.ContainerStartOptions{})
}
// Stop stops a previously started container.
func (d *Docker) Stop(id, name string) error {
if id == "" {
container, err := d.Search(name)
if err != nil {
return err
}
id = container.ID
}
return d.ContainerStop(d.ctx, id, nil)
}
// Search searches a container from the running docker containers
func (d *Docker) Search(name string) (types.Container, error) {
containers, err := d.ContainerList(d.ctx, types.ContainerListOptions{})
if err != nil {
return types.Container{}, err
}
err = errors.New("NotFound")
for _, container := range containers {
if container.Names[0] == fmt.Sprintf("/%v", name) {
return container, nil
}
}
return types.Container{}, err
}
// ImageExists verifies that an image exists in the local docker registry
func (d *Docker) ImageExists(name string) bool {
fltr := filters.NewArgs()
fltr.Add("reference", "govm/govm")
images, err := d.ImageList(d.ctx,
types.ImageListOptions{
All: false,
Filters: fltr,
},
)
if err != nil || len(images) == 0 {
return false
}
return true
}
// Inspect inspects and return details about an specific container.
func (d *Docker) Inspect(id string) (types.ContainerJSON, error) {
return d.ContainerInspect(d.ctx, id)
}
// List lists all docker-based VM instances that mee the passed filters
func (d *Docker) List(args filters.Args) ([]types.Container, error) {
return d.ContainerList(context.Background(),
types.ContainerListOptions{
Quiet: false,
Size: false,
All: true,
Latest: false,
Since: "",
Before: "",
Limit: 0,
Filters: args,
})
}
// Remove wraps the ContainerRemove functionality.
func (d *Docker) Remove(id string) error {
return d.ContainerRemove(context.Background(), id,
types.ContainerRemoveOptions{
RemoveVolumes: false,
RemoveLinks: false,
Force: true,
})
}
// SetAPIVersion gets local docker server API version.
// nolint: godox
// TODO: Investigate how we can replace the exec.Command approach
func SetAPIVersion() {
cmd := exec.Command("docker", "version", "--format", "{{.Server.APIVersion}}")
cmdOutput := &bytes.Buffer{}
cmd.Stdout = cmdOutput
err := cmd.Run()
if err != nil {
log.Fatalf("Error getting Docker Server API version: %v", err)
}
apiVersion := strings.TrimSpace(cmdOutput.String())
_ = os.Setenv("DOCKER_API_VERSION", apiVersion)
}