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