forked from testcontainers/testcontainers-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lifecycle.go
379 lines (326 loc) · 11.7 KB
/
lifecycle.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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
package testcontainers
import (
"context"
"io"
"strings"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/api/types/network"
"github.com/docker/go-connections/nat"
"golang.org/x/exp/slices"
)
// ContainerRequestHook is a hook that will be called before a container is created.
// It can be used to modify container configuration before it is created,
// using the different lifecycle hooks that are available:
// - Creating
// For that, it will receive a ContainerRequest, modify it and return an error if needed.
type ContainerRequestHook func(ctx context.Context, req ContainerRequest) error
// ContainerHook is a hook that will be called after a container is created
// It can be used to modify the state of the container after it is created,
// using the different lifecycle hooks that are available:
// - Created
// - Starting
// - Started
// - Stopping
// - Stopped
// - Terminating
// - Terminated
// For that, it will receive a Container, modify it and return an error if needed.
type ContainerHook func(ctx context.Context, container Container) error
// ContainerLifecycleHooks is a struct that contains all the hooks that can be used
// to modify the container lifecycle. All the container lifecycle hooks except the PreCreates hooks
// will be passed to the container once it's created
type ContainerLifecycleHooks struct {
PreCreates []ContainerRequestHook
PostCreates []ContainerHook
PreStarts []ContainerHook
PostStarts []ContainerHook
PreStops []ContainerHook
PostStops []ContainerHook
PreTerminates []ContainerHook
PostTerminates []ContainerHook
}
var DefaultLoggingHook = func(logger Logging) ContainerLifecycleHooks {
shortContainerID := func(c Container) string {
return c.GetContainerID()[:12]
}
return ContainerLifecycleHooks{
PreCreates: []ContainerRequestHook{
func(ctx context.Context, req ContainerRequest) error {
logger.Printf("🐳 Creating container for image %s", req.Image)
return nil
},
},
PostCreates: []ContainerHook{
func(ctx context.Context, c Container) error {
logger.Printf("✅ Container created: %s", shortContainerID(c))
return nil
},
},
PreStarts: []ContainerHook{
func(ctx context.Context, c Container) error {
logger.Printf("🐳 Starting container: %s", shortContainerID(c))
return nil
},
},
PostStarts: []ContainerHook{
func(ctx context.Context, c Container) error {
logger.Printf("✅ Container started: %s", shortContainerID(c))
return nil
},
},
PreStops: []ContainerHook{
func(ctx context.Context, c Container) error {
logger.Printf("🐳 Stopping container: %s", shortContainerID(c))
return nil
},
},
PostStops: []ContainerHook{
func(ctx context.Context, c Container) error {
logger.Printf("✋ Container stopped: %s", shortContainerID(c))
return nil
},
},
PreTerminates: []ContainerHook{
func(ctx context.Context, c Container) error {
logger.Printf("🐳 Terminating container: %s", shortContainerID(c))
return nil
},
},
PostTerminates: []ContainerHook{
func(ctx context.Context, c Container) error {
logger.Printf("🚫 Container terminated: %s", shortContainerID(c))
return nil
},
},
}
}
// creatingHook is a hook that will be called before a container is created.
func (req ContainerRequest) creatingHook(ctx context.Context) error {
for _, lifecycleHooks := range req.LifecycleHooks {
err := lifecycleHooks.Creating(ctx)(req)
if err != nil {
return err
}
}
return nil
}
// createdHook is a hook that will be called after a container is created
func (c *DockerContainer) createdHook(ctx context.Context) error {
for _, lifecycleHooks := range c.lifecycleHooks {
err := containerHookFn(ctx, lifecycleHooks.PostCreates)(c)
if err != nil {
return err
}
}
return nil
}
// startingHook is a hook that will be called before a container is started
func (c *DockerContainer) startingHook(ctx context.Context) error {
for _, lifecycleHooks := range c.lifecycleHooks {
err := containerHookFn(ctx, lifecycleHooks.PreStarts)(c)
if err != nil {
c.printLogs(ctx, err)
return err
}
}
return nil
}
// startedHook is a hook that will be called after a container is started
func (c *DockerContainer) startedHook(ctx context.Context) error {
for _, lifecycleHooks := range c.lifecycleHooks {
err := containerHookFn(ctx, lifecycleHooks.PostStarts)(c)
if err != nil {
c.printLogs(ctx, err)
return err
}
}
return nil
}
// printLogs is a helper function that will print the logs of a Docker container
// We are going to use this helper function to inform the user of the logs when an error occurs
func (c *DockerContainer) printLogs(ctx context.Context, cause error) {
reader, err := c.Logs(ctx)
if err != nil {
c.logger.Printf("failed accessing container logs: %v\n", err)
return
}
b, err := io.ReadAll(reader)
if err != nil {
c.logger.Printf("failed reading container logs: %v\n", err)
return
}
c.logger.Printf("container logs (%s):\n%s", cause, b)
}
// stoppingHook is a hook that will be called before a container is stopped
func (c *DockerContainer) stoppingHook(ctx context.Context) error {
for _, lifecycleHooks := range c.lifecycleHooks {
err := containerHookFn(ctx, lifecycleHooks.PreStops)(c)
if err != nil {
return err
}
}
return nil
}
// stoppedHook is a hook that will be called after a container is stopped
func (c *DockerContainer) stoppedHook(ctx context.Context) error {
for _, lifecycleHooks := range c.lifecycleHooks {
err := containerHookFn(ctx, lifecycleHooks.PostStops)(c)
if err != nil {
return err
}
}
return nil
}
// terminatingHook is a hook that will be called before a container is terminated
func (c *DockerContainer) terminatingHook(ctx context.Context) error {
for _, lifecycleHooks := range c.lifecycleHooks {
err := containerHookFn(ctx, lifecycleHooks.PreTerminates)(c)
if err != nil {
return err
}
}
return nil
}
// terminatedHook is a hook that will be called after a container is terminated
func (c *DockerContainer) terminatedHook(ctx context.Context) error {
for _, lifecycleHooks := range c.lifecycleHooks {
err := containerHookFn(ctx, lifecycleHooks.PostTerminates)(c)
if err != nil {
return err
}
}
return nil
}
// Creating is a hook that will be called before a container is created.
func (c ContainerLifecycleHooks) Creating(ctx context.Context) func(req ContainerRequest) error {
return func(req ContainerRequest) error {
for _, hook := range c.PreCreates {
if err := hook(ctx, req); err != nil {
return err
}
}
return nil
}
}
// containerHookFn is a helper function that will create a function to be returned by all the different
// container lifecycle hooks. The created function will iterate over all the hooks and call them one by one.
func containerHookFn(ctx context.Context, containerHook []ContainerHook) func(container Container) error {
return func(container Container) error {
for _, hook := range containerHook {
if err := hook(ctx, container); err != nil {
return err
}
}
return nil
}
}
// Created is a hook that will be called after a container is created
func (c ContainerLifecycleHooks) Created(ctx context.Context) func(container Container) error {
return containerHookFn(ctx, c.PostCreates)
}
// Starting is a hook that will be called before a container is started
func (c ContainerLifecycleHooks) Starting(ctx context.Context) func(container Container) error {
return containerHookFn(ctx, c.PreStarts)
}
// Started is a hook that will be called after a container is started
func (c ContainerLifecycleHooks) Started(ctx context.Context) func(container Container) error {
return containerHookFn(ctx, c.PostStarts)
}
// Stopping is a hook that will be called before a container is stopped
func (c ContainerLifecycleHooks) Stopping(ctx context.Context) func(container Container) error {
return containerHookFn(ctx, c.PreStops)
}
// Stopped is a hook that will be called after a container is stopped
func (c ContainerLifecycleHooks) Stopped(ctx context.Context) func(container Container) error {
return containerHookFn(ctx, c.PostStops)
}
// Terminating is a hook that will be called before a container is terminated
func (c ContainerLifecycleHooks) Terminating(ctx context.Context) func(container Container) error {
return containerHookFn(ctx, c.PreTerminates)
}
// Terminated is a hook that will be called after a container is terminated
func (c ContainerLifecycleHooks) Terminated(ctx context.Context) func(container Container) error {
return containerHookFn(ctx, c.PostTerminates)
}
func (p *DockerProvider) preCreateContainerHook(ctx context.Context, req ContainerRequest, dockerInput *container.Config, hostConfig *container.HostConfig, networkingConfig *network.NetworkingConfig) error {
// prepare mounts
hostConfig.Mounts = mapToDockerMounts(req.Mounts)
endpointSettings := map[string]*network.EndpointSettings{}
// #248: Docker allows only one network to be specified during container creation
// If there is more than one network specified in the request container should be attached to them
// once it is created. We will take a first network if any specified in the request and use it to create container
if len(req.Networks) > 0 {
attachContainerTo := req.Networks[0]
nw, err := p.GetNetwork(ctx, NetworkRequest{
Name: attachContainerTo,
})
if err == nil {
aliases := []string{}
if _, ok := req.NetworkAliases[attachContainerTo]; ok {
aliases = req.NetworkAliases[attachContainerTo]
}
endpointSetting := network.EndpointSettings{
Aliases: aliases,
NetworkID: nw.ID,
}
endpointSettings[attachContainerTo] = &endpointSetting
}
}
if req.ConfigModifier != nil {
req.ConfigModifier(dockerInput)
}
if req.HostConfigModifier == nil {
req.HostConfigModifier = defaultHostConfigModifier(req)
}
req.HostConfigModifier(hostConfig)
if req.EnpointSettingsModifier != nil {
req.EnpointSettingsModifier(endpointSettings)
}
networkingConfig.EndpointsConfig = endpointSettings
exposedPorts := req.ExposedPorts
// this check must be done after the pre-creation Modifiers are called, so the network mode is already set
if len(exposedPorts) == 0 && !hostConfig.NetworkMode.IsContainer() {
image, _, err := p.client.ImageInspectWithRaw(ctx, dockerInput.Image)
if err != nil {
return err
}
for p := range image.Config.ExposedPorts {
exposedPorts = append(exposedPorts, string(p))
}
}
exposedPortSet, exposedPortMap, err := nat.ParsePortSpecs(exposedPorts)
if err != nil {
return err
}
dockerInput.ExposedPorts = exposedPortSet
// only exposing those ports automatically if the container request exposes zero ports and the container does not run in a container network
if len(exposedPorts) == 0 && !hostConfig.NetworkMode.IsContainer() {
hostConfig.PortBindings = exposedPortMap
} else {
hostConfig.PortBindings = mergePortBindings(hostConfig.PortBindings, exposedPortMap, req.ExposedPorts)
}
return nil
}
func mergePortBindings(configPortMap, exposedPortMap nat.PortMap, exposedPorts []string) nat.PortMap {
if exposedPortMap == nil {
exposedPortMap = make(map[nat.Port][]nat.PortBinding)
}
for k, v := range configPortMap {
if slices.Contains(exposedPorts, strings.Split(string(k), "/")[0]) {
exposedPortMap[k] = v
}
}
return exposedPortMap
}
// defaultHostConfigModifier provides a default modifier including the deprecated fields
func defaultHostConfigModifier(req ContainerRequest) func(hostConfig *container.HostConfig) {
return func(hostConfig *container.HostConfig) {
hostConfig.AutoRemove = req.AutoRemove
hostConfig.CapAdd = req.CapAdd
hostConfig.CapDrop = req.CapDrop
hostConfig.Binds = req.Binds
hostConfig.ExtraHosts = req.ExtraHosts
hostConfig.NetworkMode = req.NetworkMode
hostConfig.Resources = req.Resources
}
}