forked from chainguard-dev/melange
-
Notifications
You must be signed in to change notification settings - Fork 0
/
build.go
1302 lines (1086 loc) · 36.9 KB
/
build.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
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2022 Chainguard, Inc.
//
// 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 build
import (
"archive/tar"
"compress/gzip"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"io/fs"
"log/slog"
"os"
"path/filepath"
"runtime"
"slices"
"strconv"
"strings"
"time"
"chainguard.dev/apko/pkg/apk/apk"
apkofs "chainguard.dev/apko/pkg/apk/fs"
apko_build "chainguard.dev/apko/pkg/build"
apko_types "chainguard.dev/apko/pkg/build/types"
"chainguard.dev/apko/pkg/options"
"chainguard.dev/apko/pkg/sbom/generator/spdx"
"cloud.google.com/go/storage"
"github.com/chainguard-dev/clog"
purl "github.com/package-url/packageurl-go"
"github.com/yookoala/realpath"
"github.com/zealic/xignore"
"go.opentelemetry.io/otel"
"golang.org/x/exp/maps"
"google.golang.org/api/iterator"
"google.golang.org/api/option"
"k8s.io/kube-openapi/pkg/util/sets"
"sigs.k8s.io/release-utils/version"
"chainguard.dev/melange/pkg/config"
"chainguard.dev/melange/pkg/container"
"chainguard.dev/melange/pkg/index"
"chainguard.dev/melange/pkg/linter"
"chainguard.dev/melange/pkg/sbom"
)
const melangeOutputDirName = "melange-out"
var shellEmptyDir = []string{
"sh", "-c",
`d="$1";
[ $# -eq 1 ] || { echo "must provide dir. got $# args."; exit 1; }
cd "$d" || { echo "failed cd '$d'"; exit 1; }
set --
for e in * .*; do
[ "$e" = "." -o "$e" = ".." -o "$e" = "*" ] && continue
set -- "$@" "$e"
done
[ $# -gt 0 ] || { echo "nothing to cleanup. $d was empty."; exit 0; }
echo "cleaning Workspace by removing $# file/directories in $d"
rm -Rf "$@"`,
"shellEmptyDir",
}
var ErrSkipThisArch = errors.New("error: skip this arch")
type Build struct {
Configuration config.Configuration
// The name of the build configuration file, e.g. "crane.yaml".
ConfigFile string
// The URL of the git repository where the build configuration file is stored,
// e.g. "https://github.com/wolfi-dev/os".
ConfigFileRepositoryURL string
// The commit hash of the git repository corresponding to the current state of
// the build configuration file.
ConfigFileRepositoryCommit string
// The SPDX license string to use for the build configuration file.
ConfigFileLicense string
SourceDateEpoch time.Time
WorkspaceDir string
WorkspaceIgnore string
// Ordered directories where to find 'uses' pipelines.
PipelineDirs []string
SourceDir string
GuestDir string
SigningKey string
SigningPassphrase string
Namespace string
GenerateIndex bool
EmptyWorkspace bool
OutDir string
Arch apko_types.Architecture
Libc string
ExtraKeys []string
ExtraRepos []string
ExtraPackages []string
DependencyLog string
BinShOverlay string
CreateBuildLog bool
CacheDir string
ApkCacheDir string
CacheSource string
StripOriginName bool
EnvFile string
VarsFile string
Runner container.Runner
containerConfig *container.Config
Debug bool
DebugRunner bool
Interactive bool
Remove bool
LintRequire, LintWarn []string
DefaultCPU string
DefaultCPUModel string
DefaultDisk string
DefaultMemory string
DefaultTimeout time.Duration
Auth map[string]options.Auth
IgnoreSignatures bool
EnabledBuildOptions []string
// Initialized in New and mutated throughout the build process as we gain
// visibility into our packages' (including subpackages') composition. This is
// how we get "build-time" SBOMs!
SBOMGroup *SBOMGroup
}
func New(ctx context.Context, opts ...Option) (*Build, error) {
b := Build{
WorkspaceIgnore: ".melangeignore",
SourceDir: ".",
OutDir: ".",
CacheDir: "./melange-cache/",
Arch: apko_types.ParseArchitecture(runtime.GOARCH),
}
for _, opt := range opts {
if err := opt(&b); err != nil {
return nil, err
}
}
log := clog.New(slog.Default().Handler()).With("arch", b.Arch.ToAPK())
ctx = clog.WithLogger(ctx, log)
// If no workspace directory is explicitly requested, create a
// temporary directory for it. Otherwise, ensure we are in a
// subdir for this specific build context.
if b.WorkspaceDir != "" {
b.WorkspaceDir = filepath.Join(b.WorkspaceDir, b.Arch.ToAPK())
// Get the absolute path to the workspace dir, which is needed for bind
// mounts.
absdir, err := filepath.Abs(b.WorkspaceDir)
if err != nil {
return nil, fmt.Errorf("unable to resolve path %s: %w", b.WorkspaceDir, err)
}
b.WorkspaceDir = absdir
} else if b.Runner != nil {
tmpdir, err := os.MkdirTemp(b.Runner.TempDir(), "melange-workspace-*")
if err != nil {
return nil, fmt.Errorf("unable to create workspace dir: %w", err)
}
b.WorkspaceDir = tmpdir
}
// If no config file is explicitly requested for the build context
// we check if .melange.yaml or melange.yaml exist.
checks := []string{".melange.yaml", ".melange.yml", "melange.yaml", "melange.yml"}
if b.ConfigFile == "" {
for _, chk := range checks {
if _, err := os.Stat(chk); err == nil {
log.Infof("no configuration file provided -- using %s", chk)
b.ConfigFile = chk
break
}
}
}
// If no config file could be automatically detected, error.
if b.ConfigFile == "" {
return nil, fmt.Errorf("melange.yaml is missing")
}
if b.ConfigFileRepositoryURL == "" {
return nil, fmt.Errorf("config file repository URL was not set")
}
if b.ConfigFileRepositoryCommit == "" {
return nil, fmt.Errorf("config file repository commit was not set")
}
if b.Runner == nil {
return nil, fmt.Errorf("no runner was specified")
}
parsedCfg, err := config.ParseConfiguration(ctx,
b.ConfigFile,
config.WithEnvFileForParsing(b.EnvFile),
config.WithVarsFileForParsing(b.VarsFile),
config.WithDefaultCPU(b.DefaultCPU),
config.WithDefaultCPUModel(b.DefaultCPUModel),
config.WithDefaultDisk(b.DefaultDisk),
config.WithDefaultMemory(b.DefaultMemory),
config.WithDefaultTimeout(b.DefaultTimeout),
config.WithCommit(b.ConfigFileRepositoryCommit),
)
if err != nil {
return nil, fmt.Errorf("failed to load configuration: %w", err)
}
b.Configuration = *parsedCfg
// Now that we can find out the names of all the packages we'll be producing, we
// can start tracking SBOM data for each of them, using our SBOMGroup type.
b.SBOMGroup = NewSBOMGroup(slices.Collect(b.Configuration.AllPackageNames())...)
if len(b.Configuration.Package.TargetArchitecture) == 1 &&
b.Configuration.Package.TargetArchitecture[0] == "all" {
log.Warnf("target-architecture: ['all'] is deprecated and will become an error; remove this field to build for all available archs")
} else if len(b.Configuration.Package.TargetArchitecture) != 0 &&
!sets.NewString(b.Configuration.Package.TargetArchitecture...).Has(b.Arch.ToAPK()) {
return nil, ErrSkipThisArch
}
// SOURCE_DATE_EPOCH will always overwrite the build flag
if _, ok := os.LookupEnv("SOURCE_DATE_EPOCH"); ok {
t, err := sourceDateEpoch(b.SourceDateEpoch)
if err != nil {
return nil, err
}
b.SourceDateEpoch = t
}
b.SBOMGroup.SetCreatedTime(b.SourceDateEpoch)
// Check that we actually can run things in containers.
if b.Runner != nil && !b.Runner.TestUsability(ctx) {
return nil, fmt.Errorf("unable to run containers using %s, specify --runner and one of %s", b.Runner.Name(), GetAllRunners())
}
// Apply build options to the context.
for _, optName := range b.EnabledBuildOptions {
log.Infof("applying configuration patches for build option %s", optName)
if opt, ok := b.Configuration.Options[optName]; ok {
if err := b.applyBuildOption(opt); err != nil {
return nil, err
}
}
}
return &b, nil
}
func (b *Build) Close(ctx context.Context) error {
log := clog.FromContext(ctx)
errs := []error{}
if b.Remove {
log.Infof("deleting guest dir %s", b.GuestDir)
errs = append(errs, os.RemoveAll(b.GuestDir))
log.Infof("deleting workspace dir %s", b.WorkspaceDir)
errs = append(errs, os.RemoveAll(b.WorkspaceDir))
if b.containerConfig != nil && b.containerConfig.ImgRef != "" {
errs = append(errs, b.Runner.OCIImageLoader().RemoveImage(context.WithoutCancel(ctx), b.containerConfig.ImgRef))
}
}
if b.Runner != nil {
errs = append(errs, b.Runner.Close())
}
return errors.Join(errs...)
}
// buildGuest invokes apko to build the guest environment, returning a reference to the image
// loaded by the OCI Image loader.
//
// NB: This has side effects! This mutates Build by overwriting Configuration.Environment with
// a locked version (packages resolved to versions) so we can record which packages were used.
func (b *Build) buildGuest(ctx context.Context, imgConfig apko_types.ImageConfiguration, guestFS apkofs.FullFS) (string, error) {
log := clog.FromContext(ctx)
ctx, span := otel.Tracer("melange").Start(ctx, "buildGuest")
defer span.End()
tmp, err := os.MkdirTemp(os.TempDir(), "apko-temp-*")
if err != nil {
return "", fmt.Errorf("creating apko tempdir: %w", err)
}
defer os.RemoveAll(tmp)
if b.Runner.Name() == container.QemuName {
b.ExtraPackages = append(b.ExtraPackages, []string{
"melange-microvm-init",
}...)
}
// Work around LockImageConfiguration assuming multi-arch.
imgConfig.Archs = []apko_types.Architecture{b.Arch}
opts := []apko_build.Option{apko_build.WithImageConfiguration(imgConfig),
apko_build.WithArch(b.Arch),
apko_build.WithExtraKeys(b.ExtraKeys),
apko_build.WithExtraBuildRepos(b.ExtraRepos),
apko_build.WithExtraPackages(b.ExtraPackages),
apko_build.WithCache(b.ApkCacheDir, false, apk.NewCache(true)),
apko_build.WithTempDir(tmp),
apko_build.WithIgnoreSignatures(b.IgnoreSignatures),
}
locked, warn, err := apko_build.LockImageConfiguration(ctx, imgConfig, opts...)
if err != nil {
return "", fmt.Errorf("unable to lock image configuration: %w", err)
}
for k, v := range warn {
log.Warnf("Unable to lock package %s: %s", k, v)
}
// Overwrite the environment with the locked one.
b.Configuration.Environment = *locked
opts = append(opts, apko_build.WithImageConfiguration(*locked))
bc, err := apko_build.New(ctx, guestFS, opts...)
if err != nil {
return "", fmt.Errorf("unable to create build context: %w", err)
}
bc.Summarize(ctx)
log.Infof("auth configured for: %s", maps.Keys(b.Auth)) // TODO: add this to summarize
// lay out the contents for the image in a directory.
if err := bc.BuildImage(ctx); err != nil {
return "", fmt.Errorf("unable to generate image: %w", err)
}
// if the runner needs an image, create an OCI image from the directory and load it.
loader := b.Runner.OCIImageLoader()
if loader == nil {
return "", fmt.Errorf("runner %s does not support OCI image loading", b.Runner.Name())
}
layerTarGZ, layer, err := bc.ImageLayoutToLayer(ctx)
if err != nil {
return "", err
}
defer os.Remove(layerTarGZ)
log.Infof("using %s for image layer", layerTarGZ)
ref, err := loader.LoadImage(ctx, layer, b.Arch, bc)
if err != nil {
return "", err
}
log.Debugf("pushed %s as %v", layerTarGZ, ref)
log.Debug("successfully built workspace with apko")
return ref, nil
}
func copyFile(base, src, dest string, perm fs.FileMode) error {
basePath := filepath.Join(base, src)
destPath := filepath.Join(dest, src)
destDir := filepath.Dir(destPath)
inF, err := os.Open(basePath)
if err != nil {
return err
}
defer inF.Close()
if err := os.MkdirAll(destDir, 0o755); err != nil {
return fmt.Errorf("mkdir -p %s: %w", destDir, err)
}
outF, err := os.Create(destPath)
if err != nil {
return fmt.Errorf("create %s: %w", destPath, err)
}
defer outF.Close()
if _, err := io.Copy(outF, inF); err != nil {
return err
}
if err := os.Chmod(destPath, perm); err != nil {
return err
}
return nil
}
// applyBuildOption applies a patch described by a BuildOption to a package build.
func (b *Build) applyBuildOption(bo config.BuildOption) error {
// Patch the variables block.
if b.Configuration.Vars == nil {
b.Configuration.Vars = make(map[string]string)
}
for k, v := range bo.Vars {
b.Configuration.Vars[k] = v
}
// Patch the build environment configuration.
lo := bo.Environment.Contents.Packages
b.Configuration.Environment.Contents.Packages = append(b.Configuration.Environment.Contents.Packages, lo.Add...)
for _, pkg := range lo.Remove {
pkgList := b.Configuration.Environment.Contents.Packages
for pos, ppkg := range pkgList {
if pkg == ppkg {
pkgList[pos] = pkgList[len(pkgList)-1]
pkgList = pkgList[:len(pkgList)-1]
}
}
b.Configuration.Environment.Contents.Packages = pkgList
}
return nil
}
func (b *Build) loadIgnoreRules(ctx context.Context) ([]*xignore.Pattern, error) {
log := clog.FromContext(ctx)
ignorePath := filepath.Join(b.SourceDir, b.WorkspaceIgnore)
ignorePatterns := []*xignore.Pattern{}
if _, err := os.Stat(ignorePath); err != nil {
if errors.Is(err, os.ErrNotExist) {
return ignorePatterns, nil
}
return nil, err
}
log.Infof("loading ignore rules from %s", ignorePath)
inF, err := os.Open(ignorePath)
if err != nil {
return nil, err
}
defer inF.Close()
ignF := xignore.Ignorefile{}
if err := ignF.FromReader(inF); err != nil {
return nil, err
}
for _, rule := range ignF.Patterns {
pattern := xignore.NewPattern(rule)
if err := pattern.Prepare(); err != nil {
return nil, err
}
ignorePatterns = append(ignorePatterns, pattern)
}
return ignorePatterns, nil
}
func (b *Build) overlayBinSh() error {
if b.BinShOverlay == "" {
return nil
}
targetPath := filepath.Join(b.GuestDir, "bin", "sh")
inF, err := os.Open(b.BinShOverlay)
if err != nil {
return fmt.Errorf("copying overlay /bin/sh: %w", err)
}
defer inF.Close()
// We unlink the target first because it might be a symlink.
if err := os.Remove(targetPath); err != nil {
return fmt.Errorf("copying overlay /bin/sh: %w", err)
}
outF, err := os.Create(targetPath)
if err != nil {
return fmt.Errorf("copying overlay /bin/sh: %w", err)
}
defer outF.Close()
if _, err := io.Copy(outF, inF); err != nil {
return fmt.Errorf("copying overlay /bin/sh: %w", err)
}
if err := os.Chmod(targetPath, 0o755); err != nil {
return fmt.Errorf("setting overlay /bin/sh executable: %w", err)
}
return nil
}
func fetchBucket(ctx context.Context, cacheSource string, cmm CacheMembershipMap) (string, error) {
log := clog.FromContext(ctx)
tmp, err := os.MkdirTemp("", "melange-cache")
if err != nil {
return "", err
}
bucket, prefix, _ := strings.Cut(strings.TrimPrefix(cacheSource, "gs://"), "/")
client, err := storage.NewClient(ctx)
if err != nil {
log.Infof("downgrading to anonymous mode: %s", err)
client, err = storage.NewClient(ctx, option.WithoutAuthentication())
if err != nil {
return "", fmt.Errorf("failed to get storage client: %w", err)
}
}
bh := client.Bucket(bucket)
it := bh.Objects(ctx, &storage.Query{Prefix: prefix})
for {
attrs, err := it.Next()
if err == iterator.Done {
break
} else if err != nil {
return tmp, fmt.Errorf("failed to get next remote cache object: %w", err)
}
on := attrs.Name
if !cmm[on] {
continue
}
rc, err := bh.Object(on).NewReader(ctx)
if err != nil {
return tmp, fmt.Errorf("failed to get reader for next remote cache object %s: %w", on, err)
}
w, err := os.Create(filepath.Join(tmp, on))
if err != nil {
return tmp, err
}
if _, err := io.Copy(w, rc); err != nil {
return tmp, fmt.Errorf("failed to copy remote cache object %s: %w", on, err)
}
if err := rc.Close(); err != nil {
return tmp, fmt.Errorf("failed to close remote cache object %s: %w", on, err)
}
log.Infof("cached gs://%s/%s -> %s", bucket, on, w.Name())
}
return tmp, nil
}
// isBuildLess returns true if the build context does not actually do any building.
// TODO(kaniini): Improve the heuristic for this by checking for uses/runs statements
// in the pipeline.
func (b *Build) isBuildLess() bool {
return len(b.Configuration.Pipeline) == 0
}
// getBuildConfigPURL determines the package URL for the melange config file
// itself.
func (b Build) getBuildConfigPURL() (*purl.PackageURL, error) {
namespace, name, found := strings.Cut(strings.TrimPrefix(b.ConfigFileRepositoryURL, "https://github.com/"), "/")
if !found {
return nil, fmt.Errorf("extracting namespace and name from %s", b.ConfigFileRepositoryURL)
}
u := &purl.PackageURL{
Type: purl.TypeGithub,
Namespace: namespace,
Name: name,
Version: b.ConfigFileRepositoryCommit,
Subpath: b.ConfigFile,
}
if err := u.Normalize(); err != nil {
return nil, fmt.Errorf("normalizing PURL: %w", err)
}
return u, nil
}
func (b *Build) populateCache(ctx context.Context) error {
log := clog.FromContext(ctx)
ctx, span := otel.Tracer("melange").Start(ctx, "populateCache")
defer span.End()
if b.CacheDir == "" {
return nil
}
cmm, err := cacheItemsForBuild(b.ConfigFile)
if err != nil {
return fmt.Errorf("while determining which objects to fetch: %w", err)
}
if b.CacheSource != "" {
log.Debugf("populating cache from %s", b.CacheSource)
}
// --cache-dir=gs://bucket/path/to/cache first pulls all found objects to a
// tmp dir which is subsequently used as the cache.
if strings.HasPrefix(b.CacheSource, "gs://") {
tmp, err := fetchBucket(ctx, b.CacheSource, cmm)
if err != nil {
return err
}
defer os.RemoveAll(tmp)
log.Infof("cache bucket copied to %s", tmp)
fsys := os.DirFS(tmp)
// mkdir /var/cache/melange
if err := os.MkdirAll(b.CacheDir, 0o755); err != nil {
return err
}
// --cache-dir doesn't exist, nothing to do.
if _, err := fs.Stat(fsys, "."); errors.Is(err, fs.ErrNotExist) {
return nil
}
return fs.WalkDir(fsys, ".", func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
fi, err := d.Info()
if err != nil {
return err
}
mode := fi.Mode()
if !mode.IsRegular() {
return nil
}
// Skip files in the cache that aren't named like sha256:... or sha512:...
// This is likely a bug, and won't be matched by any fetch.
base := filepath.Base(fi.Name())
if !strings.HasPrefix(base, "sha256:") &&
!strings.HasPrefix(base, "sha512:") {
return nil
}
log.Debugf(" -> %s", path)
if err := copyFile(tmp, path, b.CacheDir, mode.Perm()); err != nil {
return err
}
return nil
})
}
return nil
}
func (b *Build) populateWorkspace(ctx context.Context, src fs.FS) error {
log := clog.FromContext(ctx)
_, span := otel.Tracer("melange").Start(ctx, "populateWorkspace")
defer span.End()
ignorePatterns, err := b.loadIgnoreRules(ctx)
if err != nil {
return err
}
return fs.WalkDir(src, ".", func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
fi, err := d.Info()
if err != nil {
return err
}
mode := fi.Mode()
if !mode.IsRegular() {
return nil
}
for _, pat := range ignorePatterns {
if pat.Match(path) {
return nil
}
}
log.Debugf(" -> %s", path)
if err := copyFile(b.SourceDir, path, b.WorkspaceDir, mode.Perm()); err != nil {
return err
}
return nil
})
}
type linterTarget struct {
pkgName string
disabled []string // checks that are downgraded from required -> warn
}
func (b *Build) BuildPackage(ctx context.Context) error {
log := clog.FromContext(ctx)
ctx, span := otel.Tracer("melange").Start(ctx, "BuildPackage")
defer span.End()
b.summarize(ctx)
namespace := b.Namespace
if namespace == "" {
namespace = "unknown"
}
if to := b.Configuration.Package.Timeout; to > 0 {
tctx, cancel := context.WithTimeoutCause(ctx, to,
fmt.Errorf("build exceeded its timeout of %s", to))
defer cancel()
ctx = tctx
}
pkg := &b.Configuration.Package
arch := b.Arch.ToAPK()
// Add the APK package(s) to their respective SBOMs. We do this early in the
// build process so that we can later add more kinds of packages that relate to
// these packages, as we learn more during the build.
for _, sp := range b.Configuration.Subpackages {
sp := sp
spSBOM := b.SBOMGroup.Document(sp.Name)
apkSubPkg := &sbom.Package{
Name: sp.Name,
Version: pkg.FullVersion(),
Copyright: pkg.FullCopyright(),
LicenseDeclared: pkg.LicenseExpression(),
Namespace: namespace,
Arch: arch,
PURL: pkg.PackageURLForSubpackage(namespace, arch, sp.Name),
}
spSBOM.AddPackageAndSetDescribed(apkSubPkg)
}
pSBOM := b.SBOMGroup.Document(pkg.Name)
apkPkg := &sbom.Package{
Name: pkg.Name,
Version: pkg.FullVersion(),
Copyright: pkg.FullCopyright(),
LicenseDeclared: pkg.LicenseExpression(),
Namespace: namespace,
Arch: arch,
PURL: pkg.PackageURL(namespace, arch),
}
pSBOM.AddPackageAndSetDescribed(apkPkg)
if b.GuestDir == "" {
guestDir, err := os.MkdirTemp(b.Runner.TempDir(), "melange-guest-*")
if err != nil {
return fmt.Errorf("unable to make guest directory: %w", err)
}
b.GuestDir = guestDir
if b.Remove {
defer os.RemoveAll(guestDir)
}
}
log.Infof("evaluating pipelines for package requirements")
if err := b.Compile(ctx); err != nil {
return fmt.Errorf("compiling build: %w", err)
}
// Filter out any subpackages with false If conditions.
b.Configuration.Subpackages = slices.DeleteFunc(b.Configuration.Subpackages, func(sp config.Subpackage) bool {
result, err := shouldRun(sp.If)
if err != nil {
// This shouldn't give an error because we evaluate it in Compile.
panic(err)
}
if !result {
log.Infof("skipping subpackage %s because %s == false", sp.Name, sp.If)
}
return !result
})
if err := b.addSBOMPackageForBuildConfigFile(); err != nil {
return fmt.Errorf("adding SBOM package for build config file: %w", err)
}
pr := &pipelineRunner{
interactive: b.Interactive,
debug: b.Debug,
config: b.workspaceConfig(ctx),
runner: b.Runner,
}
if b.EmptyWorkspace {
log.Infof("empty workspace requested")
} else {
// Prepare workspace directory
if err := os.MkdirAll(b.WorkspaceDir, 0o755); err != nil {
return fmt.Errorf("mkdir -p %s: %w", b.WorkspaceDir, err)
}
log.Infof("populating workspace %s from %s", b.WorkspaceDir, b.SourceDir)
if err := b.populateWorkspace(ctx, os.DirFS(b.SourceDir)); err != nil {
return fmt.Errorf("unable to populate workspace: %w", err)
}
}
if err := os.MkdirAll(filepath.Join(b.WorkspaceDir, melangeOutputDirName, b.Configuration.Package.Name), 0o755); err != nil {
return err
}
linterQueue := []linterTarget{}
cfg := b.workspaceConfig(ctx)
if !b.isBuildLess() {
// Prepare guest directory
if err := os.MkdirAll(b.GuestDir, 0o755); err != nil {
return fmt.Errorf("mkdir -p %s: %w", b.GuestDir, err)
}
log.Infof("building workspace in '%s' with apko", b.GuestDir)
guestFS := apkofs.DirFS(b.GuestDir, apkofs.WithCreateDir())
imgRef, err := b.buildGuest(ctx, b.Configuration.Environment, guestFS)
if err != nil {
return fmt.Errorf("unable to build guest: %w", err)
}
cfg.ImgRef = imgRef
log.Infof("ImgRef = %s", cfg.ImgRef)
// TODO(kaniini): Make overlay-binsh work with Docker and Kubernetes.
// Probably needs help from apko.
if err := b.overlayBinSh(); err != nil {
return fmt.Errorf("unable to install overlay /bin/sh: %w", err)
}
if err := b.populateCache(ctx); err != nil {
return fmt.Errorf("unable to populate cache: %w", err)
}
if err := b.Runner.StartPod(ctx, cfg); err != nil {
return fmt.Errorf("unable to start pod: %w", err)
}
if !b.DebugRunner {
defer func() {
if err := b.Runner.TerminatePod(context.WithoutCancel(ctx), cfg); err != nil {
log.Warnf("unable to terminate pod: %s", err)
}
}()
}
// run the main pipeline
log.Debug("running the main pipeline")
pipelines := b.Configuration.Pipeline
if err := pr.runPipelines(ctx, pipelines); err != nil {
return fmt.Errorf("unable to run package %s pipeline: %w", b.Configuration.Name(), err)
}
for i, p := range pipelines {
uniqueID := strconv.Itoa(i)
pkg, err := p.SBOMPackageForUpstreamSource(b.Configuration.Package.LicenseExpression(), namespace, uniqueID)
if err != nil {
return fmt.Errorf("creating SBOM package for upstream source: %w", err)
}
if pkg == nil {
// This particular pipeline step doesn't tell us about the upstream source code.
continue
}
b.SBOMGroup.AddUpstreamSourcePackage(pkg)
}
// add the main package to the linter queue
lintTarget := linterTarget{
pkgName: b.Configuration.Package.Name,
disabled: b.Configuration.Package.Checks.Disabled,
}
linterQueue = append(linterQueue, lintTarget)
}
// run any pipelines for subpackages
for _, sp := range b.Configuration.Subpackages {
sp := sp
if err := os.MkdirAll(filepath.Join(b.WorkspaceDir, melangeOutputDirName, sp.Name), 0o755); err != nil {
return err
}
if !b.isBuildLess() {
log.Infof("running pipeline for subpackage %s", sp.Name)
ctx := clog.WithLogger(ctx, log.With("subpackage", sp.Name))
if err := pr.runPipelines(ctx, sp.Pipeline); err != nil {
return fmt.Errorf("unable to run subpackage %s pipeline: %w", sp.Name, err)
}
}
// add the main package to the linter queue
lintTarget := linterTarget{
pkgName: sp.Name,
disabled: sp.Checks.Disabled,
}
linterQueue = append(linterQueue, lintTarget)
}
// Retrieve the post build workspace from the runner
log.Infof("retrieving workspace from builder: %s", cfg.PodID)
fsys := apkofs.DirFS(b.WorkspaceDir)
if err := b.retrieveWorkspace(ctx, fsys); err != nil {
return fmt.Errorf("retrieving workspace: %w", err)
}
log.Infof("retrieved and wrote post-build workspace to: %s", b.WorkspaceDir)
// perform package linting
for _, lt := range linterQueue {
log.Infof("running package linters for %s", lt.pkgName)
path := filepath.Join(b.WorkspaceDir, melangeOutputDirName, lt.pkgName)
// Downgrade disabled checks from required to warn
require := slices.DeleteFunc(b.LintRequire, func(s string) bool {
return slices.Contains(lt.disabled, s)
})
warn := slices.CompactFunc(append(b.LintWarn, lt.disabled...), func(a, b string) bool {
return a == b
})
if err := linter.LintBuild(ctx, lt.pkgName, path, require, warn); err != nil {
return fmt.Errorf("unable to lint package %s: %w", lt.pkgName, err)
}
}
li, err := b.Configuration.Package.LicensingInfos(b.WorkspaceDir)
if err != nil {
return fmt.Errorf("gathering licensing infos: %w", err)
}
b.SBOMGroup.SetLicensingInfos(li)
// Convert the SBOMs we've been working on to their SPDX representation, and
// write them to disk. We'll handle any subpackages first, and then the main
// package, but the order doesn't really matter.
for _, sp := range b.Configuration.Subpackages {
spSBOM := b.SBOMGroup.Document(sp.Name)
spdxDoc := spSBOM.ToSPDX(ctx)
log.Infof("writing SBOM for subpackage %s", sp.Name)
if err := b.writeSBOM(sp.Name, &spdxDoc); err != nil {
return fmt.Errorf("writing SBOM for %s: %w", sp.Name, err)
}
}
spdxDoc := pSBOM.ToSPDX(ctx)
log.Infof("writing SBOM for %s", pkg.Name)
if err := b.writeSBOM(pkg.Name, &spdxDoc); err != nil {
return fmt.Errorf("writing SBOM for %s: %w", pkg.Name, err)
}
// emit main package
if err := b.Emit(ctx, pkg); err != nil {
return fmt.Errorf("unable to emit package: %w", err)
}
// emit subpackages
for _, sp := range b.Configuration.Subpackages {
sp := sp
if err := b.Emit(ctx, pkgFromSub(&sp)); err != nil {
return fmt.Errorf("unable to emit package: %w", err)
}
}
// clean build environment
log.Debugf("cleaning workspacedir")
cleanEnv := map[string]string{}
if err := pr.runner.Run(ctx, pr.config, cleanEnv, append(shellEmptyDir, WorkDir)...); err != nil {
log.Warnf("unable to clean workspace: %s", err)
}
// if the Runner used WorkspaceDir as WorkDir, then this will be empty already.
if err := os.RemoveAll(b.WorkspaceDir); err != nil {
log.Warnf("unable to clean workspace: %s", err)
}
if !b.isBuildLess() {