-
Notifications
You must be signed in to change notification settings - Fork 0
/
compose.go
398 lines (356 loc) · 10.3 KB
/
compose.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
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
package confort
import (
"context"
"errors"
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
"sync"
"time"
composetypes "github.com/compose-spec/compose-go/types"
"github.com/daichitakahashi/confort/internal/exclusion"
"github.com/daichitakahashi/confort/wait"
"github.com/docker/cli/cli/command"
composecmd "github.com/docker/compose/v2/cmd/compose"
"github.com/docker/compose/v2/pkg/api"
"github.com/docker/compose/v2/pkg/compose"
"github.com/docker/docker/client"
"github.com/lestrrat-go/option"
"go.uber.org/multierr"
)
type ComposeProject struct {
cli *client.Client
svc api.Service
proj *composetypes.Project
defaultTimeout time.Duration
ex exclusion.Control
m sync.Mutex
services map[string]bool
}
type (
composeIdent interface{ compose() }
ComposeOption interface {
option.Interface
composeIdent
}
identOptionProjectDir struct{}
identOptionProjectName struct{}
composeOption struct {
option.Interface
composeIdent
}
)
// ModDir is a special value that indicates the location of go.mod of the test
// target module. Use with WithProjectDir option.
const ModDir = "\000mod\000"
// WithProjectDir sets project directory. The directory is used as working
// directory of the project.
// Also, file paths of configuration(compose.yaml) is resolved based on this
// directory. Default value is a current directory of the process.
//
// If ModDir is passed as a part of args, the value is replaced with the location
// of go.mod of the test target module.
// This allows any test code of the module to specify same configuration files.
func WithProjectDir(dir ...string) ComposeOption {
return composeOption{
Interface: option.New(identOptionProjectDir{}, dir),
}
}
// WithProjectName sets project name, which works as namespace.
// Default name is a name of project directory.
func WithProjectName(name string) ComposeOption {
return composeOption{
Interface: option.New(identOptionProjectName{}, name),
}
}
func Compose(ctx context.Context, configFiles []string, opts ...ComposeOption) (*ComposeProject, error) {
if len(configFiles) == 0 {
return nil, errors.New("no config file specified")
}
var (
projectDir = []string{"."}
projectName string
clientOpts = []client.Opt{
client.FromEnv,
}
timeout time.Duration
ex = exclusion.NewControl()
err error
)
for _, opt := range opts {
switch opt.Ident() {
case identOptionProjectDir{}:
projectDir = opt.Value().([]string)
case identOptionProjectName{}:
projectName = opt.Value().(string)
case identOptionClientOptions{}:
clientOpts = opt.Value().([]client.Opt)
case identOptionDefaultTimeout{}:
timeout = opt.Value().(time.Duration)
}
}
ctx, cancel := applyTimeout(ctx, timeout)
defer cancel()
// create docker API client
apiClient, err := client.NewClientWithOpts(clientOpts...)
if err != nil {
return nil, err
}
apiClient.NegotiateAPIVersion(ctx)
// create docker cli instance and compose service
dockerCli, err := command.NewDockerCli(
command.DockerCliOption(command.WithInitializeClient(func(dockerCli *command.DockerCli) (client.APIClient, error) {
return apiClient, nil
})),
)
if err != nil {
return nil, err
}
service := api.NewServiceProxy().
WithService(compose.NewComposeService(dockerCli))
// load configurations
project, err := prepareProject(ctx, projectDir, projectName, configFiles)
if err != nil {
return nil, fmt.Errorf("failed to load configuration files correctly: %w", err)
}
for _, service := range project.Services {
service.CustomLabels = service.CustomLabels.
Add("CUSTOM_ENV1", "VALUE1").
Add("CUSTOM_ENV2", "VALUE2")
}
return &ComposeProject{
cli: apiClient,
svc: service,
proj: project,
defaultTimeout: timeout,
ex: ex,
services: map[string]bool{},
}, nil
}
func (c *ComposeProject) Close() error {
c.m.Lock()
defer c.m.Unlock()
services := make([]string, 0, len(c.services))
for service := range c.services {
services = append(services, service)
}
if len(services) == 0 {
return nil
}
ctx := context.Background()
return multierr.Append(
c.svc.Stop(ctx, c.proj.Name, api.StopOptions{
Services: services,
}),
c.svc.Remove(ctx, c.proj.Name, api.RemoveOptions{
Volumes: true, // TODO: requires consideration
Force: true,
Services: services,
}),
)
}
func prepareProject(ctx context.Context, dir []string, name string, configFiles []string) (*composetypes.Project, error) {
for i := range dir {
// ModDir is a special value.
// Retrieve module file path and use its parent directory as a project directory.
if dir[i] == ModDir {
val, err := resolveGoModDir(ctx)
if err != nil {
return nil, fmt.Errorf("failed to get module directory: %w", err)
}
dir[i] = val
}
}
projectDir := filepath.Join(dir...)
// Resolve config file paths with project directory.
configFiles, err := resolveConfigFilePath(projectDir, configFiles)
if err != nil {
return nil, err
}
proj, err := (&composecmd.ProjectOptions{
ConfigPaths: configFiles,
ProjectName: name,
ProjectDir: projectDir,
}).ToProject(nil) // Specify services to launch
if err != nil {
return nil, fmt.Errorf("failed to load project: %w", err)
}
// If projectDir indicates root directory, project name will be empty.
// This causes invalid container name("{project}-{service}-{number}" => "-{service}-{number}"),
// and container creation fails.
// We treat this as an error before container creation.
if proj.Name == "" {
return nil, fmt.Errorf("project name required")
}
return proj, nil
}
func resolveGoModDir(ctx context.Context) (string, error) {
out, err := exec.CommandContext(ctx, "go", "env", "GOMOD").Output()
if err != nil {
return "", fmt.Errorf("failed to get module directory: %w", err)
}
v := strings.TrimSpace(string(out))
if v == os.DevNull {
// If go.mod doesn't exist, use current directory.
return ".", nil
}
_, err = os.Stat(v)
if err != nil {
if os.IsNotExist(err) {
return "", fmt.Errorf("go.mod not found: %s", v)
}
return "", fmt.Errorf("failed to check go.mod: %w", err)
}
return filepath.Dir(v), nil
}
func resolveConfigFilePath(base string, configFiles []string) (r []string, err error) {
r = make([]string, 0, len(configFiles))
for _, f := range configFiles {
if f == "" || f == "-" {
continue // Ignore empty value and stdin.
}
if !filepath.IsAbs(f) {
// Adjust config file path based on specified directory.
// It is required because cli.ProjectFromOptions resolves configuration file paths
// based on working directory of its process.
f = filepath.Join(base, f)
}
r = append(r, f)
}
return r, nil
}
type (
upIdent interface{ up() }
UpOption interface {
option.Interface
upIdent
}
identOptionWaiter struct{}
upOption struct {
option.Interface
upIdent
}
)
func WithWaiter(w *wait.Waiter) UpOption {
return upOption{
Interface: option.New(identOptionWaiter{}, w),
}
}
type Service struct {
c *ComposeProject
s composetypes.ServiceConfig
name string
ports Ports
}
func (c *ComposeProject) Up(ctx context.Context, service string, opts ...UpOption) (*Service, error) {
// Check service name.
serviceConfig, err := c.proj.GetService(service)
if err != nil {
return nil, fmt.Errorf("compose: %w", err)
}
ctx, cancel := applyTimeout(ctx, c.defaultTimeout)
defer cancel()
var w *wait.Waiter
for _, opt := range opts {
switch opt.Ident() {
case identOptionWaiter{}:
w = opt.Value().(*wait.Waiter)
}
}
name := fmt.Sprintf("%s-%s", c.proj.Name, service)
unlock, err := c.ex.LockForContainerSetup(ctx, name)
if err != nil {
return nil, fmt.Errorf("failed to acquire lock of %q: %w", service, err)
}
defer unlock()
// Check service status.
s, err := c.svc.Ps(ctx, c.proj.Name, api.PsOptions{
Services: []string{service},
All: true,
})
if err != nil {
return nil, fmt.Errorf("failed to get service info: %w", err)
}
doUp := len(s) == 0
if !doUp {
switch s[0].State {
case "running":
case "created", "exiting":
doUp = true
case "paused":
return nil, fmt.Errorf("cannot start %q, unpause is not supported", service)
default:
return nil, fmt.Errorf("cannot start %q, unexpected container state %q", service, s[0].State)
}
}
if doUp {
// If the running service doesn't exist, create and start it.
err = c.svc.Up(ctx, c.proj, api.UpOptions{
Create: api.CreateOptions{
Services: []string{service},
},
Start: api.StartOptions{
Services: []string{service},
Wait: true, // Wait until running/healthy state(depend on configuration).
},
})
if err != nil {
return nil, fmt.Errorf("failed to launch service %q: %w", service, err)
}
s, err = c.svc.Ps(ctx, c.proj.Name, api.PsOptions{
Services: []string{service},
})
if err != nil {
return nil, fmt.Errorf("failed to get service info: %w", err)
} else if len(s) == 0 {
return nil, fmt.Errorf("service %q not found", service)
}
c.m.Lock()
c.services[service] = true
c.m.Unlock()
}
// Get bound ports.
containerID := s[0].ID
info, err := c.cli.ContainerInspect(ctx, containerID)
if err != nil {
return nil, fmt.Errorf("failed to get service container info: %w", err)
}
if w != nil {
err = w.Wait(ctx, &fetcher{
cli: c.cli,
containerID: containerID,
ports: info.NetworkSettings.Ports,
})
if err != nil {
return nil, fmt.Errorf("error on waiting service: %w", err)
}
}
return &Service{
c: c,
s: serviceConfig,
name: name,
ports: Ports(info.NetworkSettings.Ports),
}, nil
}
func (s *Service) Use(ctx context.Context, exclusive bool, opts ...UseOption) (Ports, ReleaseFunc, error) {
return use(ctx, s, exclusive, opts...)
}
func (s *Service) containerIdent() string {
return s.name
}
func (s *Service) containerPorts() Ports {
return s.ports
}
func (s *Service) exclusionControl() exclusion.Control {
return s.c.ex
}
// UseExclusive acquires an exclusive lock for using the container explicitly and returns its endpoint.
func (s *Service) UseExclusive(ctx context.Context, opts ...UseOption) (Ports, ReleaseFunc, error) {
return use(ctx, s, true, opts...)
}
// UseShared acquires a shared lock for using the container explicitly and returns its endpoint.
func (s *Service) UseShared(ctx context.Context, opts ...UseOption) (Ports, ReleaseFunc, error) {
return use(ctx, s, false, opts...)
}