github.com/endophage/docker@v1.4.2-0.20161027011718-242853499895/builder/dockerfile/dispatchers.go (about)

     1  package 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  	"fmt"
    12  	"regexp"
    13  	"runtime"
    14  	"sort"
    15  	"strconv"
    16  	"strings"
    17  	"time"
    18  
    19  	"github.com/Sirupsen/logrus"
    20  	"github.com/docker/docker/api"
    21  	"github.com/docker/docker/api/types/container"
    22  	"github.com/docker/docker/api/types/strslice"
    23  	"github.com/docker/docker/builder"
    24  	"github.com/docker/docker/pkg/signal"
    25  	runconfigopts "github.com/docker/docker/runconfig/opts"
    26  	"github.com/docker/go-connections/nat"
    27  )
    28  
    29  // ENV foo bar
    30  //
    31  // Sets the environment variable foo to bar, also makes interpolation
    32  // in the dockerfile available from the next statement on via ${foo}.
    33  //
    34  func env(b *Builder, args []string, attributes map[string]bool, original string) error {
    35  	if len(args) == 0 {
    36  		return errAtLeastOneArgument("ENV")
    37  	}
    38  
    39  	if len(args)%2 != 0 {
    40  		// should never get here, but just in case
    41  		return errTooManyArguments("ENV")
    42  	}
    43  
    44  	if err := b.flags.Parse(); err != nil {
    45  		return err
    46  	}
    47  
    48  	// TODO/FIXME/NOT USED
    49  	// Just here to show how to use the builder flags stuff within the
    50  	// context of a builder command. Will remove once we actually add
    51  	// a builder command to something!
    52  	/*
    53  		flBool1 := b.flags.AddBool("bool1", false)
    54  		flStr1 := b.flags.AddString("str1", "HI")
    55  
    56  		if err := b.flags.Parse(); err != nil {
    57  			return err
    58  		}
    59  
    60  		fmt.Printf("Bool1:%v\n", flBool1)
    61  		fmt.Printf("Str1:%v\n", flStr1)
    62  	*/
    63  
    64  	commitStr := "ENV"
    65  
    66  	for j := 0; j < len(args); j++ {
    67  		// name  ==> args[j]
    68  		// value ==> args[j+1]
    69  
    70  		if len(args[j]) == 0 {
    71  			return errBlankCommandNames("ENV")
    72  		}
    73  
    74  		newVar := args[j] + "=" + args[j+1] + ""
    75  		commitStr += " " + newVar
    76  
    77  		gotOne := false
    78  		for i, envVar := range b.runConfig.Env {
    79  			envParts := strings.SplitN(envVar, "=", 2)
    80  			if envParts[0] == args[j] {
    81  				b.runConfig.Env[i] = newVar
    82  				gotOne = true
    83  				break
    84  			}
    85  		}
    86  		if !gotOne {
    87  			b.runConfig.Env = append(b.runConfig.Env, newVar)
    88  		}
    89  		j++
    90  	}
    91  
    92  	return b.commit("", b.runConfig.Cmd, commitStr)
    93  }
    94  
    95  // MAINTAINER some text <maybe@an.email.address>
    96  //
    97  // Sets the maintainer metadata.
    98  func maintainer(b *Builder, args []string, attributes map[string]bool, original string) error {
    99  	if len(args) != 1 {
   100  		return errExactlyOneArgument("MAINTAINER")
   101  	}
   102  
   103  	if err := b.flags.Parse(); err != nil {
   104  		return err
   105  	}
   106  
   107  	b.maintainer = args[0]
   108  	return b.commit("", b.runConfig.Cmd, fmt.Sprintf("MAINTAINER %s", b.maintainer))
   109  }
   110  
   111  // LABEL some json data describing the image
   112  //
   113  // Sets the Label variable foo to bar,
   114  //
   115  func label(b *Builder, args []string, attributes map[string]bool, original string) error {
   116  	if len(args) == 0 {
   117  		return errAtLeastOneArgument("LABEL")
   118  	}
   119  	if len(args)%2 != 0 {
   120  		// should never get here, but just in case
   121  		return errTooManyArguments("LABEL")
   122  	}
   123  
   124  	if err := b.flags.Parse(); err != nil {
   125  		return err
   126  	}
   127  
   128  	commitStr := "LABEL"
   129  
   130  	if b.runConfig.Labels == nil {
   131  		b.runConfig.Labels = map[string]string{}
   132  	}
   133  
   134  	for j := 0; j < len(args); j++ {
   135  		// name  ==> args[j]
   136  		// value ==> args[j+1]
   137  
   138  		if len(args[j]) == 0 {
   139  			return errBlankCommandNames("LABEL")
   140  		}
   141  
   142  		newVar := args[j] + "=" + args[j+1] + ""
   143  		commitStr += " " + newVar
   144  
   145  		b.runConfig.Labels[args[j]] = args[j+1]
   146  		j++
   147  	}
   148  	return b.commit("", b.runConfig.Cmd, commitStr)
   149  }
   150  
   151  // ADD foo /path
   152  //
   153  // Add the file 'foo' to '/path'. Tarball and Remote URL (git, http) handling
   154  // exist here. If you do not wish to have this automatic handling, use COPY.
   155  //
   156  func add(b *Builder, args []string, attributes map[string]bool, original string) error {
   157  	if len(args) < 2 {
   158  		return errAtLeastTwoArguments("ADD")
   159  	}
   160  
   161  	if err := b.flags.Parse(); err != nil {
   162  		return err
   163  	}
   164  
   165  	return b.runContextCommand(args, true, true, "ADD")
   166  }
   167  
   168  // COPY foo /path
   169  //
   170  // Same as 'ADD' but without the tar and remote url handling.
   171  //
   172  func dispatchCopy(b *Builder, args []string, attributes map[string]bool, original string) error {
   173  	if len(args) < 2 {
   174  		return errAtLeastTwoArguments("COPY")
   175  	}
   176  
   177  	if err := b.flags.Parse(); err != nil {
   178  		return err
   179  	}
   180  
   181  	return b.runContextCommand(args, false, false, "COPY")
   182  }
   183  
   184  // FROM imagename
   185  //
   186  // This sets the image the dockerfile will build on top of.
   187  //
   188  func from(b *Builder, args []string, attributes map[string]bool, original string) error {
   189  	if len(args) != 1 {
   190  		return errExactlyOneArgument("FROM")
   191  	}
   192  
   193  	if err := b.flags.Parse(); err != nil {
   194  		return err
   195  	}
   196  
   197  	name := args[0]
   198  
   199  	var (
   200  		image builder.Image
   201  		err   error
   202  	)
   203  
   204  	// Windows cannot support a container with no base image.
   205  	if name == api.NoBaseImageSpecifier {
   206  		if runtime.GOOS == "windows" {
   207  			return fmt.Errorf("Windows does not support FROM scratch")
   208  		}
   209  		b.image = ""
   210  		b.noBaseImage = true
   211  	} else {
   212  		// TODO: don't use `name`, instead resolve it to a digest
   213  		if !b.options.PullParent {
   214  			image, err = b.docker.GetImageOnBuild(name)
   215  			// TODO: shouldn't we error out if error is different from "not found" ?
   216  		}
   217  		if image == nil {
   218  			image, err = b.docker.PullOnBuild(b.clientCtx, name, b.options.AuthConfigs, b.Output)
   219  			if err != nil {
   220  				return err
   221  			}
   222  		}
   223  	}
   224  
   225  	return b.processImageFrom(image)
   226  }
   227  
   228  // ONBUILD RUN echo yo
   229  //
   230  // ONBUILD triggers run when the image is used in a FROM statement.
   231  //
   232  // ONBUILD handling has a lot of special-case functionality, the heading in
   233  // evaluator.go and comments around dispatch() in the same file explain the
   234  // special cases. search for 'OnBuild' in internals.go for additional special
   235  // cases.
   236  //
   237  func onbuild(b *Builder, args []string, attributes map[string]bool, original string) error {
   238  	if len(args) == 0 {
   239  		return errAtLeastOneArgument("ONBUILD")
   240  	}
   241  
   242  	if err := b.flags.Parse(); err != nil {
   243  		return err
   244  	}
   245  
   246  	triggerInstruction := strings.ToUpper(strings.TrimSpace(args[0]))
   247  	switch triggerInstruction {
   248  	case "ONBUILD":
   249  		return fmt.Errorf("Chaining ONBUILD via `ONBUILD ONBUILD` isn't allowed")
   250  	case "MAINTAINER", "FROM":
   251  		return fmt.Errorf("%s isn't allowed as an ONBUILD trigger", triggerInstruction)
   252  	}
   253  
   254  	original = regexp.MustCompile(`(?i)^\s*ONBUILD\s*`).ReplaceAllString(original, "")
   255  
   256  	b.runConfig.OnBuild = append(b.runConfig.OnBuild, original)
   257  	return b.commit("", b.runConfig.Cmd, fmt.Sprintf("ONBUILD %s", original))
   258  }
   259  
   260  // WORKDIR /tmp
   261  //
   262  // Set the working directory for future RUN/CMD/etc statements.
   263  //
   264  func workdir(b *Builder, args []string, attributes map[string]bool, original string) error {
   265  	if len(args) != 1 {
   266  		return errExactlyOneArgument("WORKDIR")
   267  	}
   268  
   269  	err := b.flags.Parse()
   270  	if err != nil {
   271  		return err
   272  	}
   273  
   274  	// This is from the Dockerfile and will not necessarily be in platform
   275  	// specific semantics, hence ensure it is converted.
   276  	b.runConfig.WorkingDir, err = normaliseWorkdir(b.runConfig.WorkingDir, args[0])
   277  	if err != nil {
   278  		return err
   279  	}
   280  
   281  	return b.commit("", b.runConfig.Cmd, fmt.Sprintf("WORKDIR %v", b.runConfig.WorkingDir))
   282  }
   283  
   284  // RUN some command yo
   285  //
   286  // run a command and commit the image. Args are automatically prepended with
   287  // the current SHELL which defaults to 'sh -c' under linux or 'cmd /S /C' under
   288  // Windows, in the event there is only one argument The difference in processing:
   289  //
   290  // RUN echo hi          # sh -c echo hi       (Linux)
   291  // RUN echo hi          # cmd /S /C echo hi   (Windows)
   292  // RUN [ "echo", "hi" ] # echo hi
   293  //
   294  func run(b *Builder, args []string, attributes map[string]bool, original string) error {
   295  	if b.image == "" && !b.noBaseImage {
   296  		return fmt.Errorf("Please provide a source image with `from` prior to run")
   297  	}
   298  
   299  	if err := b.flags.Parse(); err != nil {
   300  		return err
   301  	}
   302  
   303  	args = handleJSONArgs(args, attributes)
   304  
   305  	if !attributes["json"] {
   306  		args = append(getShell(b.runConfig), args...)
   307  	}
   308  	config := &container.Config{
   309  		Cmd:   strslice.StrSlice(args),
   310  		Image: b.image,
   311  	}
   312  
   313  	// stash the cmd
   314  	cmd := b.runConfig.Cmd
   315  	if len(b.runConfig.Entrypoint) == 0 && len(b.runConfig.Cmd) == 0 {
   316  		b.runConfig.Cmd = config.Cmd
   317  	}
   318  
   319  	// stash the config environment
   320  	env := b.runConfig.Env
   321  
   322  	defer func(cmd strslice.StrSlice) { b.runConfig.Cmd = cmd }(cmd)
   323  	defer func(env []string) { b.runConfig.Env = env }(env)
   324  
   325  	// derive the net build-time environment for this run. We let config
   326  	// environment override the build time environment.
   327  	// This means that we take the b.buildArgs list of env vars and remove
   328  	// any of those variables that are defined as part of the container. In other
   329  	// words, anything in b.Config.Env. What's left is the list of build-time env
   330  	// vars that we need to add to each RUN command - note the list could be empty.
   331  	//
   332  	// We don't persist the build time environment with container's config
   333  	// environment, but just sort and prepend it to the command string at time
   334  	// of commit.
   335  	// This helps with tracing back the image's actual environment at the time
   336  	// of RUN, without leaking it to the final image. It also aids cache
   337  	// lookup for same image built with same build time environment.
   338  	cmdBuildEnv := []string{}
   339  	configEnv := runconfigopts.ConvertKVStringsToMap(b.runConfig.Env)
   340  	for key, val := range b.options.BuildArgs {
   341  		if !b.isBuildArgAllowed(key) {
   342  			// skip build-args that are not in allowed list, meaning they have
   343  			// not been defined by an "ARG" Dockerfile command yet.
   344  			// This is an error condition but only if there is no "ARG" in the entire
   345  			// Dockerfile, so we'll generate any necessary errors after we parsed
   346  			// the entire file (see 'leftoverArgs' processing in evaluator.go )
   347  			continue
   348  		}
   349  		if _, ok := configEnv[key]; !ok {
   350  			cmdBuildEnv = append(cmdBuildEnv, fmt.Sprintf("%s=%s", key, val))
   351  		}
   352  	}
   353  
   354  	// derive the command to use for probeCache() and to commit in this container.
   355  	// Note that we only do this if there are any build-time env vars.  Also, we
   356  	// use the special argument "|#" at the start of the args array. This will
   357  	// avoid conflicts with any RUN command since commands can not
   358  	// start with | (vertical bar). The "#" (number of build envs) is there to
   359  	// help ensure proper cache matches. We don't want a RUN command
   360  	// that starts with "foo=abc" to be considered part of a build-time env var.
   361  	saveCmd := config.Cmd
   362  	if len(cmdBuildEnv) > 0 {
   363  		sort.Strings(cmdBuildEnv)
   364  		tmpEnv := append([]string{fmt.Sprintf("|%d", len(cmdBuildEnv))}, cmdBuildEnv...)
   365  		saveCmd = strslice.StrSlice(append(tmpEnv, saveCmd...))
   366  	}
   367  
   368  	b.runConfig.Cmd = saveCmd
   369  	hit, err := b.probeCache()
   370  	if err != nil {
   371  		return err
   372  	}
   373  	if hit {
   374  		return nil
   375  	}
   376  
   377  	// set Cmd manually, this is special case only for Dockerfiles
   378  	b.runConfig.Cmd = config.Cmd
   379  	// set build-time environment for 'run'.
   380  	b.runConfig.Env = append(b.runConfig.Env, cmdBuildEnv...)
   381  	// set config as already being escaped, this prevents double escaping on windows
   382  	b.runConfig.ArgsEscaped = true
   383  
   384  	logrus.Debugf("[BUILDER] Command to be executed: %v", b.runConfig.Cmd)
   385  
   386  	cID, err := b.create()
   387  	if err != nil {
   388  		return err
   389  	}
   390  
   391  	if err := b.run(cID); err != nil {
   392  		return err
   393  	}
   394  
   395  	// revert to original config environment and set the command string to
   396  	// have the build-time env vars in it (if any) so that future cache look-ups
   397  	// properly match it.
   398  	b.runConfig.Env = env
   399  	b.runConfig.Cmd = saveCmd
   400  	return b.commit(cID, cmd, "run")
   401  }
   402  
   403  // CMD foo
   404  //
   405  // Set the default command to run in the container (which may be empty).
   406  // Argument handling is the same as RUN.
   407  //
   408  func cmd(b *Builder, args []string, attributes map[string]bool, original string) error {
   409  	if err := b.flags.Parse(); err != nil {
   410  		return err
   411  	}
   412  
   413  	cmdSlice := handleJSONArgs(args, attributes)
   414  
   415  	if !attributes["json"] {
   416  		cmdSlice = append(getShell(b.runConfig), cmdSlice...)
   417  	}
   418  
   419  	b.runConfig.Cmd = strslice.StrSlice(cmdSlice)
   420  	// set config as already being escaped, this prevents double escaping on windows
   421  	b.runConfig.ArgsEscaped = true
   422  
   423  	if err := b.commit("", b.runConfig.Cmd, fmt.Sprintf("CMD %q", cmdSlice)); err != nil {
   424  		return err
   425  	}
   426  
   427  	if len(args) != 0 {
   428  		b.cmdSet = true
   429  	}
   430  
   431  	return nil
   432  }
   433  
   434  // parseOptInterval(flag) is the duration of flag.Value, or 0 if
   435  // empty. An error is reported if the value is given and is not positive.
   436  func parseOptInterval(f *Flag) (time.Duration, error) {
   437  	s := f.Value
   438  	if s == "" {
   439  		return 0, nil
   440  	}
   441  	d, err := time.ParseDuration(s)
   442  	if err != nil {
   443  		return 0, err
   444  	}
   445  	if d <= 0 {
   446  		return 0, fmt.Errorf("Interval %#v must be positive", f.name)
   447  	}
   448  	return d, nil
   449  }
   450  
   451  // HEALTHCHECK foo
   452  //
   453  // Set the default healthcheck command to run in the container (which may be empty).
   454  // Argument handling is the same as RUN.
   455  //
   456  func healthcheck(b *Builder, args []string, attributes map[string]bool, original string) error {
   457  	if len(args) == 0 {
   458  		return errAtLeastOneArgument("HEALTHCHECK")
   459  	}
   460  	typ := strings.ToUpper(args[0])
   461  	args = args[1:]
   462  	if typ == "NONE" {
   463  		if len(args) != 0 {
   464  			return fmt.Errorf("HEALTHCHECK NONE takes no arguments")
   465  		}
   466  		test := strslice.StrSlice{typ}
   467  		b.runConfig.Healthcheck = &container.HealthConfig{
   468  			Test: test,
   469  		}
   470  	} else {
   471  		if b.runConfig.Healthcheck != nil {
   472  			oldCmd := b.runConfig.Healthcheck.Test
   473  			if len(oldCmd) > 0 && oldCmd[0] != "NONE" {
   474  				fmt.Fprintf(b.Stdout, "Note: overriding previous HEALTHCHECK: %v\n", oldCmd)
   475  			}
   476  		}
   477  
   478  		healthcheck := container.HealthConfig{}
   479  
   480  		flInterval := b.flags.AddString("interval", "")
   481  		flTimeout := b.flags.AddString("timeout", "")
   482  		flRetries := b.flags.AddString("retries", "")
   483  
   484  		if err := b.flags.Parse(); err != nil {
   485  			return err
   486  		}
   487  
   488  		switch typ {
   489  		case "CMD":
   490  			cmdSlice := handleJSONArgs(args, attributes)
   491  			if len(cmdSlice) == 0 {
   492  				return fmt.Errorf("Missing command after HEALTHCHECK CMD")
   493  			}
   494  
   495  			if !attributes["json"] {
   496  				typ = "CMD-SHELL"
   497  			}
   498  
   499  			healthcheck.Test = strslice.StrSlice(append([]string{typ}, cmdSlice...))
   500  		default:
   501  			return fmt.Errorf("Unknown type %#v in HEALTHCHECK (try CMD)", typ)
   502  		}
   503  
   504  		interval, err := parseOptInterval(flInterval)
   505  		if err != nil {
   506  			return err
   507  		}
   508  		healthcheck.Interval = interval
   509  
   510  		timeout, err := parseOptInterval(flTimeout)
   511  		if err != nil {
   512  			return err
   513  		}
   514  		healthcheck.Timeout = timeout
   515  
   516  		if flRetries.Value != "" {
   517  			retries, err := strconv.ParseInt(flRetries.Value, 10, 32)
   518  			if err != nil {
   519  				return err
   520  			}
   521  			if retries < 1 {
   522  				return fmt.Errorf("--retries must be at least 1 (not %d)", retries)
   523  			}
   524  			healthcheck.Retries = int(retries)
   525  		} else {
   526  			healthcheck.Retries = 0
   527  		}
   528  
   529  		b.runConfig.Healthcheck = &healthcheck
   530  	}
   531  
   532  	return b.commit("", b.runConfig.Cmd, fmt.Sprintf("HEALTHCHECK %q", b.runConfig.Healthcheck))
   533  }
   534  
   535  // ENTRYPOINT /usr/sbin/nginx
   536  //
   537  // Set the entrypoint to /usr/sbin/nginx. Will accept the CMD as the arguments
   538  // to /usr/sbin/nginx. Uses the default shell if not in JSON format.
   539  //
   540  // Handles command processing similar to CMD and RUN, only b.runConfig.Entrypoint
   541  // is initialized at NewBuilder time instead of through argument parsing.
   542  //
   543  func entrypoint(b *Builder, args []string, attributes map[string]bool, original string) error {
   544  	if err := b.flags.Parse(); err != nil {
   545  		return err
   546  	}
   547  
   548  	parsed := handleJSONArgs(args, attributes)
   549  
   550  	switch {
   551  	case attributes["json"]:
   552  		// ENTRYPOINT ["echo", "hi"]
   553  		b.runConfig.Entrypoint = strslice.StrSlice(parsed)
   554  	case len(parsed) == 0:
   555  		// ENTRYPOINT []
   556  		b.runConfig.Entrypoint = nil
   557  	default:
   558  		// ENTRYPOINT echo hi
   559  		b.runConfig.Entrypoint = strslice.StrSlice(append(getShell(b.runConfig), parsed[0]))
   560  	}
   561  
   562  	// when setting the entrypoint if a CMD was not explicitly set then
   563  	// set the command to nil
   564  	if !b.cmdSet {
   565  		b.runConfig.Cmd = nil
   566  	}
   567  
   568  	if err := b.commit("", b.runConfig.Cmd, fmt.Sprintf("ENTRYPOINT %q", b.runConfig.Entrypoint)); err != nil {
   569  		return err
   570  	}
   571  
   572  	return nil
   573  }
   574  
   575  // EXPOSE 6667/tcp 7000/tcp
   576  //
   577  // Expose ports for links and port mappings. This all ends up in
   578  // b.runConfig.ExposedPorts for runconfig.
   579  //
   580  func expose(b *Builder, args []string, attributes map[string]bool, original string) error {
   581  	portsTab := args
   582  
   583  	if len(args) == 0 {
   584  		return errAtLeastOneArgument("EXPOSE")
   585  	}
   586  
   587  	if err := b.flags.Parse(); err != nil {
   588  		return err
   589  	}
   590  
   591  	if b.runConfig.ExposedPorts == nil {
   592  		b.runConfig.ExposedPorts = make(nat.PortSet)
   593  	}
   594  
   595  	ports, _, err := nat.ParsePortSpecs(portsTab)
   596  	if err != nil {
   597  		return err
   598  	}
   599  
   600  	// instead of using ports directly, we build a list of ports and sort it so
   601  	// the order is consistent. This prevents cache burst where map ordering
   602  	// changes between builds
   603  	portList := make([]string, len(ports))
   604  	var i int
   605  	for port := range ports {
   606  		if _, exists := b.runConfig.ExposedPorts[port]; !exists {
   607  			b.runConfig.ExposedPorts[port] = struct{}{}
   608  		}
   609  		portList[i] = string(port)
   610  		i++
   611  	}
   612  	sort.Strings(portList)
   613  	return b.commit("", b.runConfig.Cmd, fmt.Sprintf("EXPOSE %s", strings.Join(portList, " ")))
   614  }
   615  
   616  // USER foo
   617  //
   618  // Set the user to 'foo' for future commands and when running the
   619  // ENTRYPOINT/CMD at container run time.
   620  //
   621  func user(b *Builder, args []string, attributes map[string]bool, original string) error {
   622  	if len(args) != 1 {
   623  		return errExactlyOneArgument("USER")
   624  	}
   625  
   626  	if err := b.flags.Parse(); err != nil {
   627  		return err
   628  	}
   629  
   630  	b.runConfig.User = args[0]
   631  	return b.commit("", b.runConfig.Cmd, fmt.Sprintf("USER %v", args))
   632  }
   633  
   634  // VOLUME /foo
   635  //
   636  // Expose the volume /foo for use. Will also accept the JSON array form.
   637  //
   638  func volume(b *Builder, args []string, attributes map[string]bool, original string) error {
   639  	if len(args) == 0 {
   640  		return errAtLeastOneArgument("VOLUME")
   641  	}
   642  
   643  	if err := b.flags.Parse(); err != nil {
   644  		return err
   645  	}
   646  
   647  	if b.runConfig.Volumes == nil {
   648  		b.runConfig.Volumes = map[string]struct{}{}
   649  	}
   650  	for _, v := range args {
   651  		v = strings.TrimSpace(v)
   652  		if v == "" {
   653  			return fmt.Errorf("VOLUME specified can not be an empty string")
   654  		}
   655  		b.runConfig.Volumes[v] = struct{}{}
   656  	}
   657  	if err := b.commit("", b.runConfig.Cmd, fmt.Sprintf("VOLUME %v", args)); err != nil {
   658  		return err
   659  	}
   660  	return nil
   661  }
   662  
   663  // STOPSIGNAL signal
   664  //
   665  // Set the signal that will be used to kill the container.
   666  func stopSignal(b *Builder, args []string, attributes map[string]bool, original string) error {
   667  	if len(args) != 1 {
   668  		return errExactlyOneArgument("STOPSIGNAL")
   669  	}
   670  
   671  	sig := args[0]
   672  	_, err := signal.ParseSignal(sig)
   673  	if err != nil {
   674  		return err
   675  	}
   676  
   677  	b.runConfig.StopSignal = sig
   678  	return b.commit("", b.runConfig.Cmd, fmt.Sprintf("STOPSIGNAL %v", args))
   679  }
   680  
   681  // ARG name[=value]
   682  //
   683  // Adds the variable foo to the trusted list of variables that can be passed
   684  // to builder using the --build-arg flag for expansion/subsitution or passing to 'run'.
   685  // Dockerfile author may optionally set a default value of this variable.
   686  func arg(b *Builder, args []string, attributes map[string]bool, original string) error {
   687  	if len(args) != 1 {
   688  		return errExactlyOneArgument("ARG")
   689  	}
   690  
   691  	var (
   692  		name       string
   693  		value      string
   694  		hasDefault bool
   695  	)
   696  
   697  	arg := args[0]
   698  	// 'arg' can just be a name or name-value pair. Note that this is different
   699  	// from 'env' that handles the split of name and value at the parser level.
   700  	// The reason for doing it differently for 'arg' is that we support just
   701  	// defining an arg and not assign it a value (while 'env' always expects a
   702  	// name-value pair). If possible, it will be good to harmonize the two.
   703  	if strings.Contains(arg, "=") {
   704  		parts := strings.SplitN(arg, "=", 2)
   705  		if len(parts[0]) == 0 {
   706  			return errBlankCommandNames("ARG")
   707  		}
   708  
   709  		name = parts[0]
   710  		value = parts[1]
   711  		hasDefault = true
   712  	} else {
   713  		name = arg
   714  		hasDefault = false
   715  	}
   716  	// add the arg to allowed list of build-time args from this step on.
   717  	b.allowedBuildArgs[name] = true
   718  
   719  	// If there is a default value associated with this arg then add it to the
   720  	// b.buildArgs if one is not already passed to the builder. The args passed
   721  	// to builder override the default value of 'arg'.
   722  	if _, ok := b.options.BuildArgs[name]; !ok && hasDefault {
   723  		b.options.BuildArgs[name] = value
   724  	}
   725  
   726  	return b.commit("", b.runConfig.Cmd, fmt.Sprintf("ARG %s", arg))
   727  }
   728  
   729  // SHELL powershell -command
   730  //
   731  // Set the non-default shell to use.
   732  func shell(b *Builder, args []string, attributes map[string]bool, original string) error {
   733  	if err := b.flags.Parse(); err != nil {
   734  		return err
   735  	}
   736  	shellSlice := handleJSONArgs(args, attributes)
   737  	switch {
   738  	case len(shellSlice) == 0:
   739  		// SHELL []
   740  		return errAtLeastOneArgument("SHELL")
   741  	case attributes["json"]:
   742  		// SHELL ["powershell", "-command"]
   743  		b.runConfig.Shell = strslice.StrSlice(shellSlice)
   744  	default:
   745  		// SHELL powershell -command - not JSON
   746  		return errNotJSON("SHELL", original)
   747  	}
   748  	return b.commit("", b.runConfig.Cmd, fmt.Sprintf("SHELL %v", shellSlice))
   749  }
   750  
   751  func errAtLeastOneArgument(command string) error {
   752  	return fmt.Errorf("%s requires at least one argument", command)
   753  }
   754  
   755  func errExactlyOneArgument(command string) error {
   756  	return fmt.Errorf("%s requires exactly one argument", command)
   757  }
   758  
   759  func errAtLeastTwoArguments(command string) error {
   760  	return fmt.Errorf("%s requires at least two arguments", command)
   761  }
   762  
   763  func errBlankCommandNames(command string) error {
   764  	return fmt.Errorf("%s names can not be blank", command)
   765  }
   766  
   767  func errTooManyArguments(command string) error {
   768  	return fmt.Errorf("Bad input to %s, too many arguments", command)
   769  }
   770  
   771  // getShell is a helper function which gets the right shell for prefixing the
   772  // shell-form of RUN, ENTRYPOINT and CMD instructions
   773  func getShell(c *container.Config) []string {
   774  	if 0 == len(c.Shell) {
   775  		return defaultShell[:]
   776  	}
   777  	return c.Shell[:]
   778  }