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
|
package images
import (
"fmt"
"io"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
buildahDefine "github.com/containers/buildah/define"
buildahCLI "github.com/containers/buildah/pkg/cli"
"github.com/containers/buildah/pkg/parse"
buildahUtil "github.com/containers/buildah/pkg/util"
"github.com/containers/common/pkg/auth"
"github.com/containers/common/pkg/completion"
"github.com/containers/common/pkg/config"
encconfig "github.com/containers/ocicrypt/config"
enchelpers "github.com/containers/ocicrypt/helpers"
"github.com/containers/podman/v4/cmd/podman/common"
"github.com/containers/podman/v4/cmd/podman/registry"
"github.com/containers/podman/v4/cmd/podman/utils"
"github.com/containers/podman/v4/pkg/domain/entities"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
)
// buildFlagsWrapper are local to cmd/ as the build code is using Buildah-internal
// types. Hence, after parsing, we are converting buildFlagsWrapper to the entities'
// options which essentially embed the Buildah types.
type buildFlagsWrapper struct {
// Buildah stuff first
buildahCLI.BudResults
buildahCLI.LayerResults
buildahCLI.FromAndBudResults
buildahCLI.NameSpaceResults
buildahCLI.UserNSResults
// SquashAll squashes all layers into a single layer.
SquashAll bool
}
var (
// Command: podman _diff_ Object_ID
buildDescription = "Builds an OCI or Docker image using instructions from one or more Containerfiles and a specified build context directory."
buildCmd = &cobra.Command{
Use: "build [options] [CONTEXT]",
Short: "Build an image using instructions from Containerfiles",
Long: buildDescription,
Args: cobra.MaximumNArgs(1),
RunE: build,
ValidArgsFunction: common.AutocompleteDefaultOneArg,
Example: `podman build .
podman build --creds=username:password -t imageName -f Containerfile.simple .
podman build --layers --force-rm --tag imageName .`,
}
imageBuildCmd = &cobra.Command{
Args: buildCmd.Args,
Use: buildCmd.Use,
Short: buildCmd.Short,
Long: buildCmd.Long,
RunE: buildCmd.RunE,
ValidArgsFunction: buildCmd.ValidArgsFunction,
Example: `podman image build .
podman image build --creds=username:password -t imageName -f Containerfile.simple .
podman image build --layers --force-rm --tag imageName .`,
}
buildxBuildCmd = &cobra.Command{
Args: buildCmd.Args,
Use: buildCmd.Use,
Short: buildCmd.Short,
Long: buildCmd.Long,
RunE: buildCmd.RunE,
ValidArgsFunction: buildCmd.ValidArgsFunction,
Example: `podman buildx build .
podman buildx build --creds=username:password -t imageName -f Containerfile.simple .
podman buildx build --layers --force-rm --tag imageName .`,
}
buildOpts = buildFlagsWrapper{}
)
// useLayers returns false if BUILDAH_LAYERS is set to "0" or "false"
// otherwise it returns true
func useLayers() string {
layers := os.Getenv("BUILDAH_LAYERS")
if strings.ToLower(layers) == "false" || layers == "0" {
return "false"
}
return "true"
}
func init() {
registry.Commands = append(registry.Commands, registry.CliCommand{
Command: buildCmd,
})
buildFlags(buildCmd)
registry.Commands = append(registry.Commands, registry.CliCommand{
Command: imageBuildCmd,
Parent: imageCmd,
})
buildFlags(imageBuildCmd)
registry.Commands = append(registry.Commands, registry.CliCommand{
Command: buildxBuildCmd,
Parent: buildxCmd,
})
buildFlags(buildxBuildCmd)
}
func buildFlags(cmd *cobra.Command) {
flags := cmd.Flags()
// buildx build --load ignored, but added for compliance
flags.Bool("load", false, "buildx --load")
_ = flags.MarkHidden("load")
// buildx build --progress ignored, but added for compliance
flags.String("progress", "auto", "buildx --progress")
_ = flags.MarkHidden("progress")
// Podman flags
flags.BoolVarP(&buildOpts.SquashAll, "squash-all", "", false, "Squash all layers into a single layer")
// Bud flags
budFlags := buildahCLI.GetBudFlags(&buildOpts.BudResults)
// --pull flag
flag := budFlags.Lookup("pull")
if err := flag.Value.Set("true"); err != nil {
logrus.Errorf("Unable to set --pull to true: %v", err)
}
flag.DefValue = "true"
flag.Usage = "Always attempt to pull the image (errors are fatal)"
flags.AddFlagSet(&budFlags)
// Add the completion functions
budCompletions := buildahCLI.GetBudFlagsCompletions()
completion.CompleteCommandFlags(cmd, budCompletions)
// Layer flags
layerFlags := buildahCLI.GetLayerFlags(&buildOpts.LayerResults)
// --layers flag
flag = layerFlags.Lookup("layers")
useLayersVal := useLayers()
buildOpts.Layers = useLayersVal == "true"
if err := flag.Value.Set(useLayersVal); err != nil {
logrus.Errorf("Unable to set --layers to %v: %v", useLayersVal, err)
}
flag.DefValue = useLayersVal
// --force-rm flag
flag = layerFlags.Lookup("force-rm")
if err := flag.Value.Set("true"); err != nil {
logrus.Errorf("Unable to set --force-rm to true: %v", err)
}
flag.DefValue = "true"
flags.AddFlagSet(&layerFlags)
// FromAndBud flags
fromAndBudFlags, err := buildahCLI.GetFromAndBudFlags(&buildOpts.FromAndBudResults, &buildOpts.UserNSResults, &buildOpts.NameSpaceResults)
if err != nil {
logrus.Errorf("Setting up build flags: %v", err)
os.Exit(1)
}
// --http-proxy flag
// containers.conf defaults to true but we want to force false by default for remote, since settings do not apply
if registry.IsRemote() {
flag = fromAndBudFlags.Lookup("http-proxy")
buildOpts.HTTPProxy = false
if err := flag.Value.Set("false"); err != nil {
logrus.Errorf("Unable to set --https-proxy to %v: %v", false, err)
}
flag.DefValue = "false"
}
flags.AddFlagSet(&fromAndBudFlags)
// Add the completion functions
fromAndBudFlagsCompletions := buildahCLI.GetFromAndBudFlagsCompletions()
completion.CompleteCommandFlags(cmd, fromAndBudFlagsCompletions)
flags.SetNormalizeFunc(buildahCLI.AliasFlags)
if registry.IsRemote() {
flag = flags.Lookup("isolation")
buildOpts.Isolation = buildahDefine.OCI
if err := flag.Value.Set(buildahDefine.OCI); err != nil {
logrus.Errorf("Unable to set --isolation to %v: %v", buildahDefine.OCI, err)
}
flag.DefValue = buildahDefine.OCI
_ = flags.MarkHidden("disable-content-trust")
_ = flags.MarkHidden("cache-from")
_ = flags.MarkHidden("sign-by")
_ = flags.MarkHidden("signature-policy")
_ = flags.MarkHidden("tls-verify")
_ = flags.MarkHidden("compress")
_ = flags.MarkHidden("volume")
}
}
// build executes the build command.
func build(cmd *cobra.Command, args []string) error {
if (cmd.Flags().Changed("squash") && cmd.Flags().Changed("layers")) ||
(cmd.Flags().Changed("squash-all") && cmd.Flags().Changed("layers")) ||
(cmd.Flags().Changed("squash-all") && cmd.Flags().Changed("squash")) {
return errors.New("cannot specify --squash, --squash-all and --layers options together")
}
// Extract container files from the CLI (i.e., --file/-f) first.
var containerFiles []string
for _, f := range buildOpts.File {
if f == "-" {
containerFiles = append(containerFiles, "/dev/stdin")
} else {
containerFiles = append(containerFiles, f)
}
}
// Determine context directory.
var contextDir string
if len(args) > 0 {
// The context directory could be a URL. Try to handle that.
tempDir, subDir, err := buildahDefine.TempDirForURL("", "buildah", args[0])
if err != nil {
return errors.Wrapf(err, "error prepping temporary context directory")
}
if tempDir != "" {
// We had to download it to a temporary directory.
// Delete it later.
defer func() {
if err = os.RemoveAll(tempDir); err != nil {
logrus.Errorf("Removing temporary directory %q: %v", contextDir, err)
}
}()
contextDir = filepath.Join(tempDir, subDir)
} else {
// Nope, it was local. Use it as is.
absDir, err := filepath.Abs(args[0])
if err != nil {
return errors.Wrapf(err, "error determining path to directory %q", args[0])
}
contextDir = absDir
}
} else {
// No context directory or URL was specified. Try to use the home of
// the first locally-available Containerfile.
for i := range containerFiles {
if strings.HasPrefix(containerFiles[i], "http://") ||
strings.HasPrefix(containerFiles[i], "https://") ||
strings.HasPrefix(containerFiles[i], "git://") ||
strings.HasPrefix(containerFiles[i], "github.com/") {
continue
}
absFile, err := filepath.Abs(containerFiles[i])
if err != nil {
return errors.Wrapf(err, "error determining path to file %q", containerFiles[i])
}
contextDir = filepath.Dir(absFile)
containerFiles[i] = absFile
break
}
}
if contextDir == "" {
return errors.Errorf("no context directory and no Containerfile specified")
}
if !utils.IsDir(contextDir) {
return errors.Errorf("context must be a directory: %q", contextDir)
}
if len(containerFiles) == 0 {
if utils.FileExists(filepath.Join(contextDir, "Containerfile")) {
containerFiles = append(containerFiles, filepath.Join(contextDir, "Containerfile"))
} else {
containerFiles = append(containerFiles, filepath.Join(contextDir, "Dockerfile"))
}
}
var logfile *os.File
if cmd.Flag("logfile").Changed {
var err error
logfile, err = os.OpenFile(buildOpts.Logfile, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0600)
if err != nil {
return err
}
defer logfile.Close()
}
apiBuildOpts, err := buildFlagsWrapperToOptions(cmd, contextDir, &buildOpts, logfile)
if err != nil {
return err
}
report, err := registry.ImageEngine().Build(registry.GetContext(), containerFiles, *apiBuildOpts)
if err != nil {
exitCode := buildahCLI.ExecErrorCodeGeneric
if registry.IsRemote() {
// errors from server does not contain ExitCode
// so parse exit code from error message
remoteExitCode, parseErr := utils.ExitCodeFromBuildError(fmt.Sprint(errors.Cause(err)))
if parseErr == nil {
exitCode = remoteExitCode
}
}
if ee, ok := (errors.Cause(err)).(*exec.ExitError); ok {
exitCode = ee.ExitCode()
}
registry.SetExitCode(exitCode)
return err
}
if cmd.Flag("iidfile").Changed {
f, err := os.Create(buildOpts.Iidfile)
if err != nil {
return err
}
if _, err := f.WriteString("sha256:" + report.ID); err != nil {
return err
}
}
return nil
}
// buildFlagsWrapperToOptions converts the local build flags to the build options used
// in the API which embed Buildah types used across the build code. Doing the
// conversion here prevents the API from doing that (redundantly).
//
// TODO: this code should really be in Buildah.
func buildFlagsWrapperToOptions(c *cobra.Command, contextDir string, flags *buildFlagsWrapper, logfile *os.File) (*entities.BuildOptions, error) {
output := ""
tags := []string{}
if c.Flag("tag").Changed {
tags = flags.Tag
if len(tags) > 0 {
output = tags[0]
tags = tags[1:]
}
}
commonOpts, err := parse.CommonBuildOptions(c)
if err != nil {
return nil, err
}
pullFlagsCount := 0
if c.Flag("pull").Changed {
pullFlagsCount++
}
if c.Flag("pull-always").Changed {
pullFlagsCount++
}
if c.Flag("pull-never").Changed {
pullFlagsCount++
}
if pullFlagsCount > 1 {
return nil, errors.Errorf("can only set one of 'pull' or 'pull-always' or 'pull-never'")
}
pullPolicy := buildahDefine.PullIfMissing
if c.Flags().Changed("pull") && flags.Pull {
pullPolicy = buildahDefine.PullAlways
}
if flags.PullAlways {
pullPolicy = buildahDefine.PullAlways
}
if flags.PullNever {
pullPolicy = buildahDefine.PullNever
}
if c.Flag("authfile").Changed {
if err := auth.CheckAuthFile(flags.Authfile); err != nil {
return nil, err
}
}
cleanTmpFile := false
flags.Authfile, cleanTmpFile = buildahUtil.MirrorToTempFileIfPathIsDescriptor(flags.Authfile)
if cleanTmpFile {
defer os.Remove(flags.Authfile)
}
args := make(map[string]string)
if c.Flag("build-arg").Changed {
for _, arg := range flags.BuildArg {
av := strings.SplitN(arg, "=", 2)
if len(av) > 1 {
args[av[0]] = av[1]
} else {
// check if the env is set in the local environment and use that value if it is
if val, present := os.LookupEnv(av[0]); present {
args[av[0]] = val
} else {
delete(args, av[0])
}
}
}
}
flags.Layers = buildOpts.Layers
// `buildah bud --layers=false` acts like `docker build --squash` does.
// That is all of the new layers created during the build process are
// condensed into one, any layers present prior to this build are
// retained without condensing. `buildah bud --squash` squashes both
// new and old layers down into one. Translate Podman commands into
// Buildah. Squash invoked, retain old layers, squash new layers into
// one.
if c.Flags().Changed("squash") && buildOpts.Squash {
flags.Squash = false
flags.Layers = false
}
// Squash-all invoked, squash both new and old layers into one.
if c.Flags().Changed("squash-all") {
flags.Squash = true
flags.Layers = false
}
var stdin io.Reader
if flags.Stdin {
stdin = os.Stdin
}
var stdout, stderr, reporter *os.File
stdout = os.Stdout
stderr = os.Stderr
reporter = os.Stderr
if logfile != nil {
logrus.SetOutput(logfile)
stdout = logfile
stderr = logfile
reporter = logfile
}
nsValues, networkPolicy, err := parse.NamespaceOptions(c)
if err != nil {
return nil, err
}
// `buildah bud --layers=false` acts like `docker build --squash` does.
// That is all of the new layers created during the build process are
// condensed into one, any layers present prior to this build are retained
// without condensing. `buildah bud --squash` squashes both new and old
// layers down into one. Translate Podman commands into Buildah.
// Squash invoked, retain old layers, squash new layers into one.
if c.Flags().Changed("squash") && flags.Squash {
flags.Squash = false
flags.Layers = false
}
// Squash-all invoked, squash both new and old layers into one.
if c.Flags().Changed("squash-all") {
flags.Squash = true
flags.Layers = false
}
compression := buildahDefine.Gzip
if flags.DisableCompression {
compression = buildahDefine.Uncompressed
}
isolation, err := parse.IsolationOption(flags.Isolation)
if err != nil {
return nil, err
}
usernsOption, idmappingOptions, err := parse.IDMappingOptions(c, isolation)
if err != nil {
return nil, err
}
nsValues = append(nsValues, usernsOption...)
systemContext, err := parse.SystemContextFromOptions(c)
if err != nil {
return nil, err
}
format := ""
flags.Format = strings.ToLower(flags.Format)
switch {
case strings.HasPrefix(flags.Format, buildahDefine.OCI):
format = buildahDefine.OCIv1ImageManifest
case strings.HasPrefix(flags.Format, buildahDefine.DOCKER):
format = buildahDefine.Dockerv2ImageManifest
default:
return nil, errors.Errorf("unrecognized image type %q", flags.Format)
}
runtimeFlags := []string{}
for _, arg := range flags.RuntimeFlags {
runtimeFlags = append(runtimeFlags, "--"+arg)
}
containerConfig := registry.PodmanConfig()
for _, arg := range containerConfig.RuntimeFlags {
runtimeFlags = append(runtimeFlags, "--"+arg)
}
if containerConfig.Engine.CgroupManager == config.SystemdCgroupsManager {
runtimeFlags = append(runtimeFlags, "--systemd-cgroup")
}
platforms, err := parse.PlatformsFromOptions(c)
if err != nil {
return nil, err
}
decConfig, err := getDecryptConfig(flags.DecryptionKeys)
if err != nil {
return nil, errors.Wrapf(err, "unable to obtain decrypt config")
}
opts := buildahDefine.BuildOptions{
AddCapabilities: flags.CapAdd,
AdditionalTags: tags,
AllPlatforms: flags.AllPlatforms,
Annotations: flags.Annotation,
Args: args,
BlobDirectory: flags.BlobCache,
CommonBuildOpts: commonOpts,
Compression: compression,
ConfigureNetwork: networkPolicy,
ContextDirectory: contextDir,
DefaultMountsFilePath: containerConfig.Containers.DefaultMountsFile,
Devices: flags.Devices,
DropCapabilities: flags.CapDrop,
Err: stderr,
ForceRmIntermediateCtrs: flags.ForceRm,
From: flags.From,
IDMappingOptions: idmappingOptions,
In: stdin,
Isolation: isolation,
Jobs: &flags.Jobs,
Labels: flags.Label,
Layers: flags.Layers,
LogRusage: flags.LogRusage,
Manifest: flags.Manifest,
MaxPullPushRetries: 3,
NamespaceOptions: nsValues,
NoCache: flags.NoCache,
OciDecryptConfig: decConfig,
Out: stdout,
Output: output,
OutputFormat: format,
Platforms: platforms,
PullPolicy: pullPolicy,
PullPushRetryDelay: 2 * time.Second,
Quiet: flags.Quiet,
RemoveIntermediateCtrs: flags.Rm,
ReportWriter: reporter,
Runtime: containerConfig.RuntimePath,
RuntimeArgs: runtimeFlags,
RusageLogFile: flags.RusageLogFile,
SignBy: flags.SignBy,
SignaturePolicyPath: flags.SignaturePolicy,
Squash: flags.Squash,
SystemContext: systemContext,
Target: flags.Target,
TransientMounts: flags.Volumes,
UnsetEnvs: flags.UnsetEnvs,
}
if flags.IgnoreFile != "" {
excludes, err := parseDockerignore(flags.IgnoreFile)
if err != nil {
return nil, errors.Wrapf(err, "unable to obtain decrypt config")
}
opts.Excludes = excludes
}
if c.Flag("timestamp").Changed {
timestamp := time.Unix(flags.Timestamp, 0).UTC()
opts.Timestamp = ×tamp
}
return &entities.BuildOptions{BuildOptions: opts}, nil
}
func getDecryptConfig(decryptionKeys []string) (*encconfig.DecryptConfig, error) {
decConfig := &encconfig.DecryptConfig{}
if len(decryptionKeys) > 0 {
// decryption
dcc, err := enchelpers.CreateCryptoConfig([]string{}, decryptionKeys)
if err != nil {
return nil, errors.Wrapf(err, "invalid decryption keys")
}
cc := encconfig.CombineCryptoConfigs([]encconfig.CryptoConfig{dcc})
decConfig = cc.DecryptConfig
}
return decConfig, nil
}
func parseDockerignore(ignoreFile string) ([]string, error) {
excludes := []string{}
ignore, err := ioutil.ReadFile(ignoreFile)
if err != nil {
return excludes, err
}
for _, e := range strings.Split(string(ignore), "\n") {
if len(e) == 0 || e[0] == '#' {
continue
}
excludes = append(excludes, e)
}
return excludes, nil
}
|