-
Notifications
You must be signed in to change notification settings - Fork 9
/
dfile.go
170 lines (144 loc) · 5.31 KB
/
dfile.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
// 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 dockerfile
import (
"bytes"
"context"
"errors"
"fmt"
"io/fs"
"strings"
"github.com/moby/buildkit/client/llb"
"github.com/moby/buildkit/frontend/dockerfile/dockerignore"
"github.com/moby/buildkit/frontend/dockerui"
specs "github.com/opencontainers/image-spec/specs-go/v1"
"golang.org/x/exp/maps"
"namespacelabs.dev/foundation/internal/artifacts/oci"
"namespacelabs.dev/foundation/internal/build"
"namespacelabs.dev/foundation/internal/build/buildkit"
"namespacelabs.dev/foundation/internal/compute"
"namespacelabs.dev/foundation/internal/fnerrors"
"namespacelabs.dev/foundation/internal/parsing/platform"
"namespacelabs.dev/foundation/schema"
"namespacelabs.dev/foundation/std/pkggraph"
"namespacelabs.dev/foundation/std/tasks"
)
// A Dockerfile build is always relative to the module it lives in. Within that
// module, what's the relative path to the context, and within that context,
// what's the relative path to the Dockerfile.
func Build(rel string, d *schema.ImageBuildPlan_DockerBuild) (build.Spec, error) {
return dockerfileBuild{rel, d}, nil
}
type dockerfileBuild struct {
contextRel string // Relative to the workspace.
plan *schema.ImageBuildPlan_DockerBuild // Dockerfile is relative to ContextRel.
}
var _ build.Spec = dockerfileBuild{}
func makeDockerfileState(sourceLabel string, contents []byte) llb.State {
return llb.Scratch().
File(llb.Mkfile("/Dockerfile", 0644,
contents,
llb.WithCreatedTime(build.FixedPoint)),
llb.WithCustomName(fmt.Sprintf("Dockerfile (%s)", sourceLabel)))
}
func (df dockerfileBuild) BuildImage(ctx context.Context, env pkggraph.SealedContext, conf build.Configuration) (compute.Computable[oci.Image], error) {
// There's a compromise here: we go through a non-snapshot to fetch
// .dockerignore, to avoid creating two snapshots.
dfignore, err := fs.ReadFile(conf.Workspace().ReadOnlyFS(df.contextRel), ".dockerignore")
if err != nil {
if !errors.Is(err, fs.ErrNotExist) {
return nil, fnerrors.InternalError("failed to check if a .dockerignore exists: %w", err)
}
}
excludes, err := dockerignore.ReadAll(bytes.NewReader(dfignore))
if err != nil {
return nil, fnerrors.New("failed to parse dockerignore: %w", err)
}
dfcontents, err := fs.ReadFile(conf.Workspace().ReadOnlyFS(df.contextRel), df.plan.Dockerfile)
if err != nil {
return nil, err
}
generatedRequest := &generateRequest{
contextRel: df.contextRel,
dockerfile: string(dfcontents),
conf: conf,
plan: df.plan,
excludes: excludes,
}
return buildkit.MakeImage(
buildkit.DeferClient(env.Configuration(), conf.TargetPlatform()),
conf,
generatedRequest,
[]buildkit.LocalContents{
dockerContext(conf, df.contextRel, excludes),
}, conf.PublishName()), nil
}
func (df dockerfileBuild) PlatformIndependent() bool { return false }
type generateRequest struct {
contextRel, dockerfile string
conf build.Configuration
excludes []string
plan *schema.ImageBuildPlan_DockerBuild
compute.LocalScoped[*buildkit.FrontendRequest]
}
var _ compute.Computable[*buildkit.FrontendRequest] = &generateRequest{}
func (g *generateRequest) Action() *tasks.ActionEvent {
return tasks.Action("buildkit.make-dockerfile-request").
Arg("module_name", g.conf.Workspace().ModuleName()).
Arg("rel", g.contextRel).
LogLevel(1)
}
func (g *generateRequest) Inputs() *compute.In {
return compute.Inputs().
Str("contextRel", g.contextRel).
Str("dockerfile", g.dockerfile).
JSON("plan", g.plan).
Indigestible("conf", g.conf)
}
func (g *generateRequest) Output() compute.Output { return compute.Output{NotCacheable: true} }
func (g *generateRequest) Compute(ctx context.Context, deps compute.Resolved) (*buildkit.FrontendRequest, error) {
req := &buildkit.FrontendRequest{
Frontend: "dockerfile.v0",
FrontendInputs: map[string]llb.State{
dockerui.DefaultLocalNameDockerfile: makeDockerfileState(g.conf.SourceLabel(), []byte(g.dockerfile)),
dockerui.DefaultLocalNameContext: buildkit.MakeLocalState(dockerContext(g.conf, g.contextRel, g.excludes)),
},
}
if g.conf.TargetPlatform() != nil {
req.FrontendAttrs = makeDockerOpts([]specs.Platform{*g.conf.TargetPlatform()})
}
if len(g.plan.Attrs) > 0 {
req.FrontendAttrs = mergeMaps(req.FrontendAttrs, g.plan.Attrs)
}
if g.conf.TargetPlatform() != nil {
p := platform.FormatPlatform(*g.conf.TargetPlatform())
for _, x := range g.plan.AttrsByPlatform {
if x.Platform == p {
req.FrontendAttrs = mergeMaps(req.FrontendAttrs, x.Attrs)
}
}
}
return req, nil
}
func mergeMaps(target map[string]string, src map[string]string) map[string]string {
if target == nil {
return maps.Clone(src)
}
for k, v := range src {
target[k] = v
}
return target
}
func dockerContext(conf build.Configuration, contextRel string, excludes []string) buildkit.LocalContents {
return buildkit.LocalContents{
Module: conf.Workspace(),
Path: contextRel,
ExcludePatterns: excludes,
}
}
func makeDockerOpts(platforms []specs.Platform) map[string]string {
return map[string]string{
"platform": strings.Join(platform.FormatPlatforms(platforms), ","),
}
}