-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontainer.go
303 lines (239 loc) · 8.77 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
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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
package dockertest
import (
"errors"
"fmt"
"strings"
"time"
"github.com/docker/go-connections/nat"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/container"
dockerNetwork "github.com/docker/docker/api/types/network"
"github.com/mohae/deepcopy"
)
// ErrContainerStillRunning is returned from a call to ExitCode() if the container is still running.
var ErrContainerStillRunning = errors.New("container is running, it has no exit code yet")
// ErrInspectingContainer is returned from a call to ExitCode() if the docker client returned an error on inspect.
var ErrInspectingContainer = errors.New("error inspecting container")
// Container is a access wrapper for a docker container.
type Container struct {
Name string
startOptions types.ContainerStartOptions
containerID string
clientEnabled
}
// Start starts the container.
func (c Container) Start() error {
return c.dockerClient.ContainerStart(c.ctx, c.containerID, c.startOptions)
}
// ExitCode returns the exit code of the container.
// The container must be exited and exist, otherwise an error is returned.
func (c Container) ExitCode() (int, error) {
inspectResult, inspectError := c.dockerClient.ContainerInspect(c.ctx, c.containerID)
if inspectError != nil {
return -1, fmt.Errorf("%w: %w", ErrInspectingContainer, inspectError)
}
if inspectResult.State.Running {
return -1, ErrContainerStillRunning
}
return inspectResult.State.ExitCode, nil
}
// ContainerBuilder helps to create customized containers.
// Note that calling functions have not affect to running or already created container.
// only when calling the "Build" method all configuration is applied to a new container.
type ContainerBuilder struct {
ContainerConfig *container.Config
HostConfig *container.HostConfig
NetworkingConfig *dockerNetwork.NetworkingConfig
ContainerName string
originalName string
sessionID string
clientEnabled
}
// NewContainerBuilder returns a new *ContainerBuilder.
func (b *ContainerBuilder) NewContainerBuilder() *ContainerBuilder {
newBuilder := deepcopy.Copy(b).(*ContainerBuilder)
newBuilder.ctx = b.ctx
newBuilder.dockerClient = b.dockerClient
newBuilder.sessionID = b.sessionID
newBuilder.originalName = b.originalName
return newBuilder
}
// Build creates a container from the current builders state.
func (b *ContainerBuilder) Build() (*Container, error) {
containerBody, err := b.dockerClient.ContainerCreate(
b.ctx,
b.ContainerConfig,
b.HostConfig,
b.NetworkingConfig,
nil,
b.ContainerName,
)
if err != nil {
return nil, err
}
return &Container{
Name: b.ContainerName,
containerID: containerBody.ID,
clientEnabled: b.clientEnabled,
}, nil
}
// Connect connects the container to the given Network.
func (b *ContainerBuilder) Connect(n *Network) *ContainerBuilder {
b.HostConfig.NetworkMode = container.NetworkMode(n.NetworkName)
b.ensureNetworkConfig(n)
b.NetworkingConfig.EndpointsConfig[n.NetworkName].NetworkID = n.NetworkID
return b
}
// Mount creates a volume binding to mount a local directory into the container.
func (b *ContainerBuilder) Mount(localPath string, containerPath string) *ContainerBuilder {
b.HostConfig.Binds = append(b.HostConfig.Binds, fmt.Sprintf("%s:%s", localPath, containerPath))
return b
}
// Cmd sets the command that is executed when the container starts.
func (b *ContainerBuilder) Cmd(cmd string) *ContainerBuilder {
b.ContainerConfig.Cmd = strings.Split(cmd, " ")
return b
}
// CmdArgs sets the command that is executed when the container starts.
func (b *ContainerBuilder) CmdArgs(args ...string) *ContainerBuilder {
b.ContainerConfig.Cmd = args
return b
}
// Name defines the container name.
func (b *ContainerBuilder) Name(s string) *ContainerBuilder {
b.originalName = s
b.ContainerName = s
if b.sessionID != "" {
b.ContainerName = fmt.Sprintf("%s-%s", s, b.sessionID)
}
return b
}
// AutoRemove tells the docker daemon to remove the container after it exits.
func (b *ContainerBuilder) AutoRemove(v bool) *ContainerBuilder {
b.HostConfig.AutoRemove = v
return b
}
// Image sets the docker image to start a container from.
func (b *ContainerBuilder) Image(image string) *ContainerBuilder {
b.ContainerConfig.Image = image
return b
}
// HealthDisable disabled the health check.
func (b *ContainerBuilder) HealthDisable() *ContainerBuilder {
b.ensureHealth()
b.ContainerConfig.Healthcheck.Test = []string{"NONE"}
return b
}
// HealthCmd sets a command that is executed directly.
func (b *ContainerBuilder) HealthCmd(cmd string) *ContainerBuilder {
b.ensureHealth()
b.ContainerConfig.Healthcheck.Test = []string{"CMD", cmd}
return b
}
// HealthShellCmd sets a command that is executed in the containers default shell
// to determine if the container is healthy.
func (b *ContainerBuilder) HealthShellCmd(cmd string) *ContainerBuilder {
b.ensureHealth()
b.ContainerConfig.Healthcheck.Test = []string{"CMD-SHELL", cmd}
return b
}
// HealthTimeout sets the timeout to wait before considering the check to have hung.
func (b *ContainerBuilder) HealthTimeout(t time.Duration) *ContainerBuilder {
b.ensureHealth()
b.ContainerConfig.Healthcheck.Timeout = t
return b
}
// HealthInterval sets the time to wait between checks.
func (b *ContainerBuilder) HealthInterval(d time.Duration) *ContainerBuilder {
b.ensureHealth()
b.ContainerConfig.Healthcheck.Interval = d
return b
}
// HealthRetries sets the number of consecutive failures needed to consider a container as unhealthy.
func (b *ContainerBuilder) HealthRetries(r int) *ContainerBuilder {
b.ensureHealth()
b.ContainerConfig.Healthcheck.Retries = r
return b
}
func (b *ContainerBuilder) ensureHealth() {
if b.ContainerConfig.Healthcheck == nil {
b.ContainerConfig.Healthcheck = &container.HealthConfig{}
}
}
// Env defines an environment variable that will be set in the container.
func (b *ContainerBuilder) Env(name string, value string) *ContainerBuilder {
b.ContainerConfig.Env = append(b.ContainerConfig.Env, fmt.Sprintf("%s=%s", name, value))
return b
}
// WorkingDir defines the working directory for the container.
func (b *ContainerBuilder) WorkingDir(wd string) *ContainerBuilder {
b.ContainerConfig.WorkingDir = wd
return b
}
// Dns adds a dns server to the container.
// nolint: golint, revive, stylecheck
func (b *ContainerBuilder) Dns(dnsServerIP string) *ContainerBuilder {
b.HostConfig.DNS = append(b.HostConfig.DNS, dnsServerIP)
return b
}
// UseOriginalName removes the unique session-identifier from the container name.
func (b *ContainerBuilder) UseOriginalName() *ContainerBuilder {
b.ContainerName = b.originalName
return b
}
// Link links a foreign container.
func (b *ContainerBuilder) Link(container *Container, alias string, n *Network) *ContainerBuilder {
b.ensureNetworkConfig(n)
b.NetworkingConfig.EndpointsConfig[n.NetworkName].Links = append(
b.NetworkingConfig.EndpointsConfig[n.NetworkName].Links,
fmt.Sprintf("%s:%s", container.Name, alias),
)
return b
}
// Port bind a Host port to a container port.
// Deprecated: use BindPort instead.
func (b *ContainerBuilder) Port(containerPort, hostPort string) *ContainerBuilder {
return b.BindPort(containerPort, hostPort)
}
// BindPort bind a Host port to a container port.
func (b *ContainerBuilder) BindPort(containerPort, hostPort string) *ContainerBuilder {
b.HostConfig.PortBindings = nat.PortMap{
nat.Port(containerPort): []nat.PortBinding{
{HostIP: "0.0.0.0", HostPort: hostPort},
},
}
return b
}
// ExposePort exposes a containers port inside the docker network - for example "80/tcp".
func (b *ContainerBuilder) ExposePort(port string) *ContainerBuilder {
if b.ContainerConfig.ExposedPorts == nil {
b.ContainerConfig.ExposedPorts = map[nat.Port]struct{}{}
}
b.ContainerConfig.ExposedPorts[nat.Port(port)] = struct{}{}
return b
}
func (b *ContainerBuilder) ensureNetworkConfig(n *Network) {
if b.NetworkingConfig.EndpointsConfig == nil {
b.NetworkingConfig.EndpointsConfig = map[string]*dockerNetwork.EndpointSettings{}
}
if b.NetworkingConfig.EndpointsConfig[n.NetworkName] == nil {
b.NetworkingConfig.EndpointsConfig[n.NetworkName] = &dockerNetwork.EndpointSettings{}
}
}
// IPAddress defines the IP address used by the container.
func (b *ContainerBuilder) IPAddress(ipAddress string, n *Network) *ContainerBuilder {
if b.NetworkingConfig.EndpointsConfig == nil {
b.NetworkingConfig.EndpointsConfig = map[string]*dockerNetwork.EndpointSettings{}
}
if b.NetworkingConfig.EndpointsConfig[n.NetworkName] == nil {
endpointSetting := &dockerNetwork.EndpointSettings{
IPAMConfig: &dockerNetwork.EndpointIPAMConfig{IPv4Address: ipAddress},
}
b.NetworkingConfig.EndpointsConfig[n.NetworkName] = endpointSetting
} else {
b.NetworkingConfig.EndpointsConfig[n.NetworkName].IPAMConfig = &dockerNetwork.EndpointIPAMConfig{
IPv4Address: ipAddress,
}
}
return b
}