-
Notifications
You must be signed in to change notification settings - Fork 9
/
daemon.go
88 lines (74 loc) · 2.45 KB
/
daemon.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
// Copyright 2022 Namespace Labs Inc; All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
package buildkit
import (
"context"
"fmt"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/mount"
"github.com/docker/docker/client"
buildkit "github.com/moby/buildkit/client"
"namespacelabs.dev/foundation/internal/console"
"namespacelabs.dev/foundation/internal/fnerrors"
"namespacelabs.dev/foundation/internal/runtime/docker"
"namespacelabs.dev/foundation/internal/runtime/docker/install"
)
const DefaultContainerName = "fn-buildkitd"
func EnsureBuildkitd(ctx context.Context, containerName string) (string, error) {
vendoredVersion, err := Version()
if err != nil {
return "", err
}
var spec = install.PersistentSpec{
Name: "buildkit",
ContainerName: containerName,
Version: vendoredVersion,
Image: "moby/buildkit",
WaitUntilRunning: func(ctx context.Context, containerName string) error {
return waitReadiness(ctx, func() (*buildkit.Client, error) {
return buildkit.New(ctx, makeAddr(containerName))
})
},
Volumes: map[string]string{
containerName: "/var/lib/buildkit",
},
Privileged: true,
}
if err := spec.Ensure(ctx, console.TypedOutput(ctx, "docker", console.CatOutputTool)); err != nil {
return "", err
}
return makeAddr(spec.ContainerName), nil
}
func RemoveBuildkitd(ctx context.Context) error {
dockerclient, err := docker.NewClient()
if err != nil {
return fnerrors.InternalError("failed to instantiate the docker client while removing buildkitd: %w", err)
}
// Ignore if the container is already removed.
ctr, err := dockerclient.ContainerInspect(ctx, DefaultContainerName)
if err != nil {
if client.IsErrNotFound(err) {
return nil
} else {
return err
}
}
// Remove container
opts := types.ContainerRemoveOptions{Force: true}
if err := dockerclient.ContainerRemove(ctx, ctr.Name, opts); err != nil {
return fnerrors.InternalError("failed to remove the buildkitd container: %w", err)
}
// Remove volumes
for _, m := range ctr.Mounts {
if m.Type == mount.TypeVolume {
if err := dockerclient.VolumeRemove(ctx, m.Name, true); err != nil {
return fnerrors.InternalError("failed to remove the buildkitd volume: %w", err)
}
}
}
return nil
}
func makeAddr(containerName string) string {
return fmt.Sprintf("docker-container://%s", containerName)
}