github.com/wozhu6104/docker@v20.10.10+incompatible/builder/dockerfile/dispatchers.go (about)

     1  package dockerfile // import "github.com/docker/docker/builder/dockerfile"
     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  	"bytes"
    12  	"fmt"
    13  	"runtime"
    14  	"sort"
    15  	"strings"
    16  
    17  	"github.com/containerd/containerd/platforms"
    18  	"github.com/docker/docker/api"
    19  	"github.com/docker/docker/api/types/strslice"
    20  	"github.com/docker/docker/builder"
    21  	"github.com/docker/docker/errdefs"
    22  	"github.com/docker/docker/image"
    23  	"github.com/docker/docker/pkg/jsonmessage"
    24  	"github.com/docker/docker/pkg/signal"
    25  	"github.com/docker/docker/pkg/system"
    26  	"github.com/docker/go-connections/nat"
    27  	"github.com/moby/buildkit/frontend/dockerfile/instructions"
    28  	"github.com/moby/buildkit/frontend/dockerfile/parser"
    29  	"github.com/moby/buildkit/frontend/dockerfile/shell"
    30  	specs "github.com/opencontainers/image-spec/specs-go/v1"
    31  	"github.com/pkg/errors"
    32  )
    33  
    34  // ENV foo bar
    35  //
    36  // Sets the environment variable foo to bar, also makes interpolation
    37  // in the dockerfile available from the next statement on via ${foo}.
    38  //
    39  func dispatchEnv(d dispatchRequest, c *instructions.EnvCommand) error {
    40  	runConfig := d.state.runConfig
    41  	commitMessage := bytes.NewBufferString("ENV")
    42  	for _, e := range c.Env {
    43  		name := e.Key
    44  		newVar := e.String()
    45  
    46  		commitMessage.WriteString(" " + newVar)
    47  		gotOne := false
    48  		for i, envVar := range runConfig.Env {
    49  			envParts := strings.SplitN(envVar, "=", 2)
    50  			compareFrom := envParts[0]
    51  			if shell.EqualEnvKeys(compareFrom, name) {
    52  				runConfig.Env[i] = newVar
    53  				gotOne = true
    54  				break
    55  			}
    56  		}
    57  		if !gotOne {
    58  			runConfig.Env = append(runConfig.Env, newVar)
    59  		}
    60  	}
    61  	return d.builder.commit(d.state, commitMessage.String())
    62  }
    63  
    64  // MAINTAINER some text <maybe@an.email.address>
    65  //
    66  // Sets the maintainer metadata.
    67  func dispatchMaintainer(d dispatchRequest, c *instructions.MaintainerCommand) error {
    68  
    69  	d.state.maintainer = c.Maintainer
    70  	return d.builder.commit(d.state, "MAINTAINER "+c.Maintainer)
    71  }
    72  
    73  // LABEL some json data describing the image
    74  //
    75  // Sets the Label variable foo to bar,
    76  //
    77  func dispatchLabel(d dispatchRequest, c *instructions.LabelCommand) error {
    78  	if d.state.runConfig.Labels == nil {
    79  		d.state.runConfig.Labels = make(map[string]string)
    80  	}
    81  	commitStr := "LABEL"
    82  	for _, v := range c.Labels {
    83  		d.state.runConfig.Labels[v.Key] = v.Value
    84  		commitStr += " " + v.String()
    85  	}
    86  	return d.builder.commit(d.state, commitStr)
    87  }
    88  
    89  // ADD foo /path
    90  //
    91  // Add the file 'foo' to '/path'. Tarball and Remote URL (http, https) handling
    92  // exist here. If you do not wish to have this automatic handling, use COPY.
    93  //
    94  func dispatchAdd(d dispatchRequest, c *instructions.AddCommand) error {
    95  	if c.Chmod != "" {
    96  		return errors.New("the --chmod option requires BuildKit. Refer to https://docs.docker.com/go/buildkit/ to learn how to build images with BuildKit enabled")
    97  	}
    98  	downloader := newRemoteSourceDownloader(d.builder.Output, d.builder.Stdout)
    99  	copier := copierFromDispatchRequest(d, downloader, nil)
   100  	defer copier.Cleanup()
   101  
   102  	copyInstruction, err := copier.createCopyInstruction(c.SourcesAndDest, "ADD")
   103  	if err != nil {
   104  		return err
   105  	}
   106  	copyInstruction.chownStr = c.Chown
   107  	copyInstruction.allowLocalDecompression = true
   108  
   109  	return d.builder.performCopy(d, copyInstruction)
   110  }
   111  
   112  // COPY foo /path
   113  //
   114  // Same as 'ADD' but without the tar and remote url handling.
   115  //
   116  func dispatchCopy(d dispatchRequest, c *instructions.CopyCommand) error {
   117  	if c.Chmod != "" {
   118  		return errors.New("the --chmod option requires BuildKit. Refer to https://docs.docker.com/go/buildkit/ to learn how to build images with BuildKit enabled")
   119  	}
   120  	var im *imageMount
   121  	var err error
   122  	if c.From != "" {
   123  		im, err = d.getImageMount(c.From)
   124  		if err != nil {
   125  			return errors.Wrapf(err, "invalid from flag value %s", c.From)
   126  		}
   127  	}
   128  	copier := copierFromDispatchRequest(d, errOnSourceDownload, im)
   129  	defer copier.Cleanup()
   130  	copyInstruction, err := copier.createCopyInstruction(c.SourcesAndDest, "COPY")
   131  	if err != nil {
   132  		return err
   133  	}
   134  	copyInstruction.chownStr = c.Chown
   135  	if c.From != "" && copyInstruction.chownStr == "" {
   136  		copyInstruction.preserveOwnership = true
   137  	}
   138  	return d.builder.performCopy(d, copyInstruction)
   139  }
   140  
   141  func (d *dispatchRequest) getImageMount(imageRefOrID string) (*imageMount, error) {
   142  	if imageRefOrID == "" {
   143  		// TODO: this could return the source in the default case as well?
   144  		return nil, nil
   145  	}
   146  
   147  	var localOnly bool
   148  	stage, err := d.stages.get(imageRefOrID)
   149  	if err != nil {
   150  		return nil, err
   151  	}
   152  	if stage != nil {
   153  		imageRefOrID = stage.Image
   154  		localOnly = true
   155  	}
   156  	return d.builder.imageSources.Get(imageRefOrID, localOnly, d.builder.platform)
   157  }
   158  
   159  // FROM [--platform=platform] imagename[:tag | @digest] [AS build-stage-name]
   160  //
   161  func initializeStage(d dispatchRequest, cmd *instructions.Stage) error {
   162  	d.builder.imageProber.Reset()
   163  
   164  	var platform *specs.Platform
   165  	if v := cmd.Platform; v != "" {
   166  		v, err := d.getExpandedString(d.shlex, v)
   167  		if err != nil {
   168  			return errors.Wrapf(err, "failed to process arguments for platform %s", v)
   169  		}
   170  
   171  		p, err := platforms.Parse(v)
   172  		if err != nil {
   173  			return errors.Wrapf(err, "failed to parse platform %s", v)
   174  		}
   175  		if err := system.ValidatePlatform(p); err != nil {
   176  			return err
   177  		}
   178  		platform = &p
   179  	}
   180  
   181  	image, err := d.getFromImage(d.shlex, cmd.BaseName, platform)
   182  	if err != nil {
   183  		return err
   184  	}
   185  	state := d.state
   186  	if err := state.beginStage(cmd.Name, image); err != nil {
   187  		return err
   188  	}
   189  	if len(state.runConfig.OnBuild) > 0 {
   190  		triggers := state.runConfig.OnBuild
   191  		state.runConfig.OnBuild = nil
   192  		return dispatchTriggeredOnBuild(d, triggers)
   193  	}
   194  	return nil
   195  }
   196  
   197  func dispatchTriggeredOnBuild(d dispatchRequest, triggers []string) error {
   198  	fmt.Fprintf(d.builder.Stdout, "# Executing %d build trigger", len(triggers))
   199  	if len(triggers) > 1 {
   200  		fmt.Fprint(d.builder.Stdout, "s")
   201  	}
   202  	fmt.Fprintln(d.builder.Stdout)
   203  	for _, trigger := range triggers {
   204  		d.state.updateRunConfig()
   205  		ast, err := parser.Parse(strings.NewReader(trigger))
   206  		if err != nil {
   207  			return err
   208  		}
   209  		if len(ast.AST.Children) != 1 {
   210  			return errors.New("onbuild trigger should be a single expression")
   211  		}
   212  		cmd, err := instructions.ParseCommand(ast.AST.Children[0])
   213  		if err != nil {
   214  			var uiErr *instructions.UnknownInstruction
   215  			if errors.As(err, &uiErr) {
   216  				buildsFailed.WithValues(metricsUnknownInstructionError).Inc()
   217  			}
   218  			return err
   219  		}
   220  		err = dispatch(d, cmd)
   221  		if err != nil {
   222  			return err
   223  		}
   224  	}
   225  	return nil
   226  }
   227  
   228  func (d *dispatchRequest) getExpandedString(shlex *shell.Lex, str string) (string, error) {
   229  	substitutionArgs := []string{}
   230  	for key, value := range d.state.buildArgs.GetAllMeta() {
   231  		substitutionArgs = append(substitutionArgs, key+"="+value)
   232  	}
   233  
   234  	name, err := shlex.ProcessWord(str, substitutionArgs)
   235  	if err != nil {
   236  		return "", err
   237  	}
   238  	return name, nil
   239  }
   240  
   241  func (d *dispatchRequest) getImageOrStage(name string, platform *specs.Platform) (builder.Image, error) {
   242  	var localOnly bool
   243  	if im, ok := d.stages.getByName(name); ok {
   244  		name = im.Image
   245  		localOnly = true
   246  	}
   247  
   248  	if platform == nil {
   249  		platform = d.builder.platform
   250  	}
   251  
   252  	// Windows cannot support a container with no base image unless it is LCOW.
   253  	if name == api.NoBaseImageSpecifier {
   254  		p := platforms.DefaultSpec()
   255  		if platform != nil {
   256  			p = *platform
   257  		}
   258  		imageImage := &image.Image{}
   259  		imageImage.OS = p.OS
   260  
   261  		// old windows scratch handling
   262  		// TODO: scratch should not have an os. It should be nil image.
   263  		// Windows supports scratch. What is not supported is running containers
   264  		// from it.
   265  		if runtime.GOOS == "windows" {
   266  			if platform == nil || platform.OS == "linux" {
   267  				if !system.LCOWSupported() {
   268  					return nil, errors.New("Linux containers are not supported on this system")
   269  				}
   270  				imageImage.OS = "linux"
   271  			} else if platform.OS == "windows" {
   272  				return nil, errors.New("Windows does not support FROM scratch")
   273  			} else {
   274  				return nil, errors.Errorf("platform %s is not supported", platforms.Format(p))
   275  			}
   276  		}
   277  		return builder.Image(imageImage), nil
   278  	}
   279  	imageMount, err := d.builder.imageSources.Get(name, localOnly, platform)
   280  	if err != nil {
   281  		return nil, err
   282  	}
   283  	return imageMount.Image(), nil
   284  }
   285  func (d *dispatchRequest) getFromImage(shlex *shell.Lex, basename string, platform *specs.Platform) (builder.Image, error) {
   286  	name, err := d.getExpandedString(shlex, basename)
   287  	if err != nil {
   288  		return nil, err
   289  	}
   290  	// Empty string is interpreted to FROM scratch by images.GetImageAndReleasableLayer,
   291  	// so validate expanded result is not empty.
   292  	if name == "" {
   293  		return nil, errors.Errorf("base name (%s) should not be blank", basename)
   294  	}
   295  
   296  	return d.getImageOrStage(name, platform)
   297  }
   298  
   299  func dispatchOnbuild(d dispatchRequest, c *instructions.OnbuildCommand) error {
   300  	d.state.runConfig.OnBuild = append(d.state.runConfig.OnBuild, c.Expression)
   301  	return d.builder.commit(d.state, "ONBUILD "+c.Expression)
   302  }
   303  
   304  // WORKDIR /tmp
   305  //
   306  // Set the working directory for future RUN/CMD/etc statements.
   307  //
   308  func dispatchWorkdir(d dispatchRequest, c *instructions.WorkdirCommand) error {
   309  	runConfig := d.state.runConfig
   310  	var err error
   311  	runConfig.WorkingDir, err = normalizeWorkdir(d.state.operatingSystem, runConfig.WorkingDir, c.Path)
   312  	if err != nil {
   313  		return err
   314  	}
   315  
   316  	// For performance reasons, we explicitly do a create/mkdir now
   317  	// This avoids having an unnecessary expensive mount/unmount calls
   318  	// (on Windows in particular) during each container create.
   319  	// Prior to 1.13, the mkdir was deferred and not executed at this step.
   320  	if d.builder.disableCommit {
   321  		// Don't call back into the daemon if we're going through docker commit --change "WORKDIR /foo".
   322  		// We've already updated the runConfig and that's enough.
   323  		return nil
   324  	}
   325  
   326  	comment := "WORKDIR " + runConfig.WorkingDir
   327  	runConfigWithCommentCmd := copyRunConfig(runConfig, withCmdCommentString(comment, d.state.operatingSystem))
   328  
   329  	containerID, err := d.builder.probeAndCreate(d.state, runConfigWithCommentCmd)
   330  	if err != nil || containerID == "" {
   331  		return err
   332  	}
   333  
   334  	if err := d.builder.docker.ContainerCreateWorkdir(containerID); err != nil {
   335  		return err
   336  	}
   337  
   338  	return d.builder.commitContainer(d.state, containerID, runConfigWithCommentCmd)
   339  }
   340  
   341  // RUN some command yo
   342  //
   343  // run a command and commit the image. Args are automatically prepended with
   344  // the current SHELL which defaults to 'sh -c' under linux or 'cmd /S /C' under
   345  // Windows, in the event there is only one argument The difference in processing:
   346  //
   347  // RUN echo hi          # sh -c echo hi       (Linux and LCOW)
   348  // RUN echo hi          # cmd /S /C echo hi   (Windows)
   349  // RUN [ "echo", "hi" ] # echo hi
   350  //
   351  func dispatchRun(d dispatchRequest, c *instructions.RunCommand) error {
   352  	if !system.IsOSSupported(d.state.operatingSystem) {
   353  		return system.ErrNotSupportedOperatingSystem
   354  	}
   355  
   356  	if len(c.FlagsUsed) > 0 {
   357  		// classic builder RUN currently does not support any flags, so fail on the first one
   358  		return errors.Errorf("the --%s option requires BuildKit. Refer to https://docs.docker.com/go/buildkit/ to learn how to build images with BuildKit enabled", c.FlagsUsed[0])
   359  	}
   360  
   361  	stateRunConfig := d.state.runConfig
   362  	cmdFromArgs, argsEscaped := resolveCmdLine(c.ShellDependantCmdLine, stateRunConfig, d.state.operatingSystem, c.Name(), c.String())
   363  	buildArgs := d.state.buildArgs.FilterAllowed(stateRunConfig.Env)
   364  
   365  	saveCmd := cmdFromArgs
   366  	if len(buildArgs) > 0 {
   367  		saveCmd = prependEnvOnCmd(d.state.buildArgs, buildArgs, cmdFromArgs)
   368  	}
   369  
   370  	runConfigForCacheProbe := copyRunConfig(stateRunConfig,
   371  		withCmd(saveCmd),
   372  		withArgsEscaped(argsEscaped),
   373  		withEntrypointOverride(saveCmd, nil))
   374  	if hit, err := d.builder.probeCache(d.state, runConfigForCacheProbe); err != nil || hit {
   375  		return err
   376  	}
   377  
   378  	runConfig := copyRunConfig(stateRunConfig,
   379  		withCmd(cmdFromArgs),
   380  		withArgsEscaped(argsEscaped),
   381  		withEnv(append(stateRunConfig.Env, buildArgs...)),
   382  		withEntrypointOverride(saveCmd, strslice.StrSlice{""}),
   383  		withoutHealthcheck())
   384  
   385  	cID, err := d.builder.create(runConfig)
   386  	if err != nil {
   387  		return err
   388  	}
   389  
   390  	if err := d.builder.containerManager.Run(d.builder.clientCtx, cID, d.builder.Stdout, d.builder.Stderr); err != nil {
   391  		if err, ok := err.(*statusCodeError); ok {
   392  			// TODO: change error type, because jsonmessage.JSONError assumes HTTP
   393  			msg := fmt.Sprintf(
   394  				"The command '%s' returned a non-zero code: %d",
   395  				strings.Join(runConfig.Cmd, " "), err.StatusCode())
   396  			if err.Error() != "" {
   397  				msg = fmt.Sprintf("%s: %s", msg, err.Error())
   398  			}
   399  			return &jsonmessage.JSONError{
   400  				Message: msg,
   401  				Code:    err.StatusCode(),
   402  			}
   403  		}
   404  		return err
   405  	}
   406  
   407  	// Don't persist the argsEscaped value in the committed image. Use the original
   408  	// from previous build steps (only CMD and ENTRYPOINT persist this).
   409  	if d.state.operatingSystem == "windows" {
   410  		runConfigForCacheProbe.ArgsEscaped = stateRunConfig.ArgsEscaped
   411  	}
   412  
   413  	return d.builder.commitContainer(d.state, cID, runConfigForCacheProbe)
   414  }
   415  
   416  // Derive the command to use for probeCache() and to commit in this container.
   417  // Note that we only do this if there are any build-time env vars.  Also, we
   418  // use the special argument "|#" at the start of the args array. This will
   419  // avoid conflicts with any RUN command since commands can not
   420  // start with | (vertical bar). The "#" (number of build envs) is there to
   421  // help ensure proper cache matches. We don't want a RUN command
   422  // that starts with "foo=abc" to be considered part of a build-time env var.
   423  //
   424  // remove any unreferenced built-in args from the environment variables.
   425  // These args are transparent so resulting image should be the same regardless
   426  // of the value.
   427  func prependEnvOnCmd(buildArgs *BuildArgs, buildArgVars []string, cmd strslice.StrSlice) strslice.StrSlice {
   428  	var tmpBuildEnv []string
   429  	for _, env := range buildArgVars {
   430  		key := strings.SplitN(env, "=", 2)[0]
   431  		if buildArgs.IsReferencedOrNotBuiltin(key) {
   432  			tmpBuildEnv = append(tmpBuildEnv, env)
   433  		}
   434  	}
   435  
   436  	sort.Strings(tmpBuildEnv)
   437  	tmpEnv := append([]string{fmt.Sprintf("|%d", len(tmpBuildEnv))}, tmpBuildEnv...)
   438  	return strslice.StrSlice(append(tmpEnv, cmd...))
   439  }
   440  
   441  // CMD foo
   442  //
   443  // Set the default command to run in the container (which may be empty).
   444  // Argument handling is the same as RUN.
   445  //
   446  func dispatchCmd(d dispatchRequest, c *instructions.CmdCommand) error {
   447  	runConfig := d.state.runConfig
   448  	cmd, argsEscaped := resolveCmdLine(c.ShellDependantCmdLine, runConfig, d.state.operatingSystem, c.Name(), c.String())
   449  
   450  	// We warn here as Windows shell processing operates differently to Linux.
   451  	// Linux:   /bin/sh -c "echo hello" world	--> hello
   452  	// Windows: cmd /s /c "echo hello" world	--> hello world
   453  	if d.state.operatingSystem == "windows" &&
   454  		len(runConfig.Entrypoint) > 0 &&
   455  		d.state.runConfig.ArgsEscaped != argsEscaped {
   456  		fmt.Fprintf(d.builder.Stderr, " ---> [Warning] Shell-form ENTRYPOINT and exec-form CMD may have unexpected results\n")
   457  	}
   458  
   459  	runConfig.Cmd = cmd
   460  	runConfig.ArgsEscaped = argsEscaped
   461  
   462  	if err := d.builder.commit(d.state, fmt.Sprintf("CMD %q", cmd)); err != nil {
   463  		return err
   464  	}
   465  	if len(c.ShellDependantCmdLine.CmdLine) != 0 {
   466  		d.state.cmdSet = true
   467  	}
   468  
   469  	return nil
   470  }
   471  
   472  // HEALTHCHECK foo
   473  //
   474  // Set the default healthcheck command to run in the container (which may be empty).
   475  // Argument handling is the same as RUN.
   476  //
   477  func dispatchHealthcheck(d dispatchRequest, c *instructions.HealthCheckCommand) error {
   478  	runConfig := d.state.runConfig
   479  	if runConfig.Healthcheck != nil {
   480  		oldCmd := runConfig.Healthcheck.Test
   481  		if len(oldCmd) > 0 && oldCmd[0] != "NONE" {
   482  			fmt.Fprintf(d.builder.Stdout, "Note: overriding previous HEALTHCHECK: %v\n", oldCmd)
   483  		}
   484  	}
   485  	runConfig.Healthcheck = c.Health
   486  	return d.builder.commit(d.state, fmt.Sprintf("HEALTHCHECK %q", runConfig.Healthcheck))
   487  }
   488  
   489  // ENTRYPOINT /usr/sbin/nginx
   490  //
   491  // Set the entrypoint to /usr/sbin/nginx. Will accept the CMD as the arguments
   492  // to /usr/sbin/nginx. Uses the default shell if not in JSON format.
   493  //
   494  // Handles command processing similar to CMD and RUN, only req.runConfig.Entrypoint
   495  // is initialized at newBuilder time instead of through argument parsing.
   496  //
   497  func dispatchEntrypoint(d dispatchRequest, c *instructions.EntrypointCommand) error {
   498  	runConfig := d.state.runConfig
   499  	cmd, argsEscaped := resolveCmdLine(c.ShellDependantCmdLine, runConfig, d.state.operatingSystem, c.Name(), c.String())
   500  
   501  	// This warning is a little more complex than in dispatchCmd(), as the Windows base images (similar
   502  	// universally to almost every Linux image out there) have a single .Cmd field populated so that
   503  	// `docker run --rm image` starts the default shell which would typically be sh on Linux,
   504  	// or cmd on Windows. The catch to this is that if a dockerfile had `CMD ["c:\\windows\\system32\\cmd.exe"]`,
   505  	// we wouldn't be able to tell the difference. However, that would be highly unlikely, and besides, this
   506  	// is only trying to give a helpful warning of possibly unexpected results.
   507  	if d.state.operatingSystem == "windows" &&
   508  		d.state.runConfig.ArgsEscaped != argsEscaped &&
   509  		((len(runConfig.Cmd) == 1 && strings.ToLower(runConfig.Cmd[0]) != `c:\windows\system32\cmd.exe` && len(runConfig.Shell) == 0) || (len(runConfig.Cmd) > 1)) {
   510  		fmt.Fprintf(d.builder.Stderr, " ---> [Warning] Shell-form CMD and exec-form ENTRYPOINT may have unexpected results\n")
   511  	}
   512  
   513  	runConfig.Entrypoint = cmd
   514  	runConfig.ArgsEscaped = argsEscaped
   515  	if !d.state.cmdSet {
   516  		runConfig.Cmd = nil
   517  	}
   518  
   519  	return d.builder.commit(d.state, fmt.Sprintf("ENTRYPOINT %q", runConfig.Entrypoint))
   520  }
   521  
   522  // EXPOSE 6667/tcp 7000/tcp
   523  //
   524  // Expose ports for links and port mappings. This all ends up in
   525  // req.runConfig.ExposedPorts for runconfig.
   526  //
   527  func dispatchExpose(d dispatchRequest, c *instructions.ExposeCommand, envs []string) error {
   528  	// custom multi word expansion
   529  	// expose $FOO with FOO="80 443" is expanded as EXPOSE [80,443]. This is the only command supporting word to words expansion
   530  	// so the word processing has been de-generalized
   531  	ports := []string{}
   532  	for _, p := range c.Ports {
   533  		ps, err := d.shlex.ProcessWords(p, envs)
   534  		if err != nil {
   535  			return err
   536  		}
   537  		ports = append(ports, ps...)
   538  	}
   539  	c.Ports = ports
   540  
   541  	ps, _, err := nat.ParsePortSpecs(ports)
   542  	if err != nil {
   543  		return err
   544  	}
   545  
   546  	if d.state.runConfig.ExposedPorts == nil {
   547  		d.state.runConfig.ExposedPorts = make(nat.PortSet)
   548  	}
   549  	for p := range ps {
   550  		d.state.runConfig.ExposedPorts[p] = struct{}{}
   551  	}
   552  
   553  	return d.builder.commit(d.state, "EXPOSE "+strings.Join(c.Ports, " "))
   554  }
   555  
   556  // USER foo
   557  //
   558  // Set the user to 'foo' for future commands and when running the
   559  // ENTRYPOINT/CMD at container run time.
   560  //
   561  func dispatchUser(d dispatchRequest, c *instructions.UserCommand) error {
   562  	d.state.runConfig.User = c.User
   563  	return d.builder.commit(d.state, fmt.Sprintf("USER %v", c.User))
   564  }
   565  
   566  // VOLUME /foo
   567  //
   568  // Expose the volume /foo for use. Will also accept the JSON array form.
   569  //
   570  func dispatchVolume(d dispatchRequest, c *instructions.VolumeCommand) error {
   571  	if d.state.runConfig.Volumes == nil {
   572  		d.state.runConfig.Volumes = map[string]struct{}{}
   573  	}
   574  	for _, v := range c.Volumes {
   575  		if v == "" {
   576  			return errors.New("VOLUME specified can not be an empty string")
   577  		}
   578  		d.state.runConfig.Volumes[v] = struct{}{}
   579  	}
   580  	return d.builder.commit(d.state, fmt.Sprintf("VOLUME %v", c.Volumes))
   581  }
   582  
   583  // STOPSIGNAL signal
   584  //
   585  // Set the signal that will be used to kill the container.
   586  func dispatchStopSignal(d dispatchRequest, c *instructions.StopSignalCommand) error {
   587  
   588  	_, err := signal.ParseSignal(c.Signal)
   589  	if err != nil {
   590  		return errdefs.InvalidParameter(err)
   591  	}
   592  	d.state.runConfig.StopSignal = c.Signal
   593  	return d.builder.commit(d.state, fmt.Sprintf("STOPSIGNAL %v", c.Signal))
   594  }
   595  
   596  // ARG name[=value]
   597  //
   598  // Adds the variable foo to the trusted list of variables that can be passed
   599  // to builder using the --build-arg flag for expansion/substitution or passing to 'run'.
   600  // Dockerfile author may optionally set a default value of this variable.
   601  func dispatchArg(d dispatchRequest, c *instructions.ArgCommand) error {
   602  	var commitStr strings.Builder
   603  	commitStr.WriteString("ARG ")
   604  	for i, arg := range c.Args {
   605  		if i > 0 {
   606  			commitStr.WriteString(" ")
   607  		}
   608  		commitStr.WriteString(arg.Key)
   609  		if arg.Value != nil {
   610  			commitStr.WriteString("=")
   611  			commitStr.WriteString(*arg.Value)
   612  		}
   613  		d.state.buildArgs.AddArg(arg.Key, arg.Value)
   614  	}
   615  
   616  	return d.builder.commit(d.state, commitStr.String())
   617  }
   618  
   619  // SHELL powershell -command
   620  //
   621  // Set the non-default shell to use.
   622  func dispatchShell(d dispatchRequest, c *instructions.ShellCommand) error {
   623  	d.state.runConfig.Shell = c.Shell
   624  	return d.builder.commit(d.state, fmt.Sprintf("SHELL %v", d.state.runConfig.Shell))
   625  }