-
Notifications
You must be signed in to change notification settings - Fork 3.1k
Expand file tree
/
Copy pathbuild.go
More file actions
1263 lines (1134 loc) · 39.3 KB
/
build.go
File metadata and controls
1263 lines (1134 loc) · 39.3 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
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
package images
import (
"archive/tar"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"io/fs"
"mime/multipart"
"net/http"
"net/url"
"os"
"path/filepath"
"runtime"
"strconv"
"strings"
"github.com/blang/semver/v4"
"github.com/containers/buildah/define"
"github.com/containers/podman/v5/internal/remote_build_helpers"
ldefine "github.com/containers/podman/v5/libpod/define"
"github.com/containers/podman/v5/pkg/auth"
"github.com/containers/podman/v5/pkg/bindings"
"github.com/containers/podman/v5/pkg/domain/entities/types"
"github.com/containers/podman/v5/pkg/specgen"
"github.com/containers/podman/v5/pkg/util"
"github.com/docker/docker/pkg/jsonmessage"
"github.com/docker/go-units"
"github.com/hashicorp/go-multierror"
jsoniter "github.com/json-iterator/go"
gzip "github.com/klauspost/pgzip"
"github.com/sirupsen/logrus"
imageTypes "go.podman.io/image/v5/types"
"go.podman.io/storage/pkg/archive"
"go.podman.io/storage/pkg/fileutils"
"go.podman.io/storage/pkg/ioutils"
"go.podman.io/storage/pkg/regexp"
)
type devino struct {
Dev uint64
Ino uint64
}
var iidRegex = regexp.Delayed(`^[0-9a-f]{12}`)
type BuildResponse struct {
Stream string `json:"stream,omitempty"`
Error *jsonmessage.JSONError `json:"errorDetail,omitempty"`
// NOTE: `error` is being deprecated check https://github.com/moby/moby/blob/master/pkg/jsonmessage/jsonmessage.go#L148
ErrorMessage string `json:"error,omitempty"` // deprecate this slowly
Aux json.RawMessage `json:"aux,omitempty"`
}
// BuildFilePaths contains the file paths and exclusion patterns for the build context.
type BuildFilePaths struct {
tarContent []string
newContainerFiles []string // dockerfile paths, relative to context dir, ToSlash()ed
dontexcludes []string
excludes []string
}
// RequestParts contains the components of an HTTP request for the build API.
type RequestParts struct {
Headers http.Header
Params url.Values
Body io.ReadCloser
}
// Modify the build contexts that uses a local windows path. The windows path is
// converted into the corresping guest path in the default Windows machine
// (e.g. C:\test ==> /mnt/c/test).
func convertAdditionalBuildContexts(additionalBuildContexts map[string]*define.AdditionalBuildContext) {
for _, context := range additionalBuildContexts {
if !context.IsImage && !context.IsURL {
path, err := specgen.ConvertWinMountPath(context.Value)
// It's not worth failing if the path can't be converted
if err == nil {
context.Value = path
}
}
}
}
// convertVolumeSrcPath converts windows paths in the HOST-DIR part of a volume
// into the corresponding path in the default Windows machine.
// (e.g. C:\test:/src/docs ==> /mnt/c/test:/src/docs).
// If any error occurs while parsing the volume string, the original volume
// string is returned.
func convertVolumeSrcPath(volume string) string {
splitVol := specgen.SplitVolumeString(volume)
if len(splitVol) < 2 || len(splitVol) > 3 {
return volume
}
convertedSrcPath, err := specgen.ConvertWinMountPath(splitVol[0])
if err != nil {
return volume
}
if len(splitVol) == 2 {
return convertedSrcPath + ":" + splitVol[1]
} else {
return convertedSrcPath + ":" + splitVol[1] + ":" + splitVol[2]
}
}
// isSupportedVersion checks if the server version is greater than or equal to the specified minimum version.
// It extracts version numbers from the server version string, removing any suffixes like -dev or -rc,
// and compares them using semantic versioning.
func isSupportedVersion(ctx context.Context, minVersion string) (bool, error) {
serverVersion := bindings.ServiceVersion(ctx)
// Extract just the version numbers (remove -dev, -rc, etc)
versionStr := serverVersion.String()
if idx := strings.Index(versionStr, "-"); idx > 0 {
versionStr = versionStr[:idx]
}
serverVer, err := semver.ParseTolerant(versionStr)
if err != nil {
return false, fmt.Errorf("parsing server version %q: %w", serverVersion, err)
}
minMultipartVersion, _ := semver.ParseTolerant(minVersion)
return serverVer.GTE(minMultipartVersion), nil
}
// prepareParams converts BuildOptions into URL parameters for the build API request.
// It handles various build options including capabilities, annotations, CPU settings,
// devices, labels, platforms, volumes, and other build configuration parameters.
func prepareParams(options types.BuildOptions) (url.Values, error) {
params := url.Values{}
if caps := options.AddCapabilities; len(caps) > 0 {
c, err := jsoniter.MarshalToString(caps)
if err != nil {
return nil, err
}
params.Add("addcaps", c)
}
if annotations := options.Annotations; len(annotations) > 0 {
l, err := jsoniter.MarshalToString(annotations)
if err != nil {
return nil, err
}
params.Set("annotations", l)
}
if cppflags := options.CPPFlags; len(cppflags) > 0 {
l, err := jsoniter.MarshalToString(cppflags)
if err != nil {
return nil, err
}
params.Set("cppflags", l)
}
if options.AllPlatforms {
params.Add("allplatforms", "1")
}
params.Add("t", options.Output)
for _, tag := range options.AdditionalTags {
params.Add("t", tag)
}
if options.IDMappingOptions != nil {
idmappingsOptions, err := jsoniter.Marshal(options.IDMappingOptions)
if err != nil {
return nil, err
}
params.Set("idmappingoptions", string(idmappingsOptions))
}
if buildArgs := options.Args; len(buildArgs) > 0 {
bArgs, err := jsoniter.MarshalToString(buildArgs)
if err != nil {
return nil, err
}
params.Set("buildargs", bArgs)
}
if excludes := options.Excludes; len(excludes) > 0 {
bArgs, err := jsoniter.MarshalToString(excludes)
if err != nil {
return nil, err
}
params.Set("excludes", bArgs)
}
if cpuPeriod := options.CommonBuildOpts.CPUPeriod; cpuPeriod > 0 {
params.Set("cpuperiod", strconv.Itoa(int(cpuPeriod)))
}
if cpuQuota := options.CommonBuildOpts.CPUQuota; cpuQuota > 0 {
params.Set("cpuquota", strconv.Itoa(int(cpuQuota)))
}
if cpuSetCpus := options.CommonBuildOpts.CPUSetCPUs; len(cpuSetCpus) > 0 {
params.Set("cpusetcpus", cpuSetCpus)
}
if cpuSetMems := options.CommonBuildOpts.CPUSetMems; len(cpuSetMems) > 0 {
params.Set("cpusetmems", cpuSetMems)
}
if cpuShares := options.CommonBuildOpts.CPUShares; cpuShares > 0 {
params.Set("cpushares", strconv.Itoa(int(cpuShares)))
}
if len(options.CommonBuildOpts.CgroupParent) > 0 {
params.Set("cgroupparent", options.CommonBuildOpts.CgroupParent)
}
params.Set("networkmode", strconv.Itoa(int(options.ConfigureNetwork)))
params.Set("outputformat", options.OutputFormat)
if devices := options.Devices; len(devices) > 0 {
d, err := jsoniter.MarshalToString(devices)
if err != nil {
return nil, err
}
params.Add("devices", d)
}
if dnsservers := options.CommonBuildOpts.DNSServers; len(dnsservers) > 0 {
c, err := jsoniter.MarshalToString(dnsservers)
if err != nil {
return nil, err
}
params.Add("dnsservers", c)
}
if dnsoptions := options.CommonBuildOpts.DNSOptions; len(dnsoptions) > 0 {
c, err := jsoniter.MarshalToString(dnsoptions)
if err != nil {
return nil, err
}
params.Add("dnsoptions", c)
}
if dnssearch := options.CommonBuildOpts.DNSSearch; len(dnssearch) > 0 {
c, err := jsoniter.MarshalToString(dnssearch)
if err != nil {
return nil, err
}
params.Add("dnssearch", c)
}
if caps := options.DropCapabilities; len(caps) > 0 {
c, err := jsoniter.MarshalToString(caps)
if err != nil {
return nil, err
}
params.Add("dropcaps", c)
}
if options.ForceRmIntermediateCtrs {
params.Set("forcerm", "1")
}
if options.RemoveIntermediateCtrs {
params.Set("rm", "1")
} else {
params.Set("rm", "0")
}
if options.CommonBuildOpts.OmitHistory {
params.Set("omithistory", "1")
} else {
params.Set("omithistory", "0")
}
if len(options.From) > 0 {
params.Set("from", options.From)
}
if options.IgnoreUnrecognizedInstructions {
params.Set("ignore", "1")
}
switch options.CreatedAnnotation {
case imageTypes.OptionalBoolFalse:
params.Set("createdannotation", "0")
case imageTypes.OptionalBoolTrue:
params.Set("createdannotation", "1")
}
switch options.InheritLabels {
case imageTypes.OptionalBoolFalse:
params.Set("inheritlabels", "0")
case imageTypes.OptionalBoolTrue:
params.Set("inheritlabels", "1")
}
if options.InheritAnnotations == imageTypes.OptionalBoolFalse {
params.Set("inheritannotations", "0")
} else {
params.Set("inheritannotations", "1")
}
params.Set("isolation", strconv.Itoa(int(options.Isolation)))
if options.CommonBuildOpts.HTTPProxy {
params.Set("httpproxy", "1")
}
if options.Jobs != nil {
params.Set("jobs", strconv.FormatUint(uint64(*options.Jobs), 10))
}
if labels := options.Labels; len(labels) > 0 {
l, err := jsoniter.MarshalToString(labels)
if err != nil {
return nil, err
}
params.Set("labels", l)
}
if opt := options.CommonBuildOpts.LabelOpts; len(opt) > 0 {
o, err := jsoniter.MarshalToString(opt)
if err != nil {
return nil, err
}
params.Set("labelopts", o)
}
if len(options.CommonBuildOpts.SeccompProfilePath) > 0 {
params.Set("seccomp", options.CommonBuildOpts.SeccompProfilePath)
}
if len(options.CommonBuildOpts.ApparmorProfile) > 0 {
params.Set("apparmor", options.CommonBuildOpts.ApparmorProfile)
}
for _, layerLabel := range options.LayerLabels {
params.Add("layerLabel", layerLabel)
}
if options.Layers {
params.Set("layers", "1")
}
if options.LogRusage {
params.Set("rusage", "1")
}
if len(options.RusageLogFile) > 0 {
params.Set("rusagelogfile", options.RusageLogFile)
}
params.Set("retry", strconv.Itoa(options.MaxPullPushRetries))
params.Set("retry-delay", options.PullPushRetryDelay.String())
if len(options.Manifest) > 0 {
params.Set("manifest", options.Manifest)
}
if options.CacheFrom != nil {
cacheFrom := []string{}
for _, cacheSrc := range options.CacheFrom {
cacheFrom = append(cacheFrom, cacheSrc.String())
}
cacheFromJSON, err := jsoniter.MarshalToString(cacheFrom)
if err != nil {
return nil, err
}
params.Set("cachefrom", cacheFromJSON)
}
switch options.SkipUnusedStages {
case imageTypes.OptionalBoolTrue:
params.Set("skipunusedstages", "1")
case imageTypes.OptionalBoolFalse:
params.Set("skipunusedstages", "0")
}
if options.CacheTo != nil {
cacheTo := []string{}
for _, cacheSrc := range options.CacheTo {
cacheTo = append(cacheTo, cacheSrc.String())
}
cacheToJSON, err := jsoniter.MarshalToString(cacheTo)
if err != nil {
return nil, err
}
params.Set("cacheto", cacheToJSON)
}
if int64(options.CacheTTL) != 0 {
params.Set("cachettl", options.CacheTTL.String())
}
if memSwap := options.CommonBuildOpts.MemorySwap; memSwap > 0 {
params.Set("memswap", strconv.Itoa(int(memSwap)))
}
if mem := options.CommonBuildOpts.Memory; mem > 0 {
params.Set("memory", strconv.Itoa(int(mem)))
}
switch options.CompatVolumes {
case imageTypes.OptionalBoolTrue:
params.Set("compatvolumes", "1")
case imageTypes.OptionalBoolFalse:
params.Set("compatvolumes", "0")
}
if options.NoCache {
params.Set("nocache", "1")
}
if options.CommonBuildOpts.NoHosts {
params.Set("nohosts", "1")
}
if t := options.Output; len(t) > 0 {
params.Set("output", t)
}
if t := options.OSVersion; len(t) > 0 {
params.Set("osversion", t)
}
for _, t := range options.OSFeatures {
params.Set("osfeature", t)
}
var platform string
if len(options.OS) > 0 {
platform = options.OS
}
if len(options.Architecture) > 0 {
if len(platform) == 0 {
platform = "linux"
}
platform += "/" + options.Architecture
} else if len(platform) > 0 {
platform += "/" + runtime.GOARCH
}
if len(platform) > 0 {
params.Set("platform", platform)
}
if len(options.Platforms) > 0 {
params.Del("platform")
for _, platformSpec := range options.Platforms {
// podman-cli will send empty struct, in such
// case don't add platform to param and let the
// build backend decide the default platform.
if platformSpec.OS == "" && platformSpec.Arch == "" && platformSpec.Variant == "" {
continue
}
platform = platformSpec.OS + "/" + platformSpec.Arch
if platformSpec.Variant != "" {
platform += "/" + platformSpec.Variant
}
params.Add("platform", platform)
}
}
for _, volume := range options.CommonBuildOpts.Volumes {
params.Add("volume", convertVolumeSrcPath(volume))
}
for _, group := range options.GroupAdd {
params.Add("groupadd", group)
}
params.Set("pullpolicy", options.PullPolicy.String())
switch options.CommonBuildOpts.IdentityLabel {
case imageTypes.OptionalBoolTrue:
params.Set("identitylabel", "1")
case imageTypes.OptionalBoolFalse:
params.Set("identitylabel", "0")
}
if options.Quiet {
params.Set("q", "1")
}
if options.RemoveIntermediateCtrs {
params.Set("rm", "1")
}
if len(options.Target) > 0 {
params.Set("target", options.Target)
}
if hosts := options.CommonBuildOpts.AddHost; len(hosts) > 0 {
h, err := jsoniter.MarshalToString(hosts)
if err != nil {
return nil, err
}
params.Set("extrahosts", h)
}
if nsoptions := options.NamespaceOptions; len(nsoptions) > 0 {
ns, err := jsoniter.MarshalToString(nsoptions)
if err != nil {
return nil, err
}
params.Set("nsoptions", ns)
}
if shmSize := options.CommonBuildOpts.ShmSize; len(shmSize) > 0 {
shmBytes, err := units.RAMInBytes(shmSize)
if err != nil {
return nil, err
}
params.Set("shmsize", strconv.Itoa(int(shmBytes)))
}
if options.Squash {
params.Set("squash", "1")
}
if options.SourceDateEpoch != nil {
t := options.SourceDateEpoch
params.Set("sourcedateepoch", strconv.FormatInt(t.Unix(), 10))
}
if options.RewriteTimestamp {
params.Set("rewritetimestamp", "1")
} else {
params.Set("rewritetimestamp", "0")
}
if options.Timestamp != nil {
t := options.Timestamp
params.Set("timestamp", strconv.FormatInt(t.Unix(), 10))
}
if len(options.CommonBuildOpts.Ulimit) > 0 {
ulimitsJSON, err := json.Marshal(options.CommonBuildOpts.Ulimit)
if err != nil {
return nil, err
}
params.Set("ulimits", string(ulimitsJSON))
}
for _, env := range options.Envs {
params.Add("setenv", env)
}
for _, uenv := range options.UnsetEnvs {
params.Add("unsetenv", uenv)
}
for _, ulabel := range options.UnsetLabels {
params.Add("unsetlabel", ulabel)
}
for _, uannotation := range options.UnsetAnnotations {
params.Add("unsetannotation", uannotation)
}
return params, nil
}
// prepareAuthHeaders sets up authentication headers for the build request.
// It handles Docker authentication configuration and TLS verification settings
// from the system context.
func prepareAuthHeaders(options types.BuildOptions, requestParts *RequestParts) (*RequestParts, error) {
var err error
if options.SystemContext == nil {
return requestParts, err
}
if options.SystemContext.DockerAuthConfig != nil {
requestParts.Headers, err = auth.MakeXRegistryAuthHeader(options.SystemContext, options.SystemContext.DockerAuthConfig.Username, options.SystemContext.DockerAuthConfig.Password)
} else {
requestParts.Headers, err = auth.MakeXRegistryConfigHeader(options.SystemContext, "", "")
}
if options.SystemContext.DockerInsecureSkipTLSVerify == imageTypes.OptionalBoolTrue {
requestParts.Params.Set("tlsVerify", "false")
}
return requestParts, err
}
// prepareContainerFiles processes container files (Dockerfiles/Containerfiles) for the build.
// It handles URLs, stdin input, symlinks, and determines which files need to be included
// in the tar archive versus which are already in the context directory.
// The stdinDestination parameter specifies where to save stdin content when processing /dev/stdin.
// WARNING: Caller must ensure tempManager.Cleanup() is called to remove any temporary files created.
func prepareContainerFiles(containerFiles []string, contextDir string, stdinDestination string, tempManager *remote_build_helpers.TempFileManager) (*BuildFilePaths, error) {
out := BuildFilePaths{
tarContent: []string{contextDir},
newContainerFiles: []string{}, // dockerfile paths, relative to context dir, ToSlash()ed
dontexcludes: []string{"!Dockerfile", "!Containerfile", "!.dockerignore", "!.containerignore"},
excludes: []string{},
}
for _, c := range containerFiles {
// Do not add path to containerfile if it is a URL
if strings.HasPrefix(c, "http://") || strings.HasPrefix(c, "https://") {
out.newContainerFiles = append(out.newContainerFiles, c)
continue
}
if c == "/dev/stdin" {
stdinFile, err := tempManager.CreateTempFileFromReader(stdinDestination, "podman-build-stdin-*", os.Stdin)
if err != nil {
return nil, fmt.Errorf("processing stdin: %w", err)
}
c = stdinFile
}
c = filepath.Clean(c)
cfDir := filepath.Dir(c)
if absDir, err := filepath.EvalSymlinks(cfDir); err == nil {
name := filepath.ToSlash(strings.TrimPrefix(c, cfDir+string(filepath.Separator)))
c = filepath.Join(absDir, name)
}
containerfile, err := filepath.Abs(c)
if err != nil {
logrus.Errorf("Cannot find absolute path of %v: %v", c, err)
return nil, err
}
// Check if Containerfile is in the context directory, if so truncate the context directory off path
// Do NOT add to tarfile
if after, ok := strings.CutPrefix(containerfile, contextDir+string(filepath.Separator)); ok {
containerfile = after
out.dontexcludes = append(out.dontexcludes, "!"+containerfile)
out.dontexcludes = append(out.dontexcludes, "!"+containerfile+".dockerignore")
out.dontexcludes = append(out.dontexcludes, "!"+containerfile+".containerignore")
} else {
// If Containerfile does not exist, assume it is in context directory and do Not add to tarfile
if err := fileutils.Lexists(containerfile); err != nil {
if !os.IsNotExist(err) {
return nil, err
}
containerfile = c
out.dontexcludes = append(out.dontexcludes, "!"+containerfile)
out.dontexcludes = append(out.dontexcludes, "!"+containerfile+".dockerignore")
out.dontexcludes = append(out.dontexcludes, "!"+containerfile+".containerignore")
} else {
// If Containerfile does exist and not in the context directory, add it to the tarfile
out.tarContent = append(out.tarContent, containerfile)
}
}
out.newContainerFiles = append(out.newContainerFiles, filepath.ToSlash(containerfile))
}
return &out, nil
}
// prepareSecrets processes build secrets by creating temporary files for them.
// It moves secrets to the context directory and modifies the secret configuration
// to use relative paths suitable for remote builds.
// WARNING: Caller must ensure tempManager.Cleanup() is called to remove any temporary files created.
func prepareSecrets(secrets []string, contextDir string, tempManager *remote_build_helpers.TempFileManager) ([]string, []string, error) {
if len(secrets) == 0 {
return nil, nil, nil
}
secretsForRemote := []string{}
tarContent := []string{}
for _, secret := range secrets {
secretOpt := strings.Split(secret, ",")
modifiedOpt := []string{}
for _, token := range secretOpt {
opt, val, hasVal := strings.Cut(token, "=")
if hasVal {
switch opt {
case "src":
// read specified secret into a tmp file
// move tmp file to tar and change secret source to relative tmp file
tmpSecretFilePath, err := tempManager.CreateTempSecret(val, contextDir)
if err != nil {
return nil, nil, err
}
// add tmp file to context dir
tarContent = append(tarContent, tmpSecretFilePath)
modifiedSrc := fmt.Sprintf("src=%s", filepath.Base(tmpSecretFilePath))
modifiedOpt = append(modifiedOpt, modifiedSrc)
case "env":
// read specified env into a tmp file
// move tmp file to tar and change secret source to relative tmp file
secretVal := os.Getenv(val)
tmpSecretFilePath, err := tempManager.CreateTempFileFromReader(contextDir, "podman-build-secret-*", strings.NewReader(secretVal))
if err != nil {
return nil, nil, err
}
// add tmp file to context dir
tarContent = append(tarContent, tmpSecretFilePath)
modifiedSrc := fmt.Sprintf("src=%s", filepath.Base(tmpSecretFilePath))
modifiedOpt = append(modifiedOpt, modifiedSrc)
default:
modifiedOpt = append(modifiedOpt, token)
}
}
}
secretsForRemote = append(secretsForRemote, strings.Join(modifiedOpt, ","))
}
return secretsForRemote, tarContent, nil
}
// prepareRemoteRequestBody creates the request body for the build API call.
// It handles both simple tar archives and multipart form data for builds with
// additional build contexts, supporting URLs, images, and local directories.
// WARNING: Caller must close request body.
func prepareRemoteRequestBody(ctx context.Context, requestParts *RequestParts, buildFilePaths *BuildFilePaths, options types.BuildOptions) (*RequestParts, error) {
tarfile, err := nTar(append(buildFilePaths.excludes, buildFilePaths.dontexcludes...), buildFilePaths.tarContent...)
if err != nil {
logrus.Errorf("Cannot tar container entries %v error: %v", buildFilePaths.tarContent, err)
return nil, err
}
var contentType string
// If there are additional build contexts, we need to handle them based on the server version
// podman version >= 5.6.0 supports multipart/form-data for additional build contexts that
// are local directories or archives. URLs and images are still sent as query parameters.
isSupported, err := isSupportedVersion(ctx, "5.6.0")
if err != nil {
return nil, err
}
if len(options.SBOMScanOptions) > 0 {
for _, sbomScanOpts := range options.SBOMScanOptions {
if sbomScanOpts.SBOMOutput != "" {
requestParts.Params.Set("sbom-output", sbomScanOpts.SBOMOutput)
}
if sbomScanOpts.PURLOutput != "" {
requestParts.Params.Set("sbom-purl-output", sbomScanOpts.PURLOutput)
}
if sbomScanOpts.ImageSBOMOutput != "" {
requestParts.Params.Set("sbom-image-output", sbomScanOpts.ImageSBOMOutput)
}
if sbomScanOpts.ImagePURLOutput != "" {
requestParts.Params.Set("sbom-image-purl-output", sbomScanOpts.ImagePURLOutput)
}
if sbomScanOpts.Image != "" {
requestParts.Params.Set("sbom-scanner-image", sbomScanOpts.Image)
}
if commands := sbomScanOpts.Commands; len(commands) > 0 {
c, err := jsoniter.MarshalToString(commands)
if err != nil {
return nil, err
}
requestParts.Params.Add("sbom-scanner-command", c)
}
if sbomScanOpts.MergeStrategy != "" {
requestParts.Params.Set("sbom-merge-strategy", string(sbomScanOpts.MergeStrategy))
}
}
}
if len(options.AdditionalBuildContexts) == 0 {
requestParts.Body = tarfile
logrus.Debugf("Using main build context: %q", options.ContextDirectory)
return requestParts, nil
}
if !isSupported {
convertAdditionalBuildContexts(options.AdditionalBuildContexts)
additionalBuildContextMap, err := jsoniter.Marshal(options.AdditionalBuildContexts)
if err != nil {
return nil, err
}
requestParts.Params.Set("additionalbuildcontexts", string(additionalBuildContextMap))
requestParts.Body = tarfile
logrus.Debugf("Using main build context: %q", options.ContextDirectory)
return requestParts, nil
}
imageContexts := make(map[string]string)
urlContexts := make(map[string]string)
localContexts := make(map[string]*define.AdditionalBuildContext)
for name, context := range options.AdditionalBuildContexts {
switch {
case context.IsImage:
imageContexts[name] = context.Value
case context.IsURL:
urlContexts[name] = context.Value
default:
localContexts[name] = context
}
}
logrus.Debugf("URL Contexts: %v", urlContexts)
for name, url := range urlContexts {
requestParts.Params.Add("additionalbuildcontexts", fmt.Sprintf("%s=url:%s", name, url))
}
logrus.Debugf("Image Contexts: %v", imageContexts)
for name, imageRef := range imageContexts {
requestParts.Params.Add("additionalbuildcontexts", fmt.Sprintf("%s=image:%s", name, imageRef))
}
if len(localContexts) == 0 {
requestParts.Body = tarfile
logrus.Debugf("Using main build context: %q", options.ContextDirectory)
return requestParts, nil
}
// Multipart request structure:
// - "MainContext": The main build context as a tar file
// - "build-context-<name>": Each additional local context as a tar file
logrus.Debugf("Using additional local build contexts: %v", localContexts)
pr, pw := io.Pipe()
writer := multipart.NewWriter(pw)
contentType = writer.FormDataContentType()
requestParts.Body = pr
if requestParts.Headers == nil {
requestParts.Headers = make(http.Header)
}
requestParts.Headers.Set("Content-Type", contentType)
go func() {
defer pw.Close()
defer writer.Close()
mainContext, err := writer.CreateFormFile("MainContext", "MainContext.tar")
if err != nil {
pw.CloseWithError(fmt.Errorf("creating form file for main context: %w", err))
return
}
if _, err := io.Copy(mainContext, tarfile); err != nil {
pw.CloseWithError(fmt.Errorf("copying main context: %w", err))
return
}
defer func() {
if err := tarfile.Close(); err != nil {
logrus.Errorf("failed to close context tarfile: %v\n", err)
}
}()
for name, context := range localContexts {
logrus.Debugf("Processing additional local context: %s", name)
part, err := writer.CreateFormFile(fmt.Sprintf("build-context-%s", name), name)
if err != nil {
pw.CloseWithError(fmt.Errorf("creating form file for context %q: %w", name, err))
return
}
// Context is already a tar
if archive.IsArchivePath(context.Value) {
file, err := os.Open(context.Value)
if err != nil {
pw.CloseWithError(fmt.Errorf("opening archive %q: %w", name, err))
return
}
if _, err := io.Copy(part, file); err != nil {
file.Close()
pw.CloseWithError(fmt.Errorf("copying context %q: %w", name, err))
return
}
file.Close()
} else {
tarContent, err := nTar(nil, context.Value)
if err != nil {
pw.CloseWithError(fmt.Errorf("creating tar content %q: %w", name, err))
return
}
if _, err = io.Copy(part, tarContent); err != nil {
pw.CloseWithError(fmt.Errorf("copying tar content %q: %w", name, err))
return
}
if err := tarContent.Close(); err != nil {
logrus.Errorf("Error closing tar content for context %q: %v\n", name, err)
}
}
}
}()
logrus.Debugf("Multipart body is created with content type: %s", contentType)
return requestParts, nil
}
// executeBuildRequest sends the build request to the API endpoint and returns the response.
// It handles the HTTP request creation and error checking for the build operation.
// WARNING: Caller must close the response body.
func executeBuildRequest(ctx context.Context, endpoint string, requestParts *RequestParts) (*bindings.APIResponse, error) {
conn, err := bindings.GetClient(ctx)
if err != nil {
return nil, err
}
response, err := conn.DoRequest(ctx, requestParts.Body, http.MethodPost, endpoint, requestParts.Params, requestParts.Headers)
if err != nil {
return nil, err
}
if !response.IsSuccess() {
return nil, response.Process(err)
}
return response, nil
}
// processBuildResponse processes the streaming build response from the API.
// It reads the JSON stream, extracts build output and errors, writes to stdout,
// and returns a build report with the final image ID.
func processBuildResponse(response *bindings.APIResponse, stdout io.Writer, saveFormat string) (*types.BuildReport, error) {
body := response.Body.(io.Reader)
if logrus.IsLevelEnabled(logrus.DebugLevel) {
if v, found := os.LookupEnv("PODMAN_RETAIN_BUILD_ARTIFACT"); found {
if keep, _ := strconv.ParseBool(v); keep {
t, _ := os.CreateTemp("", "build_*_client")
defer t.Close()
body = io.TeeReader(response.Body, t)
}
}
}
dec := json.NewDecoder(body)
var id string
for {
var s BuildResponse
select {
// FIXME(vrothberg): it seems we always hit the EOF case below,
// even when the server quit but it seems desirable to
// distinguish a proper build from a transient EOF.
case <-response.Request.Context().Done():
return &types.BuildReport{ID: id, SaveFormat: saveFormat}, nil
default:
// non-blocking select
}
if err := dec.Decode(&s); err != nil {
if errors.Is(err, io.ErrUnexpectedEOF) {
return nil, fmt.Errorf("server probably quit: %w", err)
}
// EOF means the stream is over in which case we need
// to have read the id.
if errors.Is(err, io.EOF) && id != "" {
break
}
return &types.BuildReport{ID: id, SaveFormat: saveFormat}, fmt.Errorf("decoding stream: %w", err)
}
switch {
case s.Stream != "":
raw := []byte(s.Stream)
stdout.Write(raw)
if iidRegex.Match(raw) {
id = strings.TrimSuffix(s.Stream, "\n")
}
case s.Error != nil:
// If there's an error, return directly. The stream
// will be closed on return.
return &types.BuildReport{ID: id, SaveFormat: saveFormat}, errors.New(s.Error.Message)
default:
return &types.BuildReport{ID: id, SaveFormat: saveFormat}, errors.New("failed to parse build results stream, unexpected input")
}
}
return &types.BuildReport{ID: id, SaveFormat: saveFormat}, nil
}
// prepareLocalRequestBody prepares HTTP request parameters for local build API calls.
// It sets up local context directory and additional build contexts using already translated paths.
func prepareLocalRequestBody(_ context.Context, requestParts *RequestParts, _ *BuildFilePaths, options types.BuildOptions) (*RequestParts, error) {
requestParts.Params.Set("localcontextdir", options.ContextDirectory)
for name, context := range options.AdditionalBuildContexts {
switch {
case context.IsImage:
requestParts.Params.Add("additionalbuildcontexts", fmt.Sprintf("%s=image:%s", name, context.Value))
case context.IsURL:
requestParts.Params.Add("additionalbuildcontexts", fmt.Sprintf("%s=url:%s", name, context.Value))
default:
requestParts.Params.Add("additionalbuildcontexts", fmt.Sprintf("%s=localpath:%s", name, context.Value))
}
}
return requestParts, nil
}
// BuildFromServerContext performs a container image build using the local build API to build image with files present on server.
//
// Unlike the standard Build function, this uses existing files on the remote server's filesystem
// rather than uploading build contexts. The containerFiles and options parameters should contain
// already translated paths pointing to files on the remote server, making it suitable for scenarios
// where build contexts already exist on the server (e.g., shared filesystems, mounted volumes).
//
// The context directory and containerFiles paths must be accessible on the remote server.
// Missing paths will result in build errors.
//
// Returns a BuildReport containing the final image ID and save format.
func BuildFromServerContext(ctx context.Context, containerFiles []string, options types.BuildOptions) (*types.BuildReport, error) {
return build(ctx, containerFiles, options, "/local/build", prepareLocalRequestBody)
}
// Build performs a container image build on the remote API using the standard build API.
//
// Prepares build contexts and container files by creating tar archives from local directories,
// processes build secrets and authentication, and streams the build to the remote server.
// Supports additional build contexts (URLs, images, local directories) via multipart uploads
// for servers >= v5.6.0, otherwise uses query parameters for compatibility.
//
// Returns a BuildReport containing the final image ID and save format.
func Build(ctx context.Context, containerFiles []string, options types.BuildOptions) (*types.BuildReport, error) {
return build(ctx, containerFiles, options, "/build", prepareRemoteRequestBody)
}
type prepareRequestBodyFunc func(ctx context.Context, requestParts *RequestParts, buildFilePaths *BuildFilePaths, options types.BuildOptions) (*RequestParts, error)
func build(ctx context.Context, containerFiles []string, options types.BuildOptions, endpoint string, prepareRequestBody prepareRequestBodyFunc) (*types.BuildReport, error) {
if options.CommonBuildOpts == nil {
options.CommonBuildOpts = new(define.CommonBuildOptions)
}
tempManager := remote_build_helpers.NewTempFileManager()
defer tempManager.Cleanup()
params_, err := prepareParams(options)
if err != nil {
return nil, err
}
var headers http.Header
var requestBody io.ReadCloser
requestParts := &RequestParts{
Params: params_,
Headers: headers,
Body: requestBody,
}
var contextDir string