forked from testcontainers/testcontainers-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
options.go
237 lines (200 loc) · 8.23 KB
/
options.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
package testcontainers
import (
"context"
"fmt"
"strings"
"time"
"dario.cat/mergo"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/api/types/network"
tcexec "github.com/testcontainers/testcontainers-go/exec"
"github.com/testcontainers/testcontainers-go/internal/config"
"github.com/testcontainers/testcontainers-go/internal/testcontainersdocker"
"github.com/testcontainers/testcontainers-go/wait"
)
// ContainerCustomizer is an interface that can be used to configure the Testcontainers container
// request. The passed request will be merged with the default one.
type ContainerCustomizer interface {
Customize(req *GenericContainerRequest)
}
// CustomizeRequestOption is a type that can be used to configure the Testcontainers container request.
// The passed request will be merged with the default one.
type CustomizeRequestOption func(req *GenericContainerRequest)
func (opt CustomizeRequestOption) Customize(req *GenericContainerRequest) {
opt(req)
}
// CustomizeRequest returns a function that can be used to merge the passed container request with the one that is used by the container.
// Slices and Maps will be appended.
func CustomizeRequest(src GenericContainerRequest) CustomizeRequestOption {
return func(req *GenericContainerRequest) {
if err := mergo.Merge(req, &src, mergo.WithOverride, mergo.WithAppendSlice); err != nil {
fmt.Printf("error merging container request, keeping the original one. Error: %v", err)
return
}
}
}
// WithConfigModifier allows to override the default container config
func WithConfigModifier(modifier func(config *container.Config)) CustomizeRequestOption {
return func(req *GenericContainerRequest) {
req.ConfigModifier = modifier
}
}
// WithEndpointSettingsModifier allows to override the default endpoint settings
func WithEndpointSettingsModifier(modifier func(settings map[string]*network.EndpointSettings)) CustomizeRequestOption {
return func(req *GenericContainerRequest) {
req.EnpointSettingsModifier = modifier
}
}
// WithHostConfigModifier allows to override the default host config
func WithHostConfigModifier(modifier func(hostConfig *container.HostConfig)) CustomizeRequestOption {
return func(req *GenericContainerRequest) {
req.HostConfigModifier = modifier
}
}
// WithImage sets the image for a container
func WithImage(image string) CustomizeRequestOption {
return func(req *GenericContainerRequest) {
req.Image = image
}
}
// imageSubstitutor {
// ImageSubstitutor represents a way to substitute container image names
type ImageSubstitutor interface {
// Description returns the name of the type and a short description of how it modifies the image.
// Useful to be printed in logs
Description() string
Substitute(image string) (string, error)
}
// }
// prependHubRegistry represents a way to prepend a custom Hub registry to the image name,
// using the HubImageNamePrefix configuration value
type prependHubRegistry struct {
prefix string
}
// newPrependHubRegistry creates a new prependHubRegistry
func newPrependHubRegistry() prependHubRegistry {
hubPrefix := config.Read().HubImageNamePrefix
return prependHubRegistry{
prefix: hubPrefix,
}
}
// Description returns the name of the type and a short description of how it modifies the image.
func (p prependHubRegistry) Description() string {
return fmt.Sprintf("HubImageSubstitutor (prepends %s)", p.prefix)
}
// Substitute prepends the Hub prefix to the image name, with certain conditions:
// - if the prefix is empty, the image is returned as is.
// - if the image is a non-hub image (e.g. where another registry is set), the image is returned as is.
// - if the image is a Docker Hub image where the hub registry is explicitly part of the name
// (i.e. anything with a docker.io or registry.hub.docker.com host part), the image is returned as is.
func (p prependHubRegistry) Substitute(image string) (string, error) {
registry := testcontainersdocker.ExtractRegistry(image, "")
// add the exclusions in the right order
exclusions := []func() bool{
func() bool { return p.prefix == "" }, // no prefix set at the configuration level
func() bool { return registry != "" }, // non-hub image
func() bool { return registry == "docker.io" }, // explicitly including docker.io
func() bool { return registry == "registry.hub.docker.com" }, // explicitly including registry.hub.docker.com
}
for _, exclusion := range exclusions {
if exclusion() {
return image, nil
}
}
return fmt.Sprintf("%s/%s", p.prefix, image), nil
}
// WithImageSubstitutors sets the image substitutors for a container
func WithImageSubstitutors(fn ...ImageSubstitutor) CustomizeRequestOption {
return func(req *GenericContainerRequest) {
req.ImageSubstitutors = fn
}
}
// WithNetwork creates a network with the given name and attaches the container to it, setting the network alias
// on that network to the given alias.
// If the network already exists, checking if the network name already exists, it will be reused.
func WithNetwork(networkName string, alias string) CustomizeRequestOption {
return func(req *GenericContainerRequest) {
_, err := GenericNetwork(context.Background(), GenericNetworkRequest{
NetworkRequest: NetworkRequest{
Name: networkName,
CheckDuplicate: true, // force the Docker provider to reuse an existing network
},
})
if err != nil && !strings.Contains(err.Error(), "already exists") {
logger := req.Logger
if logger == nil {
logger = Logger
}
logger.Printf("Failed to create network '%s'. Container won't be attached to this network: %v", networkName, err)
return
}
// attaching to the network because it was created with success or it already existed.
req.Networks = append(req.Networks, networkName)
if req.NetworkAliases == nil {
req.NetworkAliases = make(map[string][]string)
}
req.NetworkAliases[networkName] = []string{alias}
}
}
// Executable represents an executable command to be sent to a container, including options,
// as part of the different lifecycle hooks.
type Executable interface {
AsCommand() []string
// Options can container two different types of options:
// - Docker's ExecConfigs (WithUser, WithWorkingDir, WithEnv, etc.)
// - testcontainers' ProcessOptions (i.e. Multiplexed response)
Options() []tcexec.ProcessOption
}
// ExecOptions is a struct that provides a default implementation for the Options method
// of the Executable interface.
type ExecOptions struct {
opts []tcexec.ProcessOption
}
func (ce ExecOptions) Options() []tcexec.ProcessOption {
return ce.opts
}
// RawCommand is a type that implements Executable and represents a command to be sent to a container
type RawCommand struct {
ExecOptions
cmds []string
}
func NewRawCommand(cmds []string) RawCommand {
return RawCommand{
cmds: cmds,
ExecOptions: ExecOptions{
opts: []tcexec.ProcessOption{},
},
}
}
// AsCommand returns the command as a slice of strings
func (r RawCommand) AsCommand() []string {
return r.cmds
}
// WithStartupCommand will execute the command representation of each Executable into the container.
// It will leverage the container lifecycle hooks to call the command right after the container
// is started.
func WithStartupCommand(execs ...Executable) CustomizeRequestOption {
return func(req *GenericContainerRequest) {
startupCommandsHook := ContainerLifecycleHooks{
PostStarts: []ContainerHook{},
}
for _, exec := range execs {
execFn := func(ctx context.Context, c Container) error {
_, _, err := c.Exec(ctx, exec.AsCommand(), exec.Options()...)
return err
}
startupCommandsHook.PostStarts = append(startupCommandsHook.PostStarts, execFn)
}
req.LifecycleHooks = append(req.LifecycleHooks, startupCommandsHook)
}
}
// WithWaitStrategy sets the wait strategy for a container, using 60 seconds as deadline
func WithWaitStrategy(strategies ...wait.Strategy) CustomizeRequestOption {
return WithWaitStrategyAndDeadline(60*time.Second, strategies...)
}
// WithWaitStrategyAndDeadline sets the wait strategy for a container, including deadline
func WithWaitStrategyAndDeadline(deadline time.Duration, strategies ...wait.Strategy) CustomizeRequestOption {
return func(req *GenericContainerRequest) {
req.WaitingFor = wait.ForAll(strategies...).WithDeadline(deadline)
}
}