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
|
package imagebuilder
// This file contains the dispatchers for each command. Note that
// `nullDispatch` is not actually a command, but support for commands we parse
// but do nothing with.
//
// See evaluator.go for a higher level discussion of the whole evaluator
// package.
import (
"flag"
"fmt"
"os"
"path/filepath"
"runtime"
"strconv"
"strings"
docker "github.com/fsouza/go-dockerclient"
"github.com/containerd/errdefs"
"github.com/containerd/platforms"
"github.com/containers/storage/pkg/regexp"
"github.com/openshift/imagebuilder/internal"
"github.com/openshift/imagebuilder/signal"
"github.com/openshift/imagebuilder/strslice"
buildkitcommand "github.com/moby/buildkit/frontend/dockerfile/command"
buildkitparser "github.com/moby/buildkit/frontend/dockerfile/parser"
buildkitshell "github.com/moby/buildkit/frontend/dockerfile/shell"
)
var (
obRgex = regexp.Delayed(`(?i)^\s*ONBUILD\s*`)
)
var localspec = platforms.DefaultSpec()
// https://docs.docker.com/engine/reference/builder/#automatic-platform-args-in-the-global-scope
var builtinArgDefaults = map[string]string{
"TARGETPLATFORM": localspec.OS + "/" + localspec.Architecture,
"TARGETOS": localspec.OS,
"TARGETARCH": localspec.Architecture,
"TARGETVARIANT": localspec.Variant,
"BUILDPLATFORM": localspec.OS + "/" + localspec.Architecture,
"BUILDOS": localspec.OS,
"BUILDARCH": localspec.Architecture,
"BUILDVARIANT": localspec.Variant,
}
func init() {
if localspec.Variant != "" {
builtinArgDefaults["TARGETPLATFORM"] = builtinArgDefaults["TARGETPLATFORM"] + "/" + localspec.Variant
builtinArgDefaults["BUILDPLATFORM"] = builtinArgDefaults["BUILDPLATFORM"] + "/" + localspec.Variant
}
}
// ENV foo bar
//
// Sets the environment variable foo to bar, also makes interpolation
// in the dockerfile available from the next statement on via ${foo}.
func env(b *Builder, args []string, attributes map[string]bool, flagArgs []string, original string, heredocs []buildkitparser.Heredoc) error {
if len(args) == 0 {
return errAtLeastOneArgument("ENV")
}
if len(args)%2 != 0 {
// should never get here, but just in case
return errTooManyArguments("ENV")
}
// TODO/FIXME/NOT USED
// Just here to show how to use the builder flags stuff within the
// context of a builder command. Will remove once we actually add
// a builder command to something!
/*
flBool1 := b.flags.AddBool("bool1", false)
flStr1 := b.flags.AddString("str1", "HI")
if err := b.flags.Parse(); err != nil {
return err
}
fmt.Printf("Bool1:%v\n", flBool1)
fmt.Printf("Str1:%v\n", flStr1)
*/
for j := 0; j+1 < len(args); j += 2 {
// name ==> args[j]
// value ==> args[j+1]
newVar := []string{args[j] + "=" + args[j+1]}
b.RunConfig.Env = mergeEnv(b.RunConfig.Env, newVar)
b.Env = mergeEnv(b.Env, newVar)
}
return nil
}
// MAINTAINER some text <maybe@an.email.address>
//
// Sets the maintainer metadata.
func maintainer(b *Builder, args []string, attributes map[string]bool, flagArgs []string, original string, heredocs []buildkitparser.Heredoc) error {
if len(args) != 1 {
return errExactlyOneArgument("MAINTAINER")
}
b.Author = args[0]
return nil
}
// LABEL some json data describing the image
//
// Sets the Label variable foo to bar,
func label(b *Builder, args []string, attributes map[string]bool, flagArgs []string, original string, heredocs []buildkitparser.Heredoc) error {
if len(args) == 0 {
return errAtLeastOneArgument("LABEL")
}
if len(args)%2 != 0 {
// should never get here, but just in case
return errTooManyArguments("LABEL")
}
if b.RunConfig.Labels == nil {
b.RunConfig.Labels = map[string]string{}
}
for j := 0; j < len(args); j++ {
// name ==> args[j]
// value ==> args[j+1]
b.RunConfig.Labels[args[j]] = args[j+1]
j++
}
return nil
}
func processHereDocs(instruction, originalInstruction string, heredocs []buildkitparser.Heredoc, args []string) ([]File, error) {
var files []File
for _, heredoc := range heredocs {
var err error
content := heredoc.Content
if heredoc.Chomp {
content = buildkitparser.ChompHeredocContent(content)
}
if heredoc.Expand && !strings.EqualFold(instruction, buildkitcommand.Run) {
shlex := buildkitshell.NewLex('\\')
shlex.RawQuotes = true
shlex.RawEscapes = true
content, _, err = shlex.ProcessWord(content, internal.EnvironmentSlice(args))
if err != nil {
return nil, err
}
}
file := File{
Data: content,
Name: heredoc.Name,
}
files = append(files, file)
}
return files, nil
}
// ADD foo /path
//
// Add the file 'foo' to '/path'. Tarball and Remote URL (git, http) handling
// exist here. If you do not wish to have this automatic handling, use COPY.
func add(b *Builder, args []string, attributes map[string]bool, flagArgs []string, original string, heredocs []buildkitparser.Heredoc) error {
if len(args) < 2 {
return errAtLeastTwoArgument("ADD")
}
var chown string
var chmod string
var checksum string
var keepGitDir bool
var link bool
var excludes []string
last := len(args) - 1
dest := makeAbsolute(args[last], b.RunConfig.WorkingDir)
filteredUserArgs := make(map[string]string)
for k, v := range b.Args {
if _, ok := b.AllowedArgs[k]; ok {
filteredUserArgs[k] = v
}
}
userArgs := mergeEnv(envMapAsSlice(filteredUserArgs), b.Env)
for _, a := range flagArgs {
arg, err := ProcessWord(a, userArgs)
if err != nil {
return err
}
switch {
case strings.HasPrefix(arg, "--chown="):
chown = strings.TrimPrefix(arg, "--chown=")
if chown == "" {
return fmt.Errorf("no value specified for --chown=")
}
case strings.HasPrefix(arg, "--chmod="):
chmod = strings.TrimPrefix(arg, "--chmod=")
err = checkChmodConversion(chmod)
if err != nil {
return err
}
case strings.HasPrefix(arg, "--checksum="):
checksum = strings.TrimPrefix(arg, "--checksum=")
if checksum == "" {
return fmt.Errorf("no value specified for --checksum=")
}
case arg == "--link", arg == "--link=true":
link = true
case arg == "--link=false":
link = false
case arg == "--keep-git-dir", arg == "--keep-git-dir=true":
keepGitDir = true
case arg == "--keep-git-dir=false":
keepGitDir = false
case strings.HasPrefix(arg, "--exclude="):
exclude := strings.TrimPrefix(arg, "--exclude=")
if exclude == "" {
return fmt.Errorf("no value specified for --exclude=")
}
excludes = append(excludes, exclude)
default:
return fmt.Errorf("ADD only supports the --chmod=<permissions>, --chown=<uid:gid>, --checksum=<checksum>, --link, --keep-git-dir, and --exclude=<pattern> flags")
}
}
files, err := processHereDocs(buildkitcommand.Add, original, heredocs, userArgs)
if err != nil {
return err
}
b.PendingCopies = append(b.PendingCopies, Copy{
Src: args[0:last],
Dest: dest,
Download: true,
Chown: chown,
Chmod: chmod,
Checksum: checksum,
Files: files,
KeepGitDir: keepGitDir,
Link: link,
Excludes: excludes,
})
return nil
}
// COPY foo /path
//
// Same as 'ADD' but without the tar and remote url handling.
func dispatchCopy(b *Builder, args []string, attributes map[string]bool, flagArgs []string, original string, heredocs []buildkitparser.Heredoc) error {
if len(args) < 2 {
return errAtLeastTwoArgument("COPY")
}
last := len(args) - 1
dest := makeAbsolute(args[last], b.RunConfig.WorkingDir)
var chown string
var chmod string
var from string
var link bool
var parents bool
var excludes []string
filteredUserArgs := make(map[string]string)
for k, v := range b.Args {
if _, ok := b.AllowedArgs[k]; ok {
filteredUserArgs[k] = v
}
}
userArgs := mergeEnv(envMapAsSlice(filteredUserArgs), b.Env)
for _, a := range flagArgs {
arg, err := ProcessWord(a, userArgs)
if err != nil {
return err
}
switch {
case strings.HasPrefix(arg, "--chown="):
chown = strings.TrimPrefix(arg, "--chown=")
if chown == "" {
return fmt.Errorf("no value specified for --chown=")
}
case strings.HasPrefix(arg, "--chmod="):
chmod = strings.TrimPrefix(arg, "--chmod=")
err = checkChmodConversion(chmod)
if err != nil {
return err
}
case strings.HasPrefix(arg, "--from="):
from = strings.TrimPrefix(arg, "--from=")
if from == "" {
return fmt.Errorf("no value specified for --from=")
}
case arg == "--link", arg == "--link=true":
link = true
case arg == "--link=false":
link = false
case arg == "--parents", arg == "--parents=true":
parents = true
case arg == "--parents=false":
parents = false
case strings.HasPrefix(arg, "--exclude="):
exclude := strings.TrimPrefix(arg, "--exclude=")
if exclude == "" {
return fmt.Errorf("no value specified for --exclude=")
}
excludes = append(excludes, exclude)
default:
return fmt.Errorf("COPY only supports the --chmod=<permissions>, --chown=<uid:gid>, --from=<image|stage>, --link, --parents, and --exclude=<pattern> flags")
}
}
files, err := processHereDocs(buildkitcommand.Copy, original, heredocs, userArgs)
if err != nil {
return err
}
b.PendingCopies = append(b.PendingCopies, Copy{
From: from,
Src: args[0:last],
Dest: dest,
Download: false,
Chown: chown,
Chmod: chmod,
Files: files,
Link: link,
Parents: parents,
Excludes: excludes,
})
return nil
}
// FROM imagename
//
// This sets the image the dockerfile will build on top of.
func from(b *Builder, args []string, attributes map[string]bool, flagArgs []string, original string, heredocs []buildkitparser.Heredoc) error {
switch {
case len(args) == 1:
case len(args) == 3 && len(args[0]) > 0 && strings.EqualFold(args[1], "as") && len(args[2]) > 0:
default:
return fmt.Errorf("FROM requires either one argument, or three: FROM <source> [AS <name>]")
}
name := args[0]
// Support ARG before FROM
filteredUserArgs := make(map[string]string)
for k, v := range b.UserArgs {
for _, a := range b.GlobalAllowedArgs {
if a == k {
filteredUserArgs[k] = v
}
}
}
userArgs := mergeEnv(envMapAsSlice(filteredUserArgs), b.Env)
userArgs = mergeEnv(envMapAsSlice(b.BuiltinArgDefaults), userArgs)
userArgs = mergeEnv(envMapAsSlice(builtinArgDefaults), userArgs)
userArgs = mergeEnv(envMapAsSlice(b.HeadingArgs), userArgs)
var err error
if name, err = ProcessWord(name, userArgs); err != nil {
return err
}
// Windows cannot support a container with no base image.
if name == NoBaseImageSpecifier {
if runtime.GOOS == "windows" {
return fmt.Errorf("Windows does not support FROM scratch")
}
}
for _, a := range flagArgs {
arg, err := ProcessWord(a, userArgs)
if err != nil {
return err
}
switch {
case strings.HasPrefix(arg, "--platform="):
platformString := strings.TrimPrefix(arg, "--platform=")
if platformString == "" {
return fmt.Errorf("no value specified for --platform=")
}
b.Platform = platformString
default:
return fmt.Errorf("FROM only supports the --platform flag")
}
}
b.RunConfig.Image = name
// TODO: handle onbuild
return nil
}
// ONBUILD RUN echo yo
//
// ONBUILD triggers run when the image is used in a FROM statement.
//
// ONBUILD handling has a lot of special-case functionality, the heading in
// evaluator.go and comments around dispatch() in the same file explain the
// special cases. search for 'OnBuild' in internals.go for additional special
// cases.
func onbuild(b *Builder, args []string, attributes map[string]bool, flagArgs []string, original string, heredocs []buildkitparser.Heredoc) error {
if len(args) == 0 {
return errAtLeastOneArgument("ONBUILD")
}
triggerInstruction := strings.ToUpper(strings.TrimSpace(args[0]))
switch triggerInstruction {
case "ONBUILD":
return fmt.Errorf("Chaining ONBUILD via `ONBUILD ONBUILD` isn't allowed")
case "MAINTAINER", "FROM":
return fmt.Errorf("%s isn't allowed as an ONBUILD trigger", triggerInstruction)
}
original = obRgex.ReplaceAllString(original, "")
b.RunConfig.OnBuild = append(b.RunConfig.OnBuild, original)
return nil
}
// WORKDIR /tmp
//
// Set the working directory for future RUN/CMD/etc statements.
func workdir(b *Builder, args []string, attributes map[string]bool, flagArgs []string, original string, heredocs []buildkitparser.Heredoc) error {
if len(args) != 1 {
return errExactlyOneArgument("WORKDIR")
}
// This is from the Dockerfile and will not necessarily be in platform
// specific semantics, hence ensure it is converted.
workdir := filepath.FromSlash(args[0])
if !filepath.IsAbs(workdir) {
current := filepath.FromSlash(b.RunConfig.WorkingDir)
workdir = filepath.Join(string(os.PathSeparator), current, workdir)
}
if workdir != string(os.PathSeparator) {
workdir = strings.TrimSuffix(workdir, string(os.PathSeparator))
}
b.RunConfig.WorkingDir = workdir
return nil
}
// RUN some command yo
//
// run a command and commit the image. Args are automatically prepended with
// 'sh -c' under linux or 'cmd /S /C' under Windows, in the event there is
// only one argument. The difference in processing:
//
// RUN echo hi # sh -c echo hi (Linux)
// RUN echo hi # cmd /S /C echo hi (Windows)
// RUN [ "echo", "hi" ] # echo hi
func run(b *Builder, args []string, attributes map[string]bool, flagArgs []string, original string, heredocs []buildkitparser.Heredoc) error {
if b.RunConfig.Image == "" {
return fmt.Errorf("Please provide a source image with `from` prior to run")
}
args = handleJSONArgs(args, attributes)
var mounts []string
var network string
filteredUserArgs := make(map[string]string)
for k, v := range b.Args {
if _, ok := b.AllowedArgs[k]; ok {
filteredUserArgs[k] = v
}
}
userArgs := mergeEnv(envMapAsSlice(filteredUserArgs), b.Env)
for _, a := range flagArgs {
arg, err := ProcessWord(a, userArgs)
if err != nil {
return err
}
switch {
case strings.HasPrefix(arg, "--mount="):
mount := strings.TrimPrefix(arg, "--mount=")
if mount == "" {
return fmt.Errorf("no value specified for --mount=")
}
mounts = append(mounts, mount)
case strings.HasPrefix(arg, "--network="):
network = strings.TrimPrefix(arg, "--network=")
if network == "" {
return fmt.Errorf("no value specified for --network=")
}
default:
return fmt.Errorf("RUN only supports the --mount and --network flag")
}
}
files, err := processHereDocs(buildkitcommand.Run, original, heredocs, userArgs)
if err != nil {
return err
}
run := Run{
Args: args,
Mounts: mounts,
Network: network,
Files: files,
}
if !attributes["json"] {
run.Shell = true
}
b.PendingRuns = append(b.PendingRuns, run)
return nil
}
// CMD foo
//
// Set the default command to run in the container (which may be empty).
// Argument handling is the same as RUN.
func cmd(b *Builder, args []string, attributes map[string]bool, flagArgs []string, original string, heredocs []buildkitparser.Heredoc) error {
cmdSlice := handleJSONArgs(args, attributes)
if !attributes["json"] {
if runtime.GOOS != "windows" {
cmdSlice = append([]string{"/bin/sh", "-c"}, cmdSlice...)
} else {
cmdSlice = append([]string{"cmd", "/S", "/C"}, cmdSlice...)
}
}
b.RunConfig.Cmd = strslice.StrSlice(cmdSlice)
if len(args) != 0 {
b.CmdSet = true
}
return nil
}
// ENTRYPOINT /usr/sbin/nginx
//
// Set the entrypoint (which defaults to sh -c on linux, or cmd /S /C on Windows) to
// /usr/sbin/nginx. Will accept the CMD as the arguments to /usr/sbin/nginx.
//
// Handles command processing similar to CMD and RUN, only b.RunConfig.Entrypoint
// is initialized at NewBuilder time instead of through argument parsing.
func entrypoint(b *Builder, args []string, attributes map[string]bool, flagArgs []string, original string, heredocs []buildkitparser.Heredoc) error {
parsed := handleJSONArgs(args, attributes)
switch {
case attributes["json"]:
// ENTRYPOINT ["echo", "hi"]
b.RunConfig.Entrypoint = strslice.StrSlice(parsed)
case len(parsed) == 0:
// ENTRYPOINT []
b.RunConfig.Entrypoint = nil
default:
// ENTRYPOINT echo hi
if runtime.GOOS != "windows" {
b.RunConfig.Entrypoint = strslice.StrSlice{"/bin/sh", "-c", parsed[0]}
} else {
b.RunConfig.Entrypoint = strslice.StrSlice{"cmd", "/S", "/C", parsed[0]}
}
}
// when setting the entrypoint if a CMD was not explicitly set then
// set the command to nil
if !b.CmdSet {
b.RunConfig.Cmd = nil
}
return nil
}
// EXPOSE 6667/tcp 7000/tcp
//
// Expose ports for links and port mappings. This all ends up in
// b.RunConfig.ExposedPorts for runconfig.
func expose(b *Builder, args []string, attributes map[string]bool, flagArgs []string, original string, heredocs []buildkitparser.Heredoc) error {
if len(args) == 0 {
return errAtLeastOneArgument("EXPOSE")
}
if b.RunConfig.ExposedPorts == nil {
b.RunConfig.ExposedPorts = make(map[docker.Port]struct{})
}
existing := map[string]struct{}{}
for k := range b.RunConfig.ExposedPorts {
existing[k.Port()] = struct{}{}
}
for _, port := range args {
dp := docker.Port(port)
if _, exists := existing[dp.Port()]; !exists {
b.RunConfig.ExposedPorts[docker.Port(fmt.Sprintf("%s/%s", dp.Port(), dp.Proto()))] = struct{}{}
}
}
return nil
}
// USER foo
//
// Set the user to 'foo' for future commands and when running the
// ENTRYPOINT/CMD at container run time.
func user(b *Builder, args []string, attributes map[string]bool, flagArgs []string, original string, heredocs []buildkitparser.Heredoc) error {
if len(args) != 1 {
return errExactlyOneArgument("USER")
}
b.RunConfig.User = args[0]
return nil
}
// VOLUME /foo
//
// Expose the volume /foo for use. Will also accept the JSON array form.
func volume(b *Builder, args []string, attributes map[string]bool, flagArgs []string, original string, heredocs []buildkitparser.Heredoc) error {
if len(args) == 0 {
return errAtLeastOneArgument("VOLUME")
}
if b.RunConfig.Volumes == nil {
b.RunConfig.Volumes = map[string]struct{}{}
}
for _, v := range args {
v = strings.TrimSpace(v)
if v == "" {
return fmt.Errorf("Volume specified can not be an empty string")
}
b.RunConfig.Volumes[v] = struct{}{}
b.PendingVolumes.Add(v)
}
return nil
}
// STOPSIGNAL signal
//
// Set the signal that will be used to kill the container.
func stopSignal(b *Builder, args []string, attributes map[string]bool, flagArgs []string, original string, heredocs []buildkitparser.Heredoc) error {
if len(args) != 1 {
return errExactlyOneArgument("STOPSIGNAL")
}
sig := args[0]
if err := signal.CheckSignal(sig); err != nil {
return err
}
b.RunConfig.StopSignal = sig
return nil
}
// HEALTHCHECK foo
//
// Set the default healthcheck command to run in the container (which may be empty).
// Argument handling is the same as RUN.
func healthcheck(b *Builder, args []string, attributes map[string]bool, flagArgs []string, original string, heredocs []buildkitparser.Heredoc) error {
if len(args) == 0 {
return errAtLeastOneArgument("HEALTHCHECK")
}
typ := strings.ToUpper(args[0])
args = args[1:]
if typ == "NONE" {
if len(args) != 0 {
return fmt.Errorf("HEALTHCHECK NONE takes no arguments")
}
test := strslice.StrSlice{typ}
b.RunConfig.Healthcheck = &docker.HealthConfig{
Test: test,
}
} else {
if b.RunConfig.Healthcheck != nil {
oldCmd := b.RunConfig.Healthcheck.Test
if len(oldCmd) > 0 && oldCmd[0] != "NONE" {
b.Warnings = append(b.Warnings, fmt.Sprintf("Note: overriding previous HEALTHCHECK: %v\n", oldCmd))
}
}
healthcheck := docker.HealthConfig{}
flags := flag.NewFlagSet("", flag.ContinueOnError)
flags.String("start-period", "", "")
flags.String("start-interval", "", "")
flags.String("interval", "", "")
flags.String("timeout", "", "")
flRetries := flags.String("retries", "", "")
if err := flags.Parse(flagArgs); err != nil {
return err
}
switch typ {
case "CMD":
cmdSlice := handleJSONArgs(args, attributes)
if len(cmdSlice) == 0 {
return fmt.Errorf("Missing command after HEALTHCHECK CMD")
}
if !attributes["json"] {
typ = "CMD-SHELL"
}
healthcheck.Test = strslice.StrSlice(append([]string{typ}, cmdSlice...))
default:
return fmt.Errorf("Unknown type %#v in HEALTHCHECK (try CMD)", typ)
}
period, err := parseOptInterval(flags.Lookup("start-period"))
if err != nil {
return err
}
healthcheck.StartPeriod = period
interval, err := parseOptInterval(flags.Lookup("interval"))
if err != nil {
return err
}
healthcheck.Interval = interval
startInterval, err := parseOptInterval(flags.Lookup("start-interval"))
if err != nil {
return err
}
healthcheck.StartInterval = startInterval
timeout, err := parseOptInterval(flags.Lookup("timeout"))
if err != nil {
return err
}
healthcheck.Timeout = timeout
if *flRetries != "" {
retries, err := strconv.ParseInt(*flRetries, 10, 32)
if err != nil {
return err
}
if retries < 1 {
return fmt.Errorf("--retries must be at least 1 (not %d)", retries)
}
healthcheck.Retries = int(retries)
} else {
healthcheck.Retries = 0
}
b.RunConfig.Healthcheck = &healthcheck
}
return nil
}
// ARG name[=value]
//
// Adds the variable foo to the trusted list of variables that can be passed
// to builder using the --build-arg flag for expansion/subsitution or passing to 'run'.
// Dockerfile author may optionally set a default value of this variable.
func arg(b *Builder, args []string, attributes map[string]bool, flagArgs []string, original string, heredocs []buildkitparser.Heredoc) error {
for _, argument := range args {
var (
name string
defaultValue string
haveDefault bool
)
arg := argument
// 'arg' can just be a name or name-value pair. Note that this is different
// from 'env' that handles the split of name and value at the parser level.
// The reason for doing it differently for 'arg' is that we support just
// defining an arg without assigning it a value (while 'env' always expects a
// name-value pair). If possible, it will be good to harmonize the two.
name, defaultValue, haveDefault = strings.Cut(arg, "=")
// add the arg to allowed list of build-time args from this step on.
b.AllowedArgs[name] = true
// If the stage introduces one of the predefined args, add the
// predefined value to the list of values known in this stage
if value, defined := builtinArgDefaults[name]; defined {
if haveDefault && (name == "TARGETPLATFORM" || name == "BUILDPLATFORM") {
return fmt.Errorf("attempted to redefine %q: %w", name, errdefs.ErrInvalidArgument)
}
if b.BuiltinArgDefaults == nil {
b.BuiltinArgDefaults = make(map[string]string)
}
// N.B.: we're only consulting b.BuiltinArgDefaults for
// values that correspond to keys in
// builtinArgDefaults, which keeps the caller from
// using it to sneak in arbitrary ARG values
if _, setByUser := b.UserArgs[name]; !setByUser && defined {
if builderValue, builderDefined := b.BuiltinArgDefaults[name]; builderDefined {
b.Args[name] = builderValue
} else {
b.Args[name] = value
}
}
continue
}
// If there is still no default value, check for a default value from the heading args
if !haveDefault {
defaultValue, haveDefault = b.HeadingArgs[name]
}
// If there is a default value provided for this arg, and the user didn't supply
// a value, then set the default value in b.Args. Later defaults given for the
// same arg override earlier ones. The args passed to the builder (UserArgs) override
// any default values of 'arg', so don't set them here as they were already set
// in NewBuilder().
if _, setByUser := b.UserArgs[name]; !setByUser && haveDefault {
b.Args[name] = defaultValue
}
}
return nil
}
// SHELL powershell -command
//
// Set the non-default shell to use.
func shell(b *Builder, args []string, attributes map[string]bool, flagArgs []string, original string, heredocs []buildkitparser.Heredoc) error {
shellSlice := handleJSONArgs(args, attributes)
switch {
case len(shellSlice) == 0:
// SHELL []
return errAtLeastOneArgument("SHELL")
case attributes["json"]:
// SHELL ["powershell", "-command"]
b.RunConfig.Shell = strslice.StrSlice(shellSlice)
// b.RunConfig.Shell = strslice.StrSlice(shellSlice)
default:
// SHELL powershell -command - not JSON
return errNotJSON("SHELL")
}
return nil
}
// checkChmodConversion makes sure that the argument to a --chmod= flag for
// COPY or ADD is an octal number
func checkChmodConversion(chmod string) error {
_, err := strconv.ParseUint(chmod, 8, 32)
if err != nil {
return fmt.Errorf("Error parsing chmod %s", chmod)
}
return nil
}
func errAtLeastOneArgument(command string) error {
return fmt.Errorf("%s requires at least one argument", command)
}
func errAtLeastTwoArgument(command string) error {
return fmt.Errorf("%s requires at least two arguments", command)
}
func errExactlyOneArgument(command string) error {
return fmt.Errorf("%s requires exactly one argument", command)
}
func errTooManyArguments(command string) error {
return fmt.Errorf("Bad input to %s, too many arguments", command)
}
func errNotJSON(command string) error {
return fmt.Errorf("%s requires the arguments to be in JSON form", command)
}
|