-
-
Notifications
You must be signed in to change notification settings - Fork 522
/
Copy pathcompose_api.go
360 lines (281 loc) · 9.05 KB
/
compose_api.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
package compose
import (
"context"
"fmt"
"sort"
"strings"
"sync"
"github.com/compose-spec/compose-go/cli"
"github.com/compose-spec/compose-go/types"
"github.com/docker/cli/cli/command"
"github.com/docker/compose/v2/pkg/api"
types2 "github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/filters"
"github.com/docker/docker/client"
"golang.org/x/sync/errgroup"
testcontainers "github.com/testcontainers/testcontainers-go"
wait "github.com/testcontainers/testcontainers-go/wait"
)
type stackUpOptionFunc func(s *stackUpOptions)
func (f stackUpOptionFunc) applyToStackUp(o *stackUpOptions) {
f(o)
}
//nolint:unused
type stackDownOptionFunc func(do *api.DownOptions)
//nolint:unused
func (f stackDownOptionFunc) applyToStackDown(do *api.DownOptions) {
f(do)
}
// RunServices is comparable to 'docker-compose run' as it only creates a subset of containers
// instead of all services defined by the project
func RunServices(serviceNames ...string) StackUpOption {
return stackUpOptionFunc(func(o *stackUpOptions) {
o.Services = serviceNames
})
}
// IgnoreOrphans - Ignore legacy containers for services that are not defined in the project
type IgnoreOrphans bool
//nolint:unused
func (io IgnoreOrphans) applyToStackUp(co *api.CreateOptions, _ *api.StartOptions) {
co.IgnoreOrphans = bool(io)
}
// RemoveOrphans will cleanup containers that are not declared on the compose model but own the same labels
type RemoveOrphans bool
func (ro RemoveOrphans) applyToStackUp(o *stackUpOptions) {
o.RemoveOrphans = bool(ro)
}
func (ro RemoveOrphans) applyToStackDown(o *stackDownOptions) {
o.RemoveOrphans = bool(ro)
}
// Wait won't return until containers reached the running|healthy state
type Wait bool
func (w Wait) applyToStackUp(o *stackUpOptions) {
o.Wait = bool(w)
}
// RemoveImages used by services
type RemoveImages uint8
func (ri RemoveImages) applyToStackDown(o *stackDownOptions) {
switch ri {
case RemoveImagesAll:
o.Images = "all"
case RemoveImagesLocal:
o.Images = "local"
}
}
type ComposeStackFiles []string
func (f ComposeStackFiles) applyToComposeStack(o *composeStackOptions) {
o.Paths = f
}
type StackIdentifier string
func (f StackIdentifier) applyToComposeStack(o *composeStackOptions) {
o.Identifier = string(f)
}
func (f StackIdentifier) String() string {
return string(f)
}
const (
// RemoveImagesAll - remove all images used by the stack
RemoveImagesAll RemoveImages = iota
// RemoveImagesLocal - remove only images that don't have a tag
RemoveImagesLocal
)
type dockerCompose struct {
// used to synchronize operations
lock sync.RWMutex
// name/identifier of the stack that will be started
// by default a UUID will be used
name string
// paths to stack files that will be considered when compiling the final compose project
configs []string
// wait strategies that are applied per service when starting the stack
// only one strategy can be added to a service, to use multiple use wait.ForAll(...)
waitStrategies map[string]wait.Strategy
// cache for containers that are part of the stack
// used in ServiceContainer(...) function to avoid calls to the Docker API
containers map[string]*testcontainers.DockerContainer
// docker/compose API service instance used to control the compose stack
composeService api.Service
// Docker API client used to interact with single container instances and the Docker API e.g. to list containers
dockerClient client.APIClient
// options used to compile the compose project
// e.g. environment settings, ...
projectOptions []cli.ProjectOptionsFn
// compiled compose project
// can be nil if the stack wasn't started yet
project *types.Project
}
func (d *dockerCompose) ServiceContainer(ctx context.Context, svcName string) (*testcontainers.DockerContainer, error) {
d.lock.Lock()
defer d.lock.Unlock()
return d.lookupContainer(ctx, svcName)
}
func (d *dockerCompose) Services() []string {
d.lock.Lock()
defer d.lock.Unlock()
return d.project.ServiceNames()
}
func (d *dockerCompose) Down(ctx context.Context, opts ...StackDownOption) error {
d.lock.Lock()
defer d.lock.Unlock()
options := stackDownOptions{
DownOptions: api.DownOptions{
Project: d.project,
},
}
for i := range opts {
opts[i].applyToStackDown(&options)
}
return d.composeService.Down(ctx, d.name, options.DownOptions)
}
func (d *dockerCompose) Up(ctx context.Context, opts ...StackUpOption) (err error) {
d.lock.Lock()
defer d.lock.Unlock()
d.project, err = d.compileProject()
if err != nil {
return err
}
upOptions := stackUpOptions{
Services: d.project.ServiceNames(),
Recreate: api.RecreateDiverged,
RecreateDependencies: api.RecreateDiverged,
Project: d.project,
}
for i := range opts {
opts[i].applyToStackUp(&upOptions)
}
if len(upOptions.Services) != len(d.project.Services) {
sort.Strings(upOptions.Services)
filteredServices := make(types.Services, 0, len(d.project.Services))
for i := range d.project.Services {
if idx := sort.SearchStrings(upOptions.Services, d.project.Services[i].Name); idx < len(upOptions.Services) && upOptions.Services[idx] == d.project.Services[i].Name {
filteredServices = append(filteredServices, d.project.Services[i])
}
}
d.project.Services = filteredServices
}
err = d.composeService.Up(ctx, d.project, api.UpOptions{
Create: api.CreateOptions{
Services: upOptions.Services,
Recreate: upOptions.Recreate,
RecreateDependencies: upOptions.RecreateDependencies,
RemoveOrphans: upOptions.RemoveOrphans,
},
Start: api.StartOptions{
Project: upOptions.Project,
Wait: upOptions.Wait,
},
})
if err != nil {
return err
}
if len(d.waitStrategies) == 0 {
return nil
}
errGrp, errGrpCtx := errgroup.WithContext(ctx)
for svc, strategy := range d.waitStrategies { // pinning the variables
svc := svc
strategy := strategy
errGrp.Go(func() error {
target, err := d.lookupContainer(errGrpCtx, svc)
if err != nil {
return err
}
return strategy.WaitUntilReady(errGrpCtx, target)
})
}
return errGrp.Wait()
}
func (d *dockerCompose) WaitForService(s string, strategy wait.Strategy) ComposeStack {
d.lock.Lock()
defer d.lock.Unlock()
d.waitStrategies[s] = strategy
return d
}
func (d *dockerCompose) WithEnv(m map[string]string) ComposeStack {
d.lock.Lock()
defer d.lock.Unlock()
d.projectOptions = append(d.projectOptions, withEnv(m))
return d
}
func (d *dockerCompose) WithOsEnv() ComposeStack {
d.lock.Lock()
defer d.lock.Unlock()
d.projectOptions = append(d.projectOptions, cli.WithOsEnv)
return d
}
func (d *dockerCompose) lookupContainer(ctx context.Context, svcName string) (*testcontainers.DockerContainer, error) {
if container, ok := d.containers[svcName]; ok {
return container, nil
}
listOptions := types2.ContainerListOptions{
All: true,
Filters: filters.NewArgs(
filters.Arg("label", fmt.Sprintf("%s=%s", api.ProjectLabel, d.name)),
filters.Arg("label", fmt.Sprintf("%s=%s", api.ServiceLabel, svcName)),
),
}
containers, err := d.dockerClient.ContainerList(ctx, listOptions)
if err != nil {
return nil, err
}
if len(containers) == 0 {
return nil, fmt.Errorf("no container found for service name %s", svcName)
}
containerInstance := containers[0]
container := &testcontainers.DockerContainer{
ID: containerInstance.ID,
}
dockerProvider := &testcontainers.DockerProvider{}
dockerProvider.SetClient(d.dockerClient)
container.SetProvider(dockerProvider)
d.containers[svcName] = container
return container, nil
}
func (d *dockerCompose) compileProject() (*types.Project, error) {
const nameAndDefaultConfigPath = 2
projectOptions := make([]cli.ProjectOptionsFn, len(d.projectOptions), len(d.projectOptions)+nameAndDefaultConfigPath)
copy(projectOptions, d.projectOptions)
projectOptions = append(projectOptions, cli.WithName(d.name), cli.WithDefaultConfigPath)
compiledOptions, err := cli.NewProjectOptions(d.configs, projectOptions...)
if err != nil {
return nil, err
}
proj, err := cli.ProjectFromOptions(compiledOptions)
if err != nil {
return nil, err
}
for i, s := range proj.Services {
s.CustomLabels = map[string]string{
api.ProjectLabel: proj.Name,
api.ServiceLabel: s.Name,
api.VersionLabel: api.ComposeVersion,
api.WorkingDirLabel: proj.WorkingDir,
api.ConfigFilesLabel: strings.Join(proj.ComposeFiles, ","),
api.OneoffLabel: "False", // default, will be overridden by `run` command
}
if compiledOptions.EnvFile != "" {
s.CustomLabels[api.EnvironmentFileLabel] = compiledOptions.EnvFile
}
proj.Services[i] = s
}
return proj, nil
}
func withEnv(env map[string]string) func(*cli.ProjectOptions) error {
return func(options *cli.ProjectOptions) error {
for k, v := range env {
if _, ok := options.Environment[k]; ok {
return fmt.Errorf("environment with key %s already set", k)
} else {
options.Environment[k] = v
}
}
return nil
}
}
func makeClient(*command.DockerCli) (client.APIClient, error) {
dockerClient, _, _, err := testcontainers.NewDockerClient()
if err != nil {
return nil, err
}
return dockerClient, nil
}