-
Notifications
You must be signed in to change notification settings - Fork 217
/
docker.go
492 lines (458 loc) · 15.7 KB
/
docker.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
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
package utils
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"log"
"os"
"regexp"
"strings"
"sync"
"time"
podman "github.com/containers/common/libnetwork/types"
"github.com/docker/cli/cli/command"
"github.com/docker/cli/cli/compose/loader"
dockerConfig "github.com/docker/cli/cli/config"
dockerFlags "github.com/docker/cli/cli/flags"
"github.com/docker/cli/cli/streams"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/api/types/filters"
"github.com/docker/docker/api/types/image"
"github.com/docker/docker/api/types/mount"
"github.com/docker/docker/api/types/network"
"github.com/docker/docker/api/types/versions"
"github.com/docker/docker/api/types/volume"
"github.com/docker/docker/client"
"github.com/docker/docker/errdefs"
"github.com/docker/docker/pkg/jsonmessage"
"github.com/docker/docker/pkg/stdcopy"
"github.com/go-errors/errors"
"github.com/spf13/viper"
"go.opentelemetry.io/otel"
)
var Docker = NewDocker()
func NewDocker() *client.Client {
// TODO: refactor to initialize lazily
cli, err := command.NewDockerCli()
if err != nil {
log.Fatalln("Failed to create Docker client:", err)
}
// Silence otel errors as users don't care about docker metrics
// 2024/08/12 23:11:12 1 errors occurred detecting resource:
// * conflicting Schema URL: https://opentelemetry.io/schemas/1.21.0
otel.SetErrorHandler(otel.ErrorHandlerFunc(func(cause error) {}))
if err := cli.Initialize(&dockerFlags.ClientOptions{}); err != nil {
log.Fatalln("Failed to initialize Docker client:", err)
}
return cli.Client().(*client.Client)
}
const (
DinDHost = "host.docker.internal"
CliProjectLabel = "com.supabase.cli.project"
composeProjectLabel = "com.docker.compose.project"
)
func DockerNetworkCreateIfNotExists(ctx context.Context, mode container.NetworkMode, labels map[string]string) error {
// Non-user defined networks should already exist
if !isUserDefined(mode) {
return nil
}
_, err := Docker.NetworkCreate(ctx, mode.NetworkName(), network.CreateOptions{Labels: labels})
// if error is network already exists, no need to propagate to user
if errdefs.IsConflict(err) || errors.Is(err, podman.ErrNetworkExists) {
return nil
}
if err != nil {
return errors.Errorf("failed to create docker network: %w", err)
}
return err
}
func WaitAll[T any](containers []T, exec func(container T) error) []error {
var wg sync.WaitGroup
result := make([]error, len(containers))
for i, container := range containers {
wg.Add(1)
go func(i int, container T) {
defer wg.Done()
result[i] = exec(container)
}(i, container)
}
wg.Wait()
return result
}
// NoBackupVolume TODO: encapsulate this state in a class
var NoBackupVolume = false
func DockerRemoveAll(ctx context.Context, w io.Writer, projectId string) error {
fmt.Fprintln(w, "Stopping containers...")
args := CliProjectFilter(projectId)
containers, err := Docker.ContainerList(ctx, container.ListOptions{
All: true,
Filters: args,
})
if err != nil {
return errors.Errorf("failed to list containers: %w", err)
}
// Gracefully shutdown containers
var ids []string
for _, c := range containers {
if c.State == "running" {
ids = append(ids, c.ID)
}
}
result := WaitAll(ids, func(id string) error {
if err := Docker.ContainerStop(ctx, id, container.StopOptions{}); err != nil {
return errors.Errorf("failed to stop container: %w", err)
}
return nil
})
if err := errors.Join(result...); err != nil {
return err
}
if report, err := Docker.ContainersPrune(ctx, args); err != nil {
return errors.Errorf("failed to prune containers: %w", err)
} else if viper.GetBool("DEBUG") {
fmt.Fprintln(os.Stderr, "Pruned containers:", report.ContainersDeleted)
}
// Remove named volumes
if NoBackupVolume {
vargs := args.Clone()
if versions.GreaterThanOrEqualTo(Docker.ClientVersion(), "1.42") {
// Since docker engine 25.0.3, all flag is required to include named volumes.
// https://github.com/docker/cli/blob/master/cli/command/volume/prune.go#L76
vargs.Add("all", "true")
}
if report, err := Docker.VolumesPrune(ctx, vargs); err != nil {
return errors.Errorf("failed to prune volumes: %w", err)
} else if viper.GetBool("DEBUG") {
fmt.Fprintln(os.Stderr, "Pruned volumes:", report.VolumesDeleted)
}
}
// Remove networks.
if report, err := Docker.NetworksPrune(ctx, args); err != nil {
return errors.Errorf("failed to prune networks: %w", err)
} else if viper.GetBool("DEBUG") {
fmt.Fprintln(os.Stderr, "Pruned network:", report.NetworksDeleted)
}
return nil
}
func CliProjectFilter(projectId string) filters.Args {
if len(projectId) == 0 {
return filters.NewArgs(
filters.Arg("label", CliProjectLabel),
)
}
return filters.NewArgs(
filters.Arg("label", CliProjectLabel+"="+projectId),
)
}
var (
// Only supports one registry per command invocation
registryAuth string
registryOnce sync.Once
)
func GetRegistryAuth() string {
registryOnce.Do(func() {
config := dockerConfig.LoadDefaultConfigFile(os.Stderr)
// Ref: https://docs.docker.com/engine/api/sdk/examples/#pull-an-image-with-authentication
auth, err := config.GetAuthConfig(GetRegistry())
if err != nil {
fmt.Fprintln(os.Stderr, "Failed to load registry credentials:", err)
return
}
encoded, err := json.Marshal(auth)
if err != nil {
fmt.Fprintln(os.Stderr, "Failed to serialise auth config:", err)
return
}
registryAuth = base64.URLEncoding.EncodeToString(encoded)
})
return registryAuth
}
// Defaults to Supabase public ECR for faster image pull
const defaultRegistry = "public.ecr.aws"
func GetRegistry() string {
registry := viper.GetString("INTERNAL_IMAGE_REGISTRY")
if len(registry) == 0 {
return defaultRegistry
}
return strings.ToLower(registry)
}
func GetRegistryImageUrl(imageName string) string {
registry := GetRegistry()
if registry == "docker.io" {
return imageName
}
// Configure mirror registry
parts := strings.Split(imageName, "/")
imageName = parts[len(parts)-1]
return registry + "/supabase/" + imageName
}
func DockerImagePull(ctx context.Context, imageTag string, w io.Writer) error {
out, err := Docker.ImagePull(ctx, imageTag, image.PullOptions{
RegistryAuth: GetRegistryAuth(),
})
if err != nil {
return errors.Errorf("failed to pull docker image: %w", err)
}
defer out.Close()
if err := jsonmessage.DisplayJSONMessagesToStream(out, streams.NewOut(w), nil); err != nil {
return errors.Errorf("failed to display json stream: %w", err)
}
return nil
}
// Used by unit tests
var timeUnit = time.Second
func DockerImagePullWithRetry(ctx context.Context, image string, retries int) error {
err := DockerImagePull(ctx, image, os.Stderr)
for i := 0; i < retries; i++ {
if err == nil || errors.Is(ctx.Err(), context.Canceled) {
break
}
fmt.Fprintln(os.Stderr, err)
period := time.Duration(2<<(i+1)) * timeUnit
fmt.Fprintf(os.Stderr, "Retrying after %v: %s\n", period, image)
time.Sleep(period)
err = DockerImagePull(ctx, image, os.Stderr)
}
return err
}
func DockerPullImageIfNotCached(ctx context.Context, imageName string) error {
imageUrl := GetRegistryImageUrl(imageName)
if _, _, err := Docker.ImageInspectWithRaw(ctx, imageUrl); err == nil {
return nil
} else if !client.IsErrNotFound(err) {
return errors.Errorf("failed to inspect docker image: %w", err)
}
return DockerImagePullWithRetry(ctx, imageUrl, 2)
}
var suggestDockerInstall = "Docker Desktop is a prerequisite for local development. Follow the official docs to install: https://docs.docker.com/desktop"
func DockerStart(ctx context.Context, config container.Config, hostConfig container.HostConfig, networkingConfig network.NetworkingConfig, containerName string) (string, error) {
// Pull container image
if err := DockerPullImageIfNotCached(ctx, config.Image); err != nil {
if client.IsErrConnectionFailed(err) {
CmdSuggestion = suggestDockerInstall
}
return "", err
}
// Setup default config
config.Image = GetRegistryImageUrl(config.Image)
if config.Labels == nil {
config.Labels = make(map[string]string, 2)
}
config.Labels[CliProjectLabel] = Config.ProjectId
config.Labels[composeProjectLabel] = Config.ProjectId
// Configure container network
hostConfig.ExtraHosts = append(hostConfig.ExtraHosts, extraHosts...)
if networkId := viper.GetString("network-id"); len(networkId) > 0 {
hostConfig.NetworkMode = container.NetworkMode(networkId)
} else if len(hostConfig.NetworkMode) == 0 {
hostConfig.NetworkMode = container.NetworkMode(NetId)
}
if err := DockerNetworkCreateIfNotExists(ctx, hostConfig.NetworkMode, config.Labels); err != nil {
return "", err
}
// Configure container volumes
var binds, sources []string
for _, bind := range hostConfig.Binds {
spec, err := loader.ParseVolume(bind)
if err != nil {
return "", errors.Errorf("failed to parse docker volume: %w", err)
}
if spec.Type != string(mount.TypeVolume) {
binds = append(binds, bind)
} else if len(spec.Source) > 0 {
sources = append(sources, spec.Source)
}
}
// Skip named volume for BitBucket pipeline
if os.Getenv("BITBUCKET_CLONE_DIR") != "" {
hostConfig.Binds = binds
// Bitbucket doesn't allow for --security-opt option to be set
// https://support.atlassian.com/bitbucket-cloud/docs/run-docker-commands-in-bitbucket-pipelines/#Full-list-of-restricted-commands
hostConfig.SecurityOpt = nil
} else {
// Create named volumes with labels
for _, name := range sources {
if _, err := Docker.VolumeCreate(ctx, volume.CreateOptions{
Name: name,
Labels: config.Labels,
}); err != nil {
return "", errors.Errorf("failed to create volume: %w", err)
}
}
}
// Create container from image
resp, err := Docker.ContainerCreate(ctx, &config, &hostConfig, &networkingConfig, nil, containerName)
if err != nil {
return "", errors.Errorf("failed to create docker container: %w", err)
}
// Run container in background
err = Docker.ContainerStart(ctx, resp.ID, container.StartOptions{})
if err != nil {
if hostPort := parsePortBindError(err); len(hostPort) > 0 {
CmdSuggestion = suggestDockerStop(ctx, hostPort)
prefix := "Or configure"
if len(CmdSuggestion) == 0 {
prefix = "Try configuring"
}
name := containerName
if endpoint, ok := networkingConfig.EndpointsConfig[NetId]; ok && len(endpoint.Aliases) > 0 {
name = endpoint.Aliases[0]
}
CmdSuggestion += fmt.Sprintf("\n%s a different %s port in %s", prefix, name, Bold(ConfigPath))
}
err = errors.Errorf("failed to start docker container: %w", err)
}
return resp.ID, err
}
func DockerRemove(containerId string) {
if err := Docker.ContainerRemove(context.Background(), containerId, container.RemoveOptions{
RemoveVolumes: true,
Force: true,
}); err != nil {
fmt.Fprintln(os.Stderr, "Failed to remove container:", containerId, err)
}
}
type DockerJob struct {
Image string
Env []string
Cmd []string
}
func DockerRunJob(ctx context.Context, job DockerJob, stdout, stderr io.Writer) error {
return DockerRunOnceWithStream(ctx, job.Image, job.Env, job.Cmd, stdout, stderr)
}
// Runs a container image exactly once, returning stdout and throwing error on non-zero exit code.
func DockerRunOnce(ctx context.Context, image string, env []string, cmd []string) (string, error) {
stderr := GetDebugLogger()
var out bytes.Buffer
err := DockerRunOnceWithStream(ctx, image, env, cmd, &out, stderr)
return out.String(), err
}
func DockerRunOnceWithStream(ctx context.Context, image string, env, cmd []string, stdout, stderr io.Writer) error {
return DockerRunOnceWithConfig(ctx, container.Config{
Image: image,
Env: env,
Cmd: cmd,
}, container.HostConfig{}, network.NetworkingConfig{}, "", stdout, stderr)
}
func DockerRunOnceWithConfig(ctx context.Context, config container.Config, hostConfig container.HostConfig, networkingConfig network.NetworkingConfig, containerName string, stdout, stderr io.Writer) error {
// Cannot rely on docker's auto remove because
// 1. We must inspect exit code after container stops
// 2. Context cancellation may happen after start
container, err := DockerStart(ctx, config, hostConfig, networkingConfig, containerName)
if err != nil {
return err
}
defer DockerRemove(container)
return DockerStreamLogs(ctx, container, stdout, stderr)
}
func DockerStreamLogs(ctx context.Context, containerId string, stdout, stderr io.Writer) error {
// Stream logs
logs, err := Docker.ContainerLogs(ctx, containerId, container.LogsOptions{
ShowStdout: true,
ShowStderr: true,
Follow: true,
})
if err != nil {
return errors.Errorf("failed to read docker logs: %w", err)
}
defer logs.Close()
if _, err := stdcopy.StdCopy(stdout, stderr, logs); err != nil {
return errors.Errorf("failed to copy docker logs: %w", err)
}
// Check exit code
resp, err := Docker.ContainerInspect(ctx, containerId)
if err != nil {
return errors.Errorf("failed to inspect docker container: %w", err)
}
if resp.State.ExitCode > 0 {
return errors.Errorf("error running container: exit %d", resp.State.ExitCode)
}
return nil
}
func DockerStreamLogsOnce(ctx context.Context, containerId string, stdout, stderr io.Writer) error {
logs, err := Docker.ContainerLogs(ctx, containerId, container.LogsOptions{
ShowStdout: true,
ShowStderr: true,
})
if err != nil {
return errors.Errorf("failed to read docker logs: %w", err)
}
defer logs.Close()
if _, err := stdcopy.StdCopy(stdout, stderr, logs); err != nil {
return errors.Errorf("failed to copy docker logs: %w", err)
}
return nil
}
// Exec a command once inside a container, returning stdout and throwing error on non-zero exit code.
func DockerExecOnce(ctx context.Context, containerId string, env []string, cmd []string) (string, error) {
stderr := io.Discard
if viper.GetBool("DEBUG") {
stderr = os.Stderr
}
var out bytes.Buffer
err := DockerExecOnceWithStream(ctx, containerId, "", env, cmd, &out, stderr)
return out.String(), err
}
func DockerExecOnceWithStream(ctx context.Context, containerId, workdir string, env, cmd []string, stdout, stderr io.Writer) error {
// Reset shadow database
exec, err := Docker.ContainerExecCreate(ctx, containerId, container.ExecOptions{
Env: env,
Cmd: cmd,
WorkingDir: workdir,
AttachStderr: true,
AttachStdout: true,
})
if err != nil {
return errors.Errorf("failed to exec docker create: %w", err)
}
// Read exec output
resp, err := Docker.ContainerExecAttach(ctx, exec.ID, container.ExecStartOptions{})
if err != nil {
return errors.Errorf("failed to exec docker attach: %w", err)
}
defer resp.Close()
// Capture error details
if _, err := stdcopy.StdCopy(stdout, stderr, resp.Reader); err != nil {
return errors.Errorf("failed to copy docker logs: %w", err)
}
// Get the exit code
iresp, err := Docker.ContainerExecInspect(ctx, exec.ID)
if err != nil {
return errors.Errorf("failed to exec docker inspect: %w", err)
}
if iresp.ExitCode > 0 {
err = errors.New("error executing command")
}
return err
}
var portErrorPattern = regexp.MustCompile("Bind for (.*) failed: port is already allocated")
func parsePortBindError(err error) string {
matches := portErrorPattern.FindStringSubmatch(err.Error())
if len(matches) > 1 {
return matches[len(matches)-1]
}
return ""
}
func suggestDockerStop(ctx context.Context, hostPort string) string {
if containers, err := Docker.ContainerList(ctx, container.ListOptions{}); err == nil {
for _, c := range containers {
for _, p := range c.Ports {
if fmt.Sprintf("%s:%d", p.IP, p.PublicPort) == hostPort {
if project, ok := c.Labels[CliProjectLabel]; ok {
return "\nTry stopping the running project with " + Aqua("supabase stop --project-id "+project)
} else {
name := c.ID
if len(c.Names) > 0 {
name = c.Names[0]
}
return "\nTry stopping the running container with " + Aqua("docker stop "+name)
}
}
}
}
}
return ""
}