forked from ko-build/ko
-
Notifications
You must be signed in to change notification settings - Fork 0
/
resolver.go
438 lines (384 loc) · 12.1 KB
/
resolver.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
/*
Copyright 2018 Google LLC 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.
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 commands
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"io/ioutil"
"os"
"path"
"strings"
"sync"
"github.com/google/go-containerregistry/pkg/name"
"golang.org/x/sync/errgroup"
"gopkg.in/yaml.v3"
"k8s.io/apimachinery/pkg/labels"
"github.com/google/ko/pkg/build"
"github.com/google/ko/pkg/commands/options"
"github.com/google/ko/pkg/publish"
"github.com/google/ko/pkg/resolve"
)
// ua returns the ko user agent.
func ua() string {
if v := version(); v != "" {
return "ko/" + v
}
return "ko"
}
func gobuildOptions(bo *options.BuildOptions) ([]build.Option, error) {
creationTime, err := getCreationTime()
if err != nil {
return nil, err
}
kodataCreationTime, err := getKoDataCreationTime()
if err != nil {
return nil, err
}
if len(bo.Platforms) == 0 {
envPlatform := "linux/amd64"
goos, goarch, goarm := os.Getenv("GOOS"), os.Getenv("GOARCH"), os.Getenv("GOARM")
// Default to linux/amd64 unless GOOS and GOARCH are set.
if goos != "" && goarch != "" {
envPlatform = path.Join(goos, goarch)
}
// Use GOARM for variant if it's set and GOARCH is arm.
if strings.Contains(goarch, "arm") && goarm != "" {
envPlatform = path.Join(envPlatform, "v"+goarm)
}
bo.Platforms = []string{envPlatform}
} else {
// Make sure these are all unset
for _, env := range []string{"GOOS", "GOARCH", "GOARM"} {
if s, ok := os.LookupEnv(env); ok {
return nil, fmt.Errorf("cannot use --platform with %s=%q", env, s)
}
}
}
opts := []build.Option{
build.WithBaseImages(getBaseImage(bo)),
build.WithPlatforms(bo.Platforms...),
build.WithJobs(bo.ConcurrentBuilds),
}
if creationTime != nil {
opts = append(opts, build.WithCreationTime(*creationTime))
}
if kodataCreationTime != nil {
opts = append(opts, build.WithKoDataCreationTime(*kodataCreationTime))
}
if bo.DisableOptimizations {
opts = append(opts, build.WithDisabledOptimizations())
}
switch bo.SBOM {
case "none":
opts = append(opts, build.WithDisabledSBOM())
case "go.version-m":
opts = append(opts, build.WithGoVersionSBOM())
case "cyclonedx":
opts = append(opts, build.WithCycloneDX())
default: // "spdx"
opts = append(opts, build.WithSPDX(version()))
}
opts = append(opts, build.WithTrimpath(bo.Trimpath))
for _, lf := range bo.Labels {
parts := strings.SplitN(lf, "=", 2)
if len(parts) != 2 {
return nil, fmt.Errorf("invalid label flag: %s", lf)
}
opts = append(opts, build.WithLabel(parts[0], parts[1]))
}
if bo.BuildConfigs != nil {
opts = append(opts, build.WithConfig(bo.BuildConfigs))
}
return opts, nil
}
// NewBuilder creates a ko builder
func NewBuilder(ctx context.Context, bo *options.BuildOptions) (build.Interface, error) {
return makeBuilder(ctx, bo)
}
func makeBuilder(ctx context.Context, bo *options.BuildOptions) (*build.Caching, error) {
if err := bo.LoadConfig(); err != nil {
return nil, err
}
opt, err := gobuildOptions(bo)
if err != nil {
return nil, fmt.Errorf("error setting up builder options: %w", err)
}
innerBuilder, err := build.NewGobuilds(ctx, bo.WorkingDirectory, bo.BuildConfigs, opt...)
if err != nil {
return nil, err
}
// tl;dr Wrap builder in a caching builder.
//
// The caching builder should on Build calls:
// - Check for a valid Build future
// - if a valid Build future exists at the time of the request,
// then block on it.
// - if it does not, then initiate and record a Build future.
//
// This will benefit the following key cases:
// 1. When the same import path is referenced across multiple yaml files
// we can elide subsequent builds by blocking on the same image future.
// 2. When an affected yaml file has multiple import paths (mostly unaffected)
// we can elide the builds of unchanged import paths.
return build.NewCaching(innerBuilder)
}
// NewPublisher creates a ko publisher
func NewPublisher(po *options.PublishOptions) (publish.Interface, error) {
return makePublisher(po)
}
func makePublisher(po *options.PublishOptions) (publish.Interface, error) {
// Create the publish.Interface that we will use to publish image references
// to either a docker daemon or a container image registry.
innerPublisher, err := func() (publish.Interface, error) {
repoName := po.DockerRepo
namer := options.MakeNamer(po)
if repoName == publish.LocalDomain || po.Local {
// TODO(jonjohnsonjr): I'm assuming that nobody will
// use local with other publishers, but that might
// not be true.
return publish.NewDaemon(namer, po.Tags,
publish.WithDockerClient(po.DockerClient),
publish.WithLocalDomain(po.LocalDomain),
)
}
if repoName == publish.KindDomain {
return publish.NewKindPublisher(namer, po.Tags), nil
}
if repoName == "" && po.Push {
return nil, errors.New("KO_DOCKER_REPO environment variable is unset")
}
if _, err := name.NewRegistry(repoName); err != nil {
if _, err := name.NewRepository(repoName); err != nil {
return nil, fmt.Errorf("failed to parse %q as repository: %w", repoName, err)
}
}
publishers := []publish.Interface{}
if po.OCILayoutPath != "" {
lp, err := publish.NewLayout(po.OCILayoutPath)
if err != nil {
return nil, fmt.Errorf("failed to create LayoutPublisher for %q: %w", po.OCILayoutPath, err)
}
publishers = append(publishers, lp)
}
if po.TarballFile != "" {
tp := publish.NewTarball(po.TarballFile, repoName, namer, po.Tags)
publishers = append(publishers, tp)
}
userAgent := ua()
if po.UserAgent != "" {
userAgent = po.UserAgent
}
if po.Push {
dp, err := publish.NewDefault(repoName,
publish.WithUserAgent(userAgent),
publish.WithAuthFromKeychain(keychain),
publish.WithNamer(namer),
publish.WithTags(po.Tags),
publish.WithTagOnly(po.TagOnly),
publish.Insecure(po.InsecureRegistry),
)
if err != nil {
return nil, err
}
publishers = append(publishers, dp)
}
// If not publishing, at least generate a digest to simulate
// publishing.
if len(publishers) == 0 {
publishers = append(publishers, nopPublisher{
repoName: repoName,
namer: namer,
})
}
return publish.MultiPublisher(publishers...), nil
}()
if err != nil {
return nil, err
}
if po.ImageRefsFile != "" {
f, err := os.OpenFile(po.ImageRefsFile, os.O_RDWR|os.O_CREATE, 0644)
if err != nil {
return nil, err
}
innerPublisher, err = publish.NewRecorder(innerPublisher, f)
if err != nil {
return nil, err
}
}
// Wrap publisher in a memoizing publisher implementation.
return publish.NewCaching(innerPublisher)
}
// nopPublisher simulates publishing without actually publishing anything, to
// provide fallback behavior when the user configures no push destinations.
type nopPublisher struct {
repoName string
namer publish.Namer
}
func (n nopPublisher) Publish(_ context.Context, br build.Result, s string) (name.Reference, error) {
s = strings.TrimPrefix(s, build.StrictScheme)
h, err := br.Digest()
if err != nil {
return nil, err
}
return name.NewDigest(fmt.Sprintf("%s@%s", n.namer(n.repoName, s), h))
}
func (n nopPublisher) Close() error { return nil }
// resolvedFuture represents a "future" for the bytes of a resolved file.
type resolvedFuture chan []byte
func resolveFilesToWriter(
ctx context.Context,
builder *build.Caching,
publisher publish.Interface,
fo *options.FilenameOptions,
so *options.SelectorOptions,
out io.WriteCloser) error {
defer out.Close()
// By having this as a channel, we can hook this up to a filesystem
// watcher and leave `fs` open to stream the names of yaml files
// affected by code changes (including the modification of existing or
// creation of new yaml files).
fs := options.EnumerateFiles(fo)
// This tracks filename -> []importpath
var sm sync.Map
// This tracks resolution errors and ensures we cancel other builds if an
// individual build fails.
errs, ctx := errgroup.WithContext(ctx)
var futures []resolvedFuture
for {
// Each iteration, if there is anything in the list of futures,
// listen to it in addition to the file enumerating channel.
// A nil channel is never available to receive on, so if nothing
// is available, this will result in us exclusively selecting
// on the file enumerating channel.
var bf resolvedFuture
if len(futures) > 0 {
bf = futures[0]
} else if fs == nil {
// There are no more files to enumerate and the futures
// have been drained, so quit.
break
}
select {
case file, ok := <-fs:
if !ok {
// a nil channel is never available to receive on.
// This allows us to drain the list of in-process
// futures without this case of the select winning
// each time.
fs = nil
break
}
// Make a new future to use to ship the bytes back and append
// it to the list of futures (see comment below about ordering).
ch := make(resolvedFuture)
futures = append(futures, ch)
// Kick off the resolution that will respond with its bytes on
// the future.
f := file // defensive copy
errs.Go(func() error {
defer close(ch)
// Record the builds we do via this builder.
recordingBuilder := &build.Recorder{
Builder: builder,
}
b, err := resolveFile(ctx, f, recordingBuilder, publisher, so)
if err != nil {
// This error is sometimes expected during watch mode, so this
// isn't fatal. Just print it and keep the watch open.
return fmt.Errorf("error processing import paths in %q: %w", f, err)
}
// Associate with this file the collection of binary import paths.
sm.Store(f, recordingBuilder.ImportPaths)
ch <- b
return nil
})
case b, ok := <-bf:
// Once the head channel returns something, dequeue it.
// We listen to the futures in order to be respectful of
// the kubectl apply ordering, which matters!
futures = futures[1:]
if ok {
// Write the next body and a trailing delimiter.
// We write the delimeter LAST so that when streamed to
// kubectl it knows that the resource is complete and may
// be applied.
out.Write(append(b, []byte("\n---\n")...))
}
}
}
// Make sure we exit with an error.
// See https://github.com/google/ko/issues/84
return errs.Wait()
}
func resolveFile(
ctx context.Context,
f string,
builder build.Interface,
pub publish.Interface,
so *options.SelectorOptions) (b []byte, err error) {
var selector labels.Selector
if so.Selector != "" {
var err error
selector, err = labels.Parse(so.Selector)
if err != nil {
return nil, fmt.Errorf("unable to parse selector: %w", err)
}
}
if f == "-" {
b, err = ioutil.ReadAll(os.Stdin)
} else {
b, err = ioutil.ReadFile(f)
}
if err != nil {
return nil, err
}
var docNodes []*yaml.Node
// The loop is to support multi-document yaml files.
// This is handled by using a yaml.Decoder and reading objects until io.EOF, see:
// https://godoc.org/gopkg.in/yaml.v3#Decoder.Decode
decoder := yaml.NewDecoder(bytes.NewBuffer(b))
for {
var doc yaml.Node
if err := decoder.Decode(&doc); err != nil {
if errors.Is(err, io.EOF) {
break
}
return nil, err
}
if selector != nil {
if match, err := resolve.MatchesSelector(&doc, selector); err != nil {
return nil, fmt.Errorf("error evaluating selector: %w", err)
} else if !match {
continue
}
}
docNodes = append(docNodes, &doc)
}
if err := resolve.ImageReferences(ctx, docNodes, builder, pub); err != nil {
return nil, fmt.Errorf("error resolving image references: %w", err)
}
buf := &bytes.Buffer{}
e := yaml.NewEncoder(buf)
e.SetIndent(2)
for _, doc := range docNodes {
err := e.Encode(doc)
if err != nil {
return nil, fmt.Errorf("failed to encode output: %w", err)
}
}
e.Close()
return buf.Bytes(), nil
}