forked from ory/dockertest
/
dockertest.go
277 lines (237 loc) · 7 KB
/
dockertest.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
package dockertest
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"runtime"
"strings"
"time"
"github.com/cenkalti/backoff"
dc "github.com/ory/dockertest/docker"
"github.com/pkg/errors"
)
// Pool represents a connection to the docker API and is used to create and remove docker images.
type Pool struct {
Client *dc.Client
MaxWait time.Duration
}
// Resource represents a docker container.
type Resource struct {
Container *dc.Container
}
// GetPort returns a resource's published port. You can use it to connect to the service via localhost, e.g. tcp://localhost:1231/
func (r *Resource) GetPort(id string) string {
if r.Container == nil {
return ""
} else if r.Container.NetworkSettings == nil {
return ""
}
m, ok := r.Container.NetworkSettings.Ports[dc.Port(id)]
if !ok {
return ""
} else if len(m) == 0 {
return ""
}
return m[0].HostPort
}
func (r *Resource) GetBoundIP(id string) string {
if r.Container == nil {
return ""
} else if r.Container.NetworkSettings == nil {
return ""
}
m, ok := r.Container.NetworkSettings.Ports[dc.Port(id)]
if !ok {
return ""
} else if len(m) == 0 {
return ""
}
return m[0].HostIP
}
// NewTLSPool creates a new pool given an endpoint and the certificate path. This is required for endpoints that
// require TLS communication.
func NewTLSPool(endpoint, certpath string) (*Pool, error) {
ca := fmt.Sprintf("%s/ca.pem", certpath)
cert := fmt.Sprintf("%s/cert.pem", certpath)
key := fmt.Sprintf("%s/key.pem", certpath)
client, err := dc.NewTLSClient(endpoint, cert, key, ca)
if err != nil {
return nil, errors.Wrap(err, "")
}
return &Pool{
Client: client,
}, nil
}
// NewPool creates a new pool. You can pass an empty string to use the default, which is taken from the environment
// variable DOCKER_HOST and DOCKER_URL, or from docker-machine if the environment variable DOCKER_MACHINE_NAME is set,
// or if neither is defined a sensible default for the operating system you are on.
// TLS pools are automatically configured if the DOCKER_CERT_PATH environment variable exists.
func NewPool(endpoint string) (*Pool, error) {
if endpoint == "" {
if os.Getenv("DOCKER_MACHINE_NAME") != "" {
client, err := dc.NewClientFromEnv()
if err != nil {
return nil, errors.Wrap(err, "failed to create client from environment")
}
return &Pool{Client: client}, nil
} else if os.Getenv("DOCKER_HOST") != "" {
endpoint = os.Getenv("DOCKER_HOST")
} else if os.Getenv("DOCKER_URL") != "" {
endpoint = os.Getenv("DOCKER_URL")
} else if runtime.GOOS == "windows" {
endpoint = "http://localhost:2375"
} else {
endpoint = "unix:///var/run/docker.sock"
}
}
if os.Getenv("DOCKER_CERT_PATH") != "" && shouldPreferTls(endpoint) {
return NewTLSPool(endpoint, os.Getenv("DOCKER_CERT_PATH"))
}
client, err := dc.NewClient(endpoint)
if err != nil {
return nil, errors.Wrap(err, "")
}
return &Pool{
Client: client,
}, nil
}
func shouldPreferTls(endpoint string) bool {
return !strings.HasPrefix(endpoint, "http://") && !strings.HasPrefix(endpoint, "unix://")
}
// RunOptions is used to pass in optional parameters when running a container.
type RunOptions struct {
Hostname string
Name string
Repository string
Tag string
Env []string
Entrypoint []string
Cmd []string
Mounts []string
Links []string
ExposedPorts []string
ExtraHosts []string
WorkingDir string
Auth dc.AuthConfiguration
PortBindings map[dc.Port][]dc.PortBinding
}
// BuildAndRunWithOptions builds and starts a docker container
func (d *Pool) BuildAndRunWithOptions(dockerfilePath string, opts *RunOptions) (*Resource, error) {
// Set the Dockerfile folder as build context
dir, file := filepath.Split(dockerfilePath)
err := d.Client.BuildImage(dc.BuildImageOptions{
Name: opts.Name,
Dockerfile: file,
OutputStream: ioutil.Discard,
ContextDir: dir,
})
if err != nil {
return nil, errors.Wrap(err, "")
}
opts.Repository = opts.Name
return d.RunWithOptions(opts)
}
// BuildAndRun builds and starts a docker container
func (d *Pool) BuildAndRun(name, dockerfilePath string, env []string) (*Resource, error) {
return d.BuildAndRunWithOptions(dockerfilePath, &RunOptions{Name: name, Env: env})
}
// RunWithOptions starts a docker container.
//
// pool.Run(&RunOptions{Repository: "mongo", Cmd: []string{"mongod", "--smallfiles"}})
func (d *Pool) RunWithOptions(opts *RunOptions) (*Resource, error) {
repository := opts.Repository
tag := opts.Tag
env := opts.Env
cmd := opts.Cmd
ep := opts.Entrypoint
wd := opts.WorkingDir
var exp map[dc.Port]struct{}
if len(opts.ExposedPorts) > 0 {
exp = map[dc.Port]struct{}{}
for _, p := range opts.ExposedPorts {
exp[dc.Port(p)] = struct{}{}
}
}
mounts := []dc.Mount{}
for _, m := range opts.Mounts {
sd := strings.Split(m, ":")
if len(sd) == 2 {
mounts = append(mounts, dc.Mount{
Source: sd[0],
Destination: sd[1],
RW: true,
})
} else {
return nil, errors.Wrap(fmt.Errorf("invalid mount format: got %s, expected <src>:<dst>", m), "")
}
}
if tag == "" {
tag = "latest"
}
_, err := d.Client.InspectImage(fmt.Sprintf("%s:%s", repository, tag))
if err != nil {
if err := d.Client.PullImage(dc.PullImageOptions{
Repository: repository,
Tag: tag,
}, opts.Auth); err != nil {
return nil, errors.Wrap(err, "")
}
}
c, err := d.Client.CreateContainer(dc.CreateContainerOptions{
Name: opts.Name,
Config: &dc.Config{
Hostname: opts.Hostname,
Image: fmt.Sprintf("%s:%s", repository, tag),
Env: env,
Entrypoint: ep,
Cmd: cmd,
Mounts: mounts,
ExposedPorts: exp,
WorkingDir: wd,
},
HostConfig: &dc.HostConfig{
PublishAllPorts: true,
Binds: opts.Mounts,
Links: opts.Links,
PortBindings: opts.PortBindings,
ExtraHosts: opts.ExtraHosts,
},
})
if err != nil {
return nil, errors.Wrap(err, "")
}
if err := d.Client.StartContainer(c.ID, nil); err != nil {
return nil, errors.Wrap(err, "")
}
c, err = d.Client.InspectContainer(c.ID)
if err != nil {
return nil, errors.Wrap(err, "")
}
return &Resource{
Container: c,
}, nil
}
// Run starts a docker container.
//
// pool.Run("mysql", "5.3", []string{"FOO=BAR", "BAR=BAZ"})
func (d *Pool) Run(repository, tag string, env []string) (*Resource, error) {
return d.RunWithOptions(&RunOptions{Repository: repository, Tag: tag, Env: env})
}
// Purge removes a container and linked volumes from docker.
func (d *Pool) Purge(r *Resource) error {
if err := d.Client.RemoveContainer(dc.RemoveContainerOptions{ID: r.Container.ID, Force: true, RemoveVolumes: true}); err != nil {
return errors.Wrap(err, "")
}
return nil
}
// Retry is an exponential backoff retry helper. You can use it to wait for e.g. mysql to boot up.
func (d *Pool) Retry(op func() error) error {
if d.MaxWait == 0 {
d.MaxWait = time.Minute
}
bo := backoff.NewExponentialBackOff()
bo.MaxInterval = time.Second * 5
bo.MaxElapsedTime = d.MaxWait
return backoff.Retry(op, bo)
}