This repository was archived by the owner on Nov 27, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 255
Expand file tree
/
Copy pathbuild.go
More file actions
381 lines (337 loc) · 10.2 KB
/
build.go
File metadata and controls
381 lines (337 loc) · 10.2 KB
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
/*
Copyright 2020 Docker Compose CLI authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package compose
import (
"context"
"fmt"
"os"
"strings"
"sync"
"github.com/compose-spec/compose-go/types"
"github.com/containerd/containerd/platforms"
"github.com/docker/buildx/build"
"github.com/docker/buildx/driver"
_ "github.com/docker/buildx/driver/docker" // required to get default driver registered
"github.com/docker/buildx/util/buildflags"
xprogress "github.com/docker/buildx/util/progress"
moby "github.com/docker/docker/api/types"
"github.com/docker/docker/registry"
bclient "github.com/moby/buildkit/client"
"github.com/moby/buildkit/session"
"github.com/moby/buildkit/session/auth/authprovider"
specs "github.com/opencontainers/image-spec/specs-go/v1"
"golang.org/x/sync/errgroup"
"github.com/docker/compose-cli/pkg/api"
"github.com/docker/compose-cli/pkg/progress"
"github.com/docker/compose-cli/pkg/utils"
)
func (s *composeService) Build(ctx context.Context, project *types.Project, options api.BuildOptions) error {
return progress.Run(ctx, func(ctx context.Context) error {
return s.build(ctx, project, options)
})
}
func (s *composeService) build(ctx context.Context, project *types.Project, options api.BuildOptions) error {
opts := map[string]build.Options{}
imagesToBuild := []string{}
args := flatten(options.Args.Resolve(func(s string) (string, bool) {
s, ok := project.Environment[s]
return s, ok
}))
for _, service := range project.Services {
if service.Build != nil {
imageName := getImageName(service, project.Name)
imagesToBuild = append(imagesToBuild, imageName)
buildOptions, err := s.toBuildOptions(project, service, imageName)
if err != nil {
return err
}
buildOptions.Pull = options.Pull
buildOptions.BuildArgs = mergeArgs(buildOptions.BuildArgs, args)
buildOptions.NoCache = options.NoCache
opts[imageName] = buildOptions
buildOptions.CacheFrom, err = buildflags.ParseCacheEntry(service.Build.CacheFrom)
if err != nil {
return err
}
for _, image := range service.Build.CacheFrom {
buildOptions.CacheFrom = append(buildOptions.CacheFrom, bclient.CacheOptionsEntry{
Type: "registry",
Attrs: map[string]string{"ref": image},
})
}
}
}
_, err := s.doBuild(ctx, project, opts, Containers{}, options.Progress)
if err == nil {
if len(imagesToBuild) > 0 && !options.Quiet {
utils.DisplayScanSuggestMsg()
}
}
return err
}
func (s *composeService) ensureImagesExists(ctx context.Context, project *types.Project, observedState Containers, quietPull bool) error {
for _, service := range project.Services {
if service.Image == "" && service.Build == nil {
return fmt.Errorf("invalid service %q. Must specify either image or build", service.Name)
}
}
images, err := s.getLocalImagesIDs(ctx, project)
if err != nil {
return err
}
err = s.pullRequiredImages(ctx, project, images, quietPull)
if err != nil {
return err
}
mode := xprogress.PrinterModeAuto
if quietPull {
mode = xprogress.PrinterModeQuiet
}
opts, imagesToBuild, err := s.getBuildOptions(project, images)
if err != nil {
return err
}
builtImages, err := s.doBuild(ctx, project, opts, observedState, mode)
if err != nil {
return err
}
if len(imagesToBuild) > 0 {
utils.DisplayScanSuggestMsg()
}
for name, digest := range builtImages {
images[name] = digest
}
// set digest as service.Image
for i, service := range project.Services {
digest, ok := images[getImageName(service, project.Name)]
if ok {
project.Services[i].Image = digest
}
}
return nil
}
func (s *composeService) getBuildOptions(project *types.Project, images map[string]string) (map[string]build.Options, []string, error) {
opts := map[string]build.Options{}
imagesToBuild := []string{}
for _, service := range project.Services {
if service.Image == "" && service.Build == nil {
return nil, nil, fmt.Errorf("invalid service %q. Must specify either image or build", service.Name)
}
imageName := getImageName(service, project.Name)
_, localImagePresent := images[imageName]
if service.Build != nil {
if localImagePresent && service.PullPolicy != types.PullPolicyBuild {
continue
}
imagesToBuild = append(imagesToBuild, imageName)
opt, err := s.toBuildOptions(project, service, imageName)
if err != nil {
return nil, nil, err
}
opts[imageName] = opt
continue
}
}
return opts, imagesToBuild, nil
}
func (s *composeService) getLocalImagesIDs(ctx context.Context, project *types.Project) (map[string]string, error) {
imgs, err := s.getLocalImageSummaries(ctx, project)
if err != nil {
return nil, err
}
images := map[string]string{}
for name, info := range imgs {
images[name] = info.ID
}
return images, nil
}
func (s *composeService) getLocalImageSummaries(ctx context.Context, project *types.Project) (map[string]api.ImageSummary, error) {
imageNames := []string{}
for _, s := range project.Services {
imgName := getImageName(s, project.Name)
if !utils.StringContains(imageNames, imgName) {
imageNames = append(imageNames, imgName)
}
}
imgs, err := s.getImages(ctx, imageNames)
if err != nil {
return nil, err
}
return imgs, nil
}
func (s *composeService) getLocalImagesDigests(ctx context.Context, project *types.Project) (map[string][]string, error) {
imgs, err := s.getLocalImageSummaries(ctx, project)
if err != nil {
return nil, err
}
images := map[string][]string{}
for name, summary := range imgs {
for _, d := range summary.Digests {
s := strings.Split(d, "@")
images[name] = append(images[name], s[len(s)-1])
}
}
return images, nil
}
func (s *composeService) getDistributionImagesDigests(ctx context.Context, project *types.Project) (map[string]string, error) {
images := map[string]string{}
for _, service := range project.Services {
if service.Image == "" {
continue
}
images[service.Image] = ""
}
info, err := s.apiClient.Info(ctx)
if err != nil {
return nil, err
}
if info.IndexServerAddress == "" {
info.IndexServerAddress = registry.IndexServer
}
l := sync.Mutex{}
eg, ctx := errgroup.WithContext(ctx)
for img := range images {
img := img
eg.Go(func() error {
registryAuth, err := getEncodedRegistryAuth(img, info, s.configFile)
if err != nil {
return err
}
inspect, _ := s.apiClient.DistributionInspect(ctx, img, registryAuth)
// Ignore error here.
// If you catch error here, all inspect requests will fail.
l.Lock()
images[img] = inspect.Descriptor.Digest.String()
l.Unlock()
return nil
})
}
return images, eg.Wait()
}
func (s *composeService) doBuild(ctx context.Context, project *types.Project, opts map[string]build.Options, observedState Containers, mode string) (map[string]string, error) {
info, err := s.apiClient.Info(ctx)
if err != nil {
return nil, err
}
if info.OSType == "windows" {
// no support yet for Windows container builds in Buildkit
// https://docs.docker.com/develop/develop-images/build_enhancements/#limitations
err := s.windowsBuild(opts, mode)
return nil, WrapCategorisedComposeError(err, BuildFailure)
}
if len(opts) == 0 {
return nil, nil
}
const drivername = "default"
d, err := driver.GetDriver(ctx, drivername, nil, s.apiClient, s.configFile, nil, nil, "", nil, nil, project.WorkingDir)
if err != nil {
return nil, err
}
driverInfo := []build.DriverInfo{
{
Name: "default",
Driver: d,
},
}
// Progress needs its own context that lives longer than the
// build one otherwise it won't read all the messages from
// build and will lock
progressCtx, cancel := context.WithCancel(context.Background())
defer cancel()
w := xprogress.NewPrinter(progressCtx, os.Stdout, mode)
// We rely on buildx "docker" builder integrated in docker engine, so don't need a DockerAPI here
response, err := build.Build(ctx, driverInfo, opts, nil, nil, w)
errW := w.Wait()
if err == nil {
err = errW
}
if err != nil {
return nil, WrapCategorisedComposeError(err, BuildFailure)
}
cw := progress.ContextWriter(ctx)
for _, c := range observedState {
for imageName := range opts {
if c.Image == imageName {
err = s.removeContainers(ctx, cw, []moby.Container{c}, nil, false)
if err != nil {
return nil, err
}
}
}
}
imagesBuilt := map[string]string{}
for name, img := range response {
if img == nil || len(img.ExporterResponse) == 0 {
continue
}
digest, ok := img.ExporterResponse["containerimage.digest"]
if !ok {
continue
}
imagesBuilt[name] = digest
}
return imagesBuilt, err
}
func (s *composeService) toBuildOptions(project *types.Project, service types.ServiceConfig, imageTag string) (build.Options, error) {
var tags []string
tags = append(tags, imageTag)
buildArgs := flatten(service.Build.Args.Resolve(func(s string) (string, bool) {
s, ok := project.Environment[s]
return s, ok
}))
var plats []specs.Platform
if service.Platform != "" {
p, err := platforms.Parse(service.Platform)
if err != nil {
return build.Options{}, err
}
plats = append(plats, p)
}
return build.Options{
Inputs: build.Inputs{
ContextPath: service.Build.Context,
DockerfilePath: service.Build.Dockerfile,
},
BuildArgs: buildArgs,
Tags: tags,
Target: service.Build.Target,
Exports: []bclient.ExportEntry{{Type: "image", Attrs: map[string]string{}}},
Platforms: plats,
Labels: service.Build.Labels,
Session: []session.Attachable{
authprovider.NewDockerAuthProvider(os.Stderr),
},
}, nil
}
func flatten(in types.MappingWithEquals) types.Mapping {
if len(in) == 0 {
return nil
}
out := types.Mapping{}
for k, v := range in {
if v == nil {
continue
}
out[k] = *v
}
return out
}
func mergeArgs(m ...types.Mapping) types.Mapping {
merged := types.Mapping{}
for _, mapping := range m {
for key, val := range mapping {
merged[key] = val
}
}
return merged
}