| 1 |
package imagebuilder |
| 2 |
|
| 3 |
// This file contains the dispatchers for each command. Note that |
| 4 |
// `nullDispatch` is not actually a command, but support for commands we parse |
| 5 |
// but do nothing with. |
| 6 |
// |
| 7 |
// See evaluator.go for a higher level discussion of the whole evaluator |
| 8 |
// package. |
| 9 |
|
| 10 |
import ( |
| 11 |
"flag" |
| 12 |
"fmt" |
| 13 |
"os" |
| 14 |
"path/filepath" |
| 15 |
"runtime" |
| 16 |
"strconv" |
| 17 |
"strings" |
| 18 |
|
| 19 |
docker "github.com/fsouza/go-dockerclient" |
| 20 |
|
| 21 |
"github.com/containerd/errdefs" |
| 22 |
"github.com/containerd/platforms" |
| 23 |
"github.com/openshift/imagebuilder/internal" |
| 24 |
"github.com/openshift/imagebuilder/signal" |
| 25 |
"github.com/openshift/imagebuilder/strslice" |
| 26 |
"go.podman.io/storage/pkg/regexp" |
| 27 |
|
| 28 |
buildkitcommand "github.com/moby/buildkit/frontend/dockerfile/command" |
| 29 |
buildkitparser "github.com/moby/buildkit/frontend/dockerfile/parser" |
| 30 |
buildkitshell "github.com/moby/buildkit/frontend/dockerfile/shell" |
| 31 |
"github.com/tonistiigi/dchapes-mode" |
| 32 |
) |
| 33 |
|
| 34 |
var ( |
| 35 |
obRgex = regexp.Delayed(`(?i)^\s*ONBUILD\s*`) |
| 36 |
) |
| 37 |
|
| 38 |
var localspec = platforms.DefaultSpec() |
| 39 |
|
| 40 |
// https://docs.docker.com/engine/reference/builder/#automatic-platform-args-in-the-global-scope |
| 41 |
var builtinArgDefaults = map[string]string{ |
| 42 |
"TARGETPLATFORM": localspec.OS + "/" + localspec.Architecture, |
| 43 |
"TARGETOS": localspec.OS, |
| 44 |
"TARGETARCH": localspec.Architecture, |
| 45 |
"TARGETVARIANT": "", |
| 46 |
"BUILDPLATFORM": localspec.OS + "/" + localspec.Architecture, |
| 47 |
"BUILDOS": localspec.OS, |
| 48 |
"BUILDARCH": localspec.Architecture, |
| 49 |
"BUILDVARIANT": "", |
| 50 |
} |
| 51 |
|
| 52 |
// ENV foo bar |
| 53 |
// |
| 54 |
// Sets the environment variable foo to bar, also makes interpolation |
| 55 |
// in the dockerfile available from the next statement on via ${foo}. |
| 56 |
func env(b *Builder, args []string, attributes map[string]bool, flagArgs []string, original string, heredocs []buildkitparser.Heredoc) error { |
| 57 |
if len(args) == 0 { |
| 58 |
return errAtLeastOneArgument("ENV") |
| 59 |
} |
| 60 |
|
| 61 |
if len(args)%2 != 0 { |
| 62 |
// should never get here, but just in case |
| 63 |
return errTooManyArguments("ENV") |
| 64 |
} |
| 65 |
|
| 66 |
// TODO/FIXME/NOT USED |
| 67 |
// Just here to show how to use the builder flags stuff within the |
| 68 |
// context of a builder command. Will remove once we actually add |
| 69 |
// a builder command to something! |
| 70 |
/* |
| 71 |
flBool1 := b.flags.AddBool("bool1", false) |
| 72 |
flStr1 := b.flags.AddString("str1", "HI") |
| 73 |
|
| 74 |
if err := b.flags.Parse(); err != nil { |
| 75 |
return err |
| 76 |
} |
| 77 |
|
| 78 |
fmt.Printf("Bool1:%v\n", flBool1) |
| 79 |
fmt.Printf("Str1:%v\n", flStr1) |
| 80 |
*/ |
| 81 |
|
| 82 |
for j := 0; j+1 < len(args); j += 2 { |
| 83 |
// name ==> args[j] |
| 84 |
// value ==> args[j+1] |
| 85 |
newVar := []string{args[j] + "=" + args[j+1]} |
| 86 |
b.RunConfig.Env = mergeEnv(b.RunConfig.Env, newVar) |
| 87 |
b.Env = mergeEnv(b.Env, newVar) |
| 88 |
} |
| 89 |
|
| 90 |
return nil |
| 91 |
} |
| 92 |
|
| 93 |
// MAINTAINER some text <[email protected]> |
| 94 |
// |
| 95 |
// Sets the maintainer metadata. |
| 96 |
func maintainer(b *Builder, args []string, attributes map[string]bool, flagArgs []string, original string, heredocs []buildkitparser.Heredoc) error { |
| 97 |
if len(args) != 1 { |
| 98 |
return errExactlyOneArgument("MAINTAINER") |
| 99 |
} |
| 100 |
b.Author = args[0] |
| 101 |
return nil |
| 102 |
} |
| 103 |
|
| 104 |
// LABEL some json data describing the image |
| 105 |
// |
| 106 |
// Sets the Label variable foo to bar, |
| 107 |
func label(b *Builder, args []string, attributes map[string]bool, flagArgs []string, original string, heredocs []buildkitparser.Heredoc) error { |
| 108 |
if len(args) == 0 { |
| 109 |
return errAtLeastOneArgument("LABEL") |
| 110 |
} |
| 111 |
if len(args)%2 != 0 { |
| 112 |
// should never get here, but just in case |
| 113 |
return errTooManyArguments("LABEL") |
| 114 |
} |
| 115 |
|
| 116 |
if b.RunConfig.Labels == nil { |
| 117 |
b.RunConfig.Labels = map[string]string{} |
| 118 |
} |
| 119 |
|
| 120 |
for j := 0; j < len(args); j++ { |
| 121 |
// name ==> args[j] |
| 122 |
// value ==> args[j+1] |
| 123 |
b.RunConfig.Labels[args[j]] = args[j+1] |
| 124 |
j++ |
| 125 |
} |
| 126 |
return nil |
| 127 |
} |
| 128 |
|
| 129 |
func processHereDocs(instruction, originalInstruction string, heredocs []buildkitparser.Heredoc, args []string) ([]File, error) { |
| 130 |
var files []File |
| 131 |
for _, heredoc := range heredocs { |
| 132 |
var err error |
| 133 |
content := heredoc.Content |
| 134 |
if heredoc.Chomp { |
| 135 |
content = buildkitparser.ChompHeredocContent(content) |
| 136 |
} |
| 137 |
if heredoc.Expand && !strings.EqualFold(instruction, buildkitcommand.Run) { |
| 138 |
shlex := buildkitshell.NewLex('\\') |
| 139 |
shlex.RawQuotes = true |
| 140 |
shlex.RawEscapes = true |
| 141 |
content, _, err = shlex.ProcessWord(content, internal.EnvironmentSlice(args)) |
| 142 |
if err != nil { |
| 143 |
return nil, err |
| 144 |
} |
| 145 |
} |
| 146 |
file := File{ |
| 147 |
Data: content, |
| 148 |
Name: heredoc.Name, |
| 149 |
} |
| 150 |
files = append(files, file) |
| 151 |
} |
| 152 |
return files, nil |
| 153 |
} |
| 154 |
|
| 155 |
// ADD foo /path |
| 156 |
// |
| 157 |
// Add the file 'foo' to '/path'. Tarball and Remote URL (git, http) handling |
| 158 |
// exist here. If you do not wish to have this automatic handling, use COPY. |
| 159 |
func add(b *Builder, args []string, attributes map[string]bool, flagArgs []string, original string, heredocs []buildkitparser.Heredoc) error { |
| 160 |
if len(args) < 2 { |
| 161 |
return errAtLeastTwoArgument("ADD") |
| 162 |
} |
| 163 |
var chown string |
| 164 |
var chmod string |
| 165 |
var checksum string |
| 166 |
var keepGitDir bool |
| 167 |
var link bool |
| 168 |
var excludes []string |
| 169 |
last := len(args) - 1 |
| 170 |
dest := makeAbsolute(args[last], b.RunConfig.WorkingDir) |
| 171 |
filteredUserArgs := make(map[string]string) |
| 172 |
for k, v := range b.Args { |
| 173 |
if _, ok := b.AllowedArgs[k]; ok { |
| 174 |
filteredUserArgs[k] = v |
| 175 |
} |
| 176 |
} |
| 177 |
userArgs := mergeEnv(envMapAsSlice(filteredUserArgs), b.Env) |
| 178 |
for _, a := range flagArgs { |
| 179 |
arg, err := ProcessWord(a, userArgs) |
| 180 |
if err != nil { |
| 181 |
return err |
| 182 |
} |
| 183 |
switch { |
| 184 |
case strings.HasPrefix(arg, "--chown="): |
| 185 |
chown = strings.TrimPrefix(arg, "--chown=") |
| 186 |
if chown == "" { |
| 187 |
return fmt.Errorf("no value specified for --chown=") |
| 188 |
} |
| 189 |
case strings.HasPrefix(arg, "--chmod="): |
| 190 |
chmod = strings.TrimPrefix(arg, "--chmod=") |
| 191 |
err = checkChmodConversion(chmod) |
| 192 |
if err != nil { |
| 193 |
return err |
| 194 |
} |
| 195 |
case strings.HasPrefix(arg, "--checksum="): |
| 196 |
checksum = strings.TrimPrefix(arg, "--checksum=") |
| 197 |
if checksum == "" { |
| 198 |
return fmt.Errorf("no value specified for --checksum=") |
| 199 |
} |
| 200 |
case arg == "--link", arg == "--link=true": |
| 201 |
link = true |
| 202 |
case arg == "--link=false": |
| 203 |
link = false |
| 204 |
case arg == "--keep-git-dir", arg == "--keep-git-dir=true": |
| 205 |
keepGitDir = true |
| 206 |
case arg == "--keep-git-dir=false": |
| 207 |
keepGitDir = false |
| 208 |
case strings.HasPrefix(arg, "--exclude="): |
| 209 |
exclude := strings.TrimPrefix(arg, "--exclude=") |
| 210 |
if exclude == "" { |
| 211 |
return fmt.Errorf("no value specified for --exclude=") |
| 212 |
} |
| 213 |
excludes = append(excludes, exclude) |
| 214 |
default: |
| 215 |
return fmt.Errorf("ADD only supports the --chmod=<permissions>, --chown=<uid:gid>, --checksum=<checksum>, --link, --keep-git-dir, and --exclude=<pattern> flags") |
| 216 |
} |
| 217 |
} |
| 218 |
files, err := processHereDocs(buildkitcommand.Add, original, heredocs, userArgs) |
| 219 |
if err != nil { |
| 220 |
return err |
| 221 |
} |
| 222 |
b.PendingCopies = append(b.PendingCopies, Copy{ |
| 223 |
Src: args[0:last], |
| 224 |
Dest: dest, |
| 225 |
Download: true, |
| 226 |
Chown: chown, |
| 227 |
Chmod: chmod, |
| 228 |
Checksum: checksum, |
| 229 |
Files: files, |
| 230 |
KeepGitDir: keepGitDir, |
| 231 |
Link: link, |
| 232 |
Excludes: excludes, |
| 233 |
}) |
| 234 |
return nil |
| 235 |
} |
| 236 |
|
| 237 |
// COPY foo /path |
| 238 |
// |
| 239 |
// Same as 'ADD' but without the tar and remote url handling. |
| 240 |
func dispatchCopy(b *Builder, args []string, attributes map[string]bool, flagArgs []string, original string, heredocs []buildkitparser.Heredoc) error { |
| 241 |
if len(args) < 2 { |
| 242 |
return errAtLeastTwoArgument("COPY") |
| 243 |
} |
| 244 |
last := len(args) - 1 |
| 245 |
dest := makeAbsolute(args[last], b.RunConfig.WorkingDir) |
| 246 |
var chown string |
| 247 |
var chmod string |
| 248 |
var from string |
| 249 |
var link bool |
| 250 |
var parents bool |
| 251 |
var excludes []string |
| 252 |
filteredUserArgs := make(map[string]string) |
| 253 |
for k, v := range b.Args { |
| 254 |
if _, ok := b.AllowedArgs[k]; ok { |
| 255 |
filteredUserArgs[k] = v |
| 256 |
} |
| 257 |
} |
| 258 |
userArgs := mergeEnv(envMapAsSlice(filteredUserArgs), b.Env) |
| 259 |
for _, a := range flagArgs { |
| 260 |
arg, err := ProcessWord(a, userArgs) |
| 261 |
if err != nil { |
| 262 |
return err |
| 263 |
} |
| 264 |
switch { |
| 265 |
case strings.HasPrefix(arg, "--chown="): |
| 266 |
chown = strings.TrimPrefix(arg, "--chown=") |
| 267 |
if chown == "" { |
| 268 |
return fmt.Errorf("no value specified for --chown=") |
| 269 |
} |
| 270 |
case strings.HasPrefix(arg, "--chmod="): |
| 271 |
chmod = strings.TrimPrefix(arg, "--chmod=") |
| 272 |
err = checkChmodConversion(chmod) |
| 273 |
if err != nil { |
| 274 |
return err |
| 275 |
} |
| 276 |
case strings.HasPrefix(arg, "--from="): |
| 277 |
from = strings.TrimPrefix(arg, "--from=") |
| 278 |
if from == "" { |
| 279 |
return fmt.Errorf("no value specified for --from=") |
| 280 |
} |
| 281 |
case arg == "--link", arg == "--link=true": |
| 282 |
link = true |
| 283 |
case arg == "--link=false": |
| 284 |
link = false |
| 285 |
case arg == "--parents", arg == "--parents=true": |
| 286 |
parents = true |
| 287 |
case arg == "--parents=false": |
| 288 |
parents = false |
| 289 |
case strings.HasPrefix(arg, "--exclude="): |
| 290 |
exclude := strings.TrimPrefix(arg, "--exclude=") |
| 291 |
if exclude == "" { |
| 292 |
return fmt.Errorf("no value specified for --exclude=") |
| 293 |
} |
| 294 |
excludes = append(excludes, exclude) |
| 295 |
default: |
| 296 |
return fmt.Errorf("COPY only supports the --chmod=<permissions>, --chown=<uid:gid>, --from=<image|stage>, --link, --parents, and --exclude=<pattern> flags") |
| 297 |
} |
| 298 |
} |
| 299 |
files, err := processHereDocs(buildkitcommand.Copy, original, heredocs, userArgs) |
| 300 |
if err != nil { |
| 301 |
return err |
| 302 |
} |
| 303 |
b.PendingCopies = append(b.PendingCopies, Copy{ |
| 304 |
From: from, |
| 305 |
Src: args[0:last], |
| 306 |
Dest: dest, |
| 307 |
Download: false, |
| 308 |
Chown: chown, |
| 309 |
Chmod: chmod, |
| 310 |
Files: files, |
| 311 |
Link: link, |
| 312 |
Parents: parents, |
| 313 |
Excludes: excludes, |
| 314 |
}) |
| 315 |
return nil |
| 316 |
} |
| 317 |
|
| 318 |
// FROM imagename |
| 319 |
// |
| 320 |
// This sets the image the dockerfile will build on top of. |
| 321 |
func from(b *Builder, args []string, attributes map[string]bool, flagArgs []string, original string, heredocs []buildkitparser.Heredoc) error { |
| 322 |
switch { |
| 323 |
case len(args) == 1: |
| 324 |
case len(args) == 3 && len(args[0]) > 0 && strings.EqualFold(args[1], "as") && len(args[2]) > 0: |
| 325 |
|
| 326 |
default: |
| 327 |
return fmt.Errorf("FROM requires either one argument, or three: FROM <source> [AS <name>]") |
| 328 |
} |
| 329 |
|
| 330 |
name := args[0] |
| 331 |
|
| 332 |
// Support ARG before FROM |
| 333 |
filteredUserArgs := make(map[string]string) |
| 334 |
for k, v := range b.UserArgs { |
| 335 |
for _, a := range b.GlobalAllowedArgs { |
| 336 |
if a == k { |
| 337 |
filteredUserArgs[k] = v |
| 338 |
} |
| 339 |
} |
| 340 |
} |
| 341 |
userArgs := mergeEnv(envMapAsSlice(filteredUserArgs), b.Env) |
| 342 |
userArgs = mergeEnv(envMapAsSlice(b.BuiltinArgDefaults), userArgs) |
| 343 |
userArgs = mergeEnv(envMapAsSlice(builtinArgDefaults), userArgs) |
| 344 |
userArgs = mergeEnv(envMapAsSlice(b.HeadingArgs), userArgs) |
| 345 |
var err error |
| 346 |
if name, err = ProcessWord(name, userArgs); err != nil { |
| 347 |
return err |
| 348 |
} |
| 349 |
|
| 350 |
// Windows cannot support a container with no base image. |
| 351 |
if name == NoBaseImageSpecifier { |
| 352 |
if runtime.GOOS == "windows" { |
| 353 |
return fmt.Errorf("Windows does not support FROM scratch") |
| 354 |
} |
| 355 |
} |
| 356 |
for _, a := range flagArgs { |
| 357 |
arg, err := ProcessWord(a, userArgs) |
| 358 |
if err != nil { |
| 359 |
return err |
| 360 |
} |
| 361 |
switch { |
| 362 |
case strings.HasPrefix(arg, "--platform="): |
| 363 |
platformString := strings.TrimPrefix(arg, "--platform=") |
| 364 |
if platformString == "" { |
| 365 |
return fmt.Errorf("no value specified for --platform=") |
| 366 |
} |
| 367 |
b.Platform = platformString |
| 368 |
case strings.HasPrefix(arg, "--after="): |
| 369 |
afterStage := strings.TrimPrefix(arg, "--after=") |
| 370 |
if afterStage == "" { |
| 371 |
return fmt.Errorf("no value specified for --after=") |
| 372 |
} |
| 373 |
b.After = afterStage |
| 374 |
default: |
| 375 |
return fmt.Errorf("FROM only supports the --platform and --after flags") |
| 376 |
} |
| 377 |
} |
| 378 |
b.RunConfig.Image = name |
| 379 |
// TODO: handle onbuild |
| 380 |
return nil |
| 381 |
} |
| 382 |
|
| 383 |
// ONBUILD RUN echo yo |
| 384 |
// |
| 385 |
// ONBUILD triggers run when the image is used in a FROM statement. |
| 386 |
// |
| 387 |
// ONBUILD handling has a lot of special-case functionality, the heading in |
| 388 |
// evaluator.go and comments around dispatch() in the same file explain the |
| 389 |
// special cases. search for 'OnBuild' in internals.go for additional special |
| 390 |
// cases. |
| 391 |
func onbuild(b *Builder, args []string, attributes map[string]bool, flagArgs []string, original string, heredocs []buildkitparser.Heredoc) error { |
| 392 |
if len(args) == 0 { |
| 393 |
return errAtLeastOneArgument("ONBUILD") |
| 394 |
} |
| 395 |
|
| 396 |
triggerInstruction := strings.ToUpper(strings.TrimSpace(args[0])) |
| 397 |
switch triggerInstruction { |
| 398 |
case "ONBUILD": |
| 399 |
return fmt.Errorf("Chaining ONBUILD via `ONBUILD ONBUILD` isn't allowed") |
| 400 |
case "MAINTAINER", "FROM": |
| 401 |
return fmt.Errorf("%s isn't allowed as an ONBUILD trigger", triggerInstruction) |
| 402 |
} |
| 403 |
|
| 404 |
original = obRgex.ReplaceAllString(original, "") |
| 405 |
|
| 406 |
b.RunConfig.OnBuild = append(b.RunConfig.OnBuild, original) |
| 407 |
return nil |
| 408 |
} |
| 409 |
|
| 410 |
// WORKDIR /tmp |
| 411 |
// |
| 412 |
// Set the working directory for future RUN/CMD/etc statements. |
| 413 |
func workdir(b *Builder, args []string, attributes map[string]bool, flagArgs []string, original string, heredocs []buildkitparser.Heredoc) error { |
| 414 |
if len(args) != 1 { |
| 415 |
return errExactlyOneArgument("WORKDIR") |
| 416 |
} |
| 417 |
|
| 418 |
// This is from the Dockerfile and will not necessarily be in platform |
| 419 |
// specific semantics, hence ensure it is converted. |
| 420 |
workdir := filepath.FromSlash(args[0]) |
| 421 |
|
| 422 |
if !filepath.IsAbs(workdir) { |
| 423 |
current := filepath.FromSlash(b.RunConfig.WorkingDir) |
| 424 |
workdir = filepath.Join(string(os.PathSeparator), current, workdir) |
| 425 |
} |
| 426 |
|
| 427 |
if workdir != string(os.PathSeparator) { |
| 428 |
workdir = strings.TrimSuffix(workdir, string(os.PathSeparator)) |
| 429 |
} |
| 430 |
|
| 431 |
b.RunConfig.WorkingDir = workdir |
| 432 |
return nil |
| 433 |
} |
| 434 |
|
| 435 |
// RUN some command yo |
| 436 |
// |
| 437 |
// run a command and commit the image. Args are automatically prepended with |
| 438 |
// 'sh -c' under linux or 'cmd /S /C' under Windows, in the event there is |
| 439 |
// only one argument. The difference in processing: |
| 440 |
// |
| 441 |
// RUN echo hi # sh -c echo hi (Linux) |
| 442 |
// RUN echo hi # cmd /S /C echo hi (Windows) |
| 443 |
// RUN [ "echo", "hi" ] # echo hi |
| 444 |
func run(b *Builder, args []string, attributes map[string]bool, flagArgs []string, original string, heredocs []buildkitparser.Heredoc) error { |
| 445 |
if b.RunConfig.Image == "" { |
| 446 |
return fmt.Errorf("Please provide a source image with `from` prior to run") |
| 447 |
} |
| 448 |
|
| 449 |
args = handleJSONArgs(args, attributes) |
| 450 |
|
| 451 |
var mounts []string |
| 452 |
var network string |
| 453 |
filteredUserArgs := make(map[string]string) |
| 454 |
for k, v := range b.Args { |
| 455 |
if _, ok := b.AllowedArgs[k]; ok { |
| 456 |
filteredUserArgs[k] = v |
| 457 |
} |
| 458 |
} |
| 459 |
userArgs := mergeEnv(envMapAsSlice(filteredUserArgs), b.Env) |
| 460 |
for _, a := range flagArgs { |
| 461 |
arg, err := ProcessWord(a, userArgs) |
| 462 |
if err != nil { |
| 463 |
return err |
| 464 |
} |
| 465 |
switch { |
| 466 |
case strings.HasPrefix(arg, "--mount="): |
| 467 |
mount := strings.TrimPrefix(arg, "--mount=") |
| 468 |
if mount == "" { |
| 469 |
return fmt.Errorf("no value specified for --mount=") |
| 470 |
} |
| 471 |
mounts = append(mounts, mount) |
| 472 |
case strings.HasPrefix(arg, "--network="): |
| 473 |
network = strings.TrimPrefix(arg, "--network=") |
| 474 |
if network == "" { |
| 475 |
return fmt.Errorf("no value specified for --network=") |
| 476 |
} |
| 477 |
default: |
| 478 |
return fmt.Errorf("RUN only supports the --mount and --network flag") |
| 479 |
} |
| 480 |
} |
| 481 |
|
| 482 |
files, err := processHereDocs(buildkitcommand.Run, original, heredocs, userArgs) |
| 483 |
if err != nil { |
| 484 |
return err |
| 485 |
} |
| 486 |
|
| 487 |
run := Run{ |
| 488 |
Args: args, |
| 489 |
Mounts: mounts, |
| 490 |
Network: network, |
| 491 |
Files: files, |
| 492 |
} |
| 493 |
|
| 494 |
if !attributes["json"] { |
| 495 |
run.Shell = true |
| 496 |
} |
| 497 |
b.PendingRuns = append(b.PendingRuns, run) |
| 498 |
return nil |
| 499 |
} |
| 500 |
|
| 501 |
// CMD foo |
| 502 |
// |
| 503 |
// Set the default command to run in the container (which may be empty). |
| 504 |
// Argument handling is the same as RUN. |
| 505 |
func cmd(b *Builder, args []string, attributes map[string]bool, flagArgs []string, original string, heredocs []buildkitparser.Heredoc) error { |
| 506 |
cmdSlice := handleJSONArgs(args, attributes) |
| 507 |
|
| 508 |
if !attributes["json"] { |
| 509 |
if runtime.GOOS != "windows" { |
| 510 |
cmdSlice = append([]string{"/bin/sh", "-c"}, cmdSlice...) |
| 511 |
} else { |
| 512 |
cmdSlice = append([]string{"cmd", "/S", "/C"}, cmdSlice...) |
| 513 |
} |
| 514 |
} |
| 515 |
|
| 516 |
b.RunConfig.Cmd = strslice.StrSlice(cmdSlice) |
| 517 |
if len(args) != 0 { |
| 518 |
b.CmdSet = true |
| 519 |
} |
| 520 |
return nil |
| 521 |
} |
| 522 |
|
| 523 |
// ENTRYPOINT /usr/sbin/nginx |
| 524 |
// |
| 525 |
// Set the entrypoint (which defaults to sh -c on linux, or cmd /S /C on Windows) to |
| 526 |
// /usr/sbin/nginx. Will accept the CMD as the arguments to /usr/sbin/nginx. |
| 527 |
// |
| 528 |
// Handles command processing similar to CMD and RUN, only b.RunConfig.Entrypoint |
| 529 |
// is initialized at NewBuilder time instead of through argument parsing. |
| 530 |
func entrypoint(b *Builder, args []string, attributes map[string]bool, flagArgs []string, original string, heredocs []buildkitparser.Heredoc) error { |
| 531 |
parsed := handleJSONArgs(args, attributes) |
| 532 |
|
| 533 |
switch { |
| 534 |
case attributes["json"]: |
| 535 |
// ENTRYPOINT ["echo", "hi"] |
| 536 |
b.RunConfig.Entrypoint = strslice.StrSlice(parsed) |
| 537 |
case len(parsed) == 0: |
| 538 |
// ENTRYPOINT [] |
| 539 |
b.RunConfig.Entrypoint = nil |
| 540 |
default: |
| 541 |
// ENTRYPOINT echo hi |
| 542 |
if runtime.GOOS != "windows" { |
| 543 |
b.RunConfig.Entrypoint = strslice.StrSlice{"/bin/sh", "-c", parsed[0]} |
| 544 |
} else { |
| 545 |
b.RunConfig.Entrypoint = strslice.StrSlice{"cmd", "/S", "/C", parsed[0]} |
| 546 |
} |
| 547 |
} |
| 548 |
|
| 549 |
// when setting the entrypoint if a CMD was not explicitly set then |
| 550 |
// set the command to nil |
| 551 |
if !b.CmdSet { |
| 552 |
b.RunConfig.Cmd = nil |
| 553 |
} |
| 554 |
return nil |
| 555 |
} |
| 556 |
|
| 557 |
// EXPOSE 6667/tcp 7000/tcp |
| 558 |
// |
| 559 |
// Expose ports for links and port mappings. This all ends up in |
| 560 |
// b.RunConfig.ExposedPorts for runconfig. |
| 561 |
func expose(b *Builder, args []string, attributes map[string]bool, flagArgs []string, original string, heredocs []buildkitparser.Heredoc) error { |
| 562 |
if len(args) == 0 { |
| 563 |
return errAtLeastOneArgument("EXPOSE") |
| 564 |
} |
| 565 |
|
| 566 |
if b.RunConfig.ExposedPorts == nil { |
| 567 |
b.RunConfig.ExposedPorts = make(map[docker.Port]struct{}) |
| 568 |
} |
| 569 |
|
| 570 |
existing := map[string]struct{}{} |
| 571 |
for k := range b.RunConfig.ExposedPorts { |
| 572 |
existing[k.Port()+"/"+k.Proto()] = struct{}{} |
| 573 |
} |
| 574 |
|
| 575 |
for _, port := range args { |
| 576 |
dp := docker.Port(port) |
| 577 |
if _, exists := existing[dp.Port()+"/"+dp.Proto()]; !exists { |
| 578 |
b.RunConfig.ExposedPorts[docker.Port(fmt.Sprintf("%s/%s", dp.Port(), dp.Proto()))] = struct{}{} |
| 579 |
} |
| 580 |
} |
| 581 |
return nil |
| 582 |
} |
| 583 |
|
| 584 |
// USER foo |
| 585 |
// |
| 586 |
// Set the user to 'foo' for future commands and when running the |
| 587 |
// ENTRYPOINT/CMD at container run time. |
| 588 |
func user(b *Builder, args []string, attributes map[string]bool, flagArgs []string, original string, heredocs []buildkitparser.Heredoc) error { |
| 589 |
if len(args) != 1 { |
| 590 |
return errExactlyOneArgument("USER") |
| 591 |
} |
| 592 |
|
| 593 |
b.RunConfig.User = args[0] |
| 594 |
return nil |
| 595 |
} |
| 596 |
|
| 597 |
// VOLUME /foo |
| 598 |
// |
| 599 |
// Expose the volume /foo for use. Will also accept the JSON array form. |
| 600 |
func volume(b *Builder, args []string, attributes map[string]bool, flagArgs []string, original string, heredocs []buildkitparser.Heredoc) error { |
| 601 |
if len(args) == 0 { |
| 602 |
return errAtLeastOneArgument("VOLUME") |
| 603 |
} |
| 604 |
|
| 605 |
if b.RunConfig.Volumes == nil { |
| 606 |
b.RunConfig.Volumes = map[string]struct{}{} |
| 607 |
} |
| 608 |
for _, v := range args { |
| 609 |
v = strings.TrimSpace(v) |
| 610 |
if v == "" { |
| 611 |
return fmt.Errorf("Volume specified can not be an empty string") |
| 612 |
} |
| 613 |
b.RunConfig.Volumes[v] = struct{}{} |
| 614 |
b.PendingVolumes.Add(v) |
| 615 |
} |
| 616 |
return nil |
| 617 |
} |
| 618 |
|
| 619 |
// STOPSIGNAL signal |
| 620 |
// |
| 621 |
// Set the signal that will be used to kill the container. |
| 622 |
func stopSignal(b *Builder, args []string, attributes map[string]bool, flagArgs []string, original string, heredocs []buildkitparser.Heredoc) error { |
| 623 |
if len(args) != 1 { |
| 624 |
return errExactlyOneArgument("STOPSIGNAL") |
| 625 |
} |
| 626 |
|
| 627 |
sig := args[0] |
| 628 |
if err := signal.CheckSignal(sig); err != nil { |
| 629 |
return err |
| 630 |
} |
| 631 |
|
| 632 |
b.RunConfig.StopSignal = sig |
| 633 |
return nil |
| 634 |
} |
| 635 |
|
| 636 |
// HEALTHCHECK foo |
| 637 |
// |
| 638 |
// Set the default healthcheck command to run in the container (which may be empty). |
| 639 |
// Argument handling is the same as RUN. |
| 640 |
func healthcheck(b *Builder, args []string, attributes map[string]bool, flagArgs []string, original string, heredocs []buildkitparser.Heredoc) error { |
| 641 |
if len(args) == 0 { |
| 642 |
return errAtLeastOneArgument("HEALTHCHECK") |
| 643 |
} |
| 644 |
typ := strings.ToUpper(args[0]) |
| 645 |
args = args[1:] |
| 646 |
if typ == "NONE" { |
| 647 |
if len(args) != 0 { |
| 648 |
return fmt.Errorf("HEALTHCHECK NONE takes no arguments") |
| 649 |
} |
| 650 |
test := strslice.StrSlice{typ} |
| 651 |
b.RunConfig.Healthcheck = &docker.HealthConfig{ |
| 652 |
Test: test, |
| 653 |
} |
| 654 |
} else { |
| 655 |
if b.RunConfig.Healthcheck != nil { |
| 656 |
oldCmd := b.RunConfig.Healthcheck.Test |
| 657 |
if len(oldCmd) > 0 && oldCmd[0] != "NONE" { |
| 658 |
b.Warnings = append(b.Warnings, fmt.Sprintf("Note: overriding previous HEALTHCHECK: %v\n", oldCmd)) |
| 659 |
} |
| 660 |
} |
| 661 |
|
| 662 |
healthcheck := docker.HealthConfig{} |
| 663 |
|
| 664 |
flags := flag.NewFlagSet("", flag.ContinueOnError) |
| 665 |
flags.String("start-period", "", "") |
| 666 |
flags.String("start-interval", "", "") |
| 667 |
flags.String("interval", "", "") |
| 668 |
flags.String("timeout", "", "") |
| 669 |
flRetries := flags.String("retries", "", "") |
| 670 |
|
| 671 |
if err := flags.Parse(flagArgs); err != nil { |
| 672 |
return err |
| 673 |
} |
| 674 |
|
| 675 |
switch typ { |
| 676 |
case "CMD": |
| 677 |
cmdSlice := handleJSONArgs(args, attributes) |
| 678 |
if len(cmdSlice) == 0 { |
| 679 |
return fmt.Errorf("Missing command after HEALTHCHECK CMD") |
| 680 |
} |
| 681 |
|
| 682 |
if !attributes["json"] { |
| 683 |
typ = "CMD-SHELL" |
| 684 |
} |
| 685 |
|
| 686 |
healthcheck.Test = strslice.StrSlice(append([]string{typ}, cmdSlice...)) |
| 687 |
default: |
| 688 |
return fmt.Errorf("Unknown type %#v in HEALTHCHECK (try CMD)", typ) |
| 689 |
} |
| 690 |
|
| 691 |
period, err := parseOptInterval(flags.Lookup("start-period")) |
| 692 |
if err != nil { |
| 693 |
return err |
| 694 |
} |
| 695 |
healthcheck.StartPeriod = period |
| 696 |
|
| 697 |
interval, err := parseOptInterval(flags.Lookup("interval")) |
| 698 |
if err != nil { |
| 699 |
return err |
| 700 |
} |
| 701 |
healthcheck.Interval = interval |
| 702 |
|
| 703 |
startInterval, err := parseOptInterval(flags.Lookup("start-interval")) |
| 704 |
if err != nil { |
| 705 |
return err |
| 706 |
} |
| 707 |
healthcheck.StartInterval = startInterval |
| 708 |
|
| 709 |
timeout, err := parseOptInterval(flags.Lookup("timeout")) |
| 710 |
if err != nil { |
| 711 |
return err |
| 712 |
} |
| 713 |
healthcheck.Timeout = timeout |
| 714 |
|
| 715 |
if *flRetries != "" { |
| 716 |
retries, err := strconv.ParseInt(*flRetries, 10, 32) |
| 717 |
if err != nil { |
| 718 |
return err |
| 719 |
} |
| 720 |
if retries < 1 { |
| 721 |
return fmt.Errorf("--retries must be at least 1 (not %d)", retries) |
| 722 |
} |
| 723 |
healthcheck.Retries = int(retries) |
| 724 |
} else { |
| 725 |
healthcheck.Retries = 0 |
| 726 |
} |
| 727 |
b.RunConfig.Healthcheck = &healthcheck |
| 728 |
} |
| 729 |
|
| 730 |
return nil |
| 731 |
} |
| 732 |
|
| 733 |
// ARG name[=value] |
| 734 |
// |
| 735 |
// Adds the variable foo to the trusted list of variables that can be passed |
| 736 |
// to builder using the --build-arg flag for expansion/subsitution or passing to 'run'. |
| 737 |
// Dockerfile author may optionally set a default value of this variable. |
| 738 |
func arg(b *Builder, args []string, attributes map[string]bool, flagArgs []string, original string, heredocs []buildkitparser.Heredoc) error { |
| 739 |
for _, argument := range args { |
| 740 |
var ( |
| 741 |
name string |
| 742 |
defaultValue string |
| 743 |
haveDefault bool |
| 744 |
) |
| 745 |
arg := argument |
| 746 |
// 'arg' can just be a name or name-value pair. Note that this is different |
| 747 |
// from 'env' that handles the split of name and value at the parser level. |
| 748 |
// The reason for doing it differently for 'arg' is that we support just |
| 749 |
// defining an arg without assigning it a value (while 'env' always expects a |
| 750 |
// name-value pair). If possible, it will be good to harmonize the two. |
| 751 |
name, defaultValue, haveDefault = strings.Cut(arg, "=") |
| 752 |
|
| 753 |
// add the arg to allowed list of build-time args from this step on. |
| 754 |
b.AllowedArgs[name] = true |
| 755 |
|
| 756 |
// If the stage introduces one of the predefined args, add the |
| 757 |
// predefined value to the list of values known in this stage |
| 758 |
if value, defined := builtinArgDefaults[name]; defined { |
| 759 |
if haveDefault && (name == "TARGETPLATFORM" || name == "BUILDPLATFORM") { |
| 760 |
return fmt.Errorf("attempted to redefine %q: %w", name, errdefs.ErrInvalidArgument) |
| 761 |
} |
| 762 |
if b.BuiltinArgDefaults == nil { |
| 763 |
b.BuiltinArgDefaults = make(map[string]string) |
| 764 |
} |
| 765 |
// N.B.: we're only consulting b.BuiltinArgDefaults for |
| 766 |
// values that correspond to keys in |
| 767 |
// builtinArgDefaults, which keeps the caller from |
| 768 |
// using it to sneak in arbitrary ARG values |
| 769 |
if _, setByUser := b.UserArgs[name]; !setByUser && defined { |
| 770 |
if builderValue, builderDefined := b.BuiltinArgDefaults[name]; builderDefined { |
| 771 |
b.Args[name] = builderValue |
| 772 |
} else { |
| 773 |
b.Args[name] = value |
| 774 |
} |
| 775 |
} |
| 776 |
continue |
| 777 |
} |
| 778 |
|
| 779 |
// If there is still no default value, check for a default value from the heading args |
| 780 |
if !haveDefault { |
| 781 |
defaultValue, haveDefault = b.HeadingArgs[name] |
| 782 |
} |
| 783 |
|
| 784 |
// If there is a default value provided for this arg, and the user didn't supply |
| 785 |
// a value, then set the default value in b.Args. Later defaults given for the |
| 786 |
// same arg override earlier ones. The args passed to the builder (UserArgs) override |
| 787 |
// any default values of 'arg', so don't set them here as they were already set |
| 788 |
// in NewBuilder(). |
| 789 |
if _, setByUser := b.UserArgs[name]; !setByUser && haveDefault { |
| 790 |
b.Args[name] = defaultValue |
| 791 |
} |
| 792 |
} |
| 793 |
|
| 794 |
return nil |
| 795 |
} |
| 796 |
|
| 797 |
// SHELL powershell -command |
| 798 |
// |
| 799 |
// Set the non-default shell to use. |
| 800 |
func shell(b *Builder, args []string, attributes map[string]bool, flagArgs []string, original string, heredocs []buildkitparser.Heredoc) error { |
| 801 |
shellSlice := handleJSONArgs(args, attributes) |
| 802 |
switch { |
| 803 |
case len(shellSlice) == 0: |
| 804 |
// SHELL [] |
| 805 |
return errAtLeastOneArgument("SHELL") |
| 806 |
case attributes["json"]: |
| 807 |
// SHELL ["powershell", "-command"] |
| 808 |
b.RunConfig.Shell = strslice.StrSlice(shellSlice) |
| 809 |
// b.RunConfig.Shell = strslice.StrSlice(shellSlice) |
| 810 |
default: |
| 811 |
// SHELL powershell -command - not JSON |
| 812 |
return errNotJSON("SHELL") |
| 813 |
} |
| 814 |
return nil |
| 815 |
} |
| 816 |
|
| 817 |
// checkChmodConversion makes sure that the argument to a --chmod= flag for |
| 818 |
// COPY or ADD is an octal number between 0 and 07777 or a symbolic mode, |
| 819 |
// both of which the dockerfile frontend spec accepts since Dockerfile |
| 820 |
// syntax 1.14. Parsing here only validates the syntax: the clauses are |
| 821 |
// resolved against each copied file's current mode by the executor, which |
| 822 |
// is where conditional bits such as the capital X in a+rX are meaningful. |
| 823 |
func checkChmodConversion(chmod string) error { |
| 824 |
if v, err := strconv.ParseUint(chmod, 8, 32); err == nil { |
| 825 |
if v > 0o7777 { |
| 826 |
return fmt.Errorf("Error parsing chmod %s: it should be octal and between 0 and 07777", chmod) |
| 827 |
} |
| 828 |
return nil |
| 829 |
} |
| 830 |
if _, err := mode.Parse(chmod); err != nil { |
| 831 |
return fmt.Errorf("Error parsing chmod %s: %w", chmod, err) |
| 832 |
} |
| 833 |
return nil |
| 834 |
} |
| 835 |
|
| 836 |
func errAtLeastOneArgument(command string) error { |
| 837 |
return fmt.Errorf("%s requires at least one argument", command) |
| 838 |
} |
| 839 |
|
| 840 |
func errAtLeastTwoArgument(command string) error { |
| 841 |
return fmt.Errorf("%s requires at least two arguments", command) |
| 842 |
} |
| 843 |
|
| 844 |
func errExactlyOneArgument(command string) error { |
| 845 |
return fmt.Errorf("%s requires exactly one argument", command) |
| 846 |
} |
| 847 |
|
| 848 |
func errTooManyArguments(command string) error { |
| 849 |
return fmt.Errorf("Bad input to %s, too many arguments", command) |
| 850 |
} |
| 851 |
|
| 852 |
func errNotJSON(command string) error { |
| 853 |
return fmt.Errorf("%s requires the arguments to be in JSON form", command) |
| 854 |
} |