github.com/slava-ustovytski/docker@v1.8.2-rc1/builder/dispatchers.go (about)

     1  package builder
     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  	"io/ioutil"
    13  	"path"
    14  	"path/filepath"
    15  	"regexp"
    16  	"runtime"
    17  	"sort"
    18  	"strings"
    19  
    20  	"github.com/Sirupsen/logrus"
    21  	flag "github.com/docker/docker/pkg/mflag"
    22  	"github.com/docker/docker/pkg/nat"
    23  	"github.com/docker/docker/runconfig"
    24  )
    25  
    26  const (
    27  	// NoBaseImageSpecifier is the symbol used by the FROM
    28  	// command to specify that no base image is to be used.
    29  	NoBaseImageSpecifier string = "scratch"
    30  )
    31  
    32  // dispatch with no layer / parsing. This is effectively not a command.
    33  func nullDispatch(b *builder, args []string, attributes map[string]bool, original string) error {
    34  	return nil
    35  }
    36  
    37  // ENV foo bar
    38  //
    39  // Sets the environment variable foo to bar, also makes interpolation
    40  // in the dockerfile available from the next statement on via ${foo}.
    41  //
    42  func env(b *builder, args []string, attributes map[string]bool, original string) error {
    43  	if len(args) == 0 {
    44  		return fmt.Errorf("ENV requires at least one argument")
    45  	}
    46  
    47  	if len(args)%2 != 0 {
    48  		// should never get here, but just in case
    49  		return fmt.Errorf("Bad input to ENV, too many args")
    50  	}
    51  
    52  	if err := b.BuilderFlags.Parse(); err != nil {
    53  		return err
    54  	}
    55  
    56  	// TODO/FIXME/NOT USED
    57  	// Just here to show how to use the builder flags stuff within the
    58  	// context of a builder command. Will remove once we actually add
    59  	// a builder command to something!
    60  	/*
    61  		flBool1 := b.BuilderFlags.AddBool("bool1", false)
    62  		flStr1 := b.BuilderFlags.AddString("str1", "HI")
    63  
    64  		if err := b.BuilderFlags.Parse(); err != nil {
    65  			return err
    66  		}
    67  
    68  		fmt.Printf("Bool1:%v\n", flBool1)
    69  		fmt.Printf("Str1:%v\n", flStr1)
    70  	*/
    71  
    72  	commitStr := "ENV"
    73  
    74  	for j := 0; j < len(args); j++ {
    75  		// name  ==> args[j]
    76  		// value ==> args[j+1]
    77  		newVar := args[j] + "=" + args[j+1] + ""
    78  		commitStr += " " + newVar
    79  
    80  		gotOne := false
    81  		for i, envVar := range b.Config.Env {
    82  			envParts := strings.SplitN(envVar, "=", 2)
    83  			if envParts[0] == args[j] {
    84  				b.Config.Env[i] = newVar
    85  				gotOne = true
    86  				break
    87  			}
    88  		}
    89  		if !gotOne {
    90  			b.Config.Env = append(b.Config.Env, newVar)
    91  		}
    92  		j++
    93  	}
    94  
    95  	return b.commit("", b.Config.Cmd, commitStr)
    96  }
    97  
    98  // MAINTAINER some text <maybe@an.email.address>
    99  //
   100  // Sets the maintainer metadata.
   101  func maintainer(b *builder, args []string, attributes map[string]bool, original string) error {
   102  	if len(args) != 1 {
   103  		return fmt.Errorf("MAINTAINER requires exactly one argument")
   104  	}
   105  
   106  	if err := b.BuilderFlags.Parse(); err != nil {
   107  		return err
   108  	}
   109  
   110  	b.maintainer = args[0]
   111  	return b.commit("", b.Config.Cmd, fmt.Sprintf("MAINTAINER %s", b.maintainer))
   112  }
   113  
   114  // LABEL some json data describing the image
   115  //
   116  // Sets the Label variable foo to bar,
   117  //
   118  func label(b *builder, args []string, attributes map[string]bool, original string) error {
   119  	if len(args) == 0 {
   120  		return fmt.Errorf("LABEL requires at least one argument")
   121  	}
   122  	if len(args)%2 != 0 {
   123  		// should never get here, but just in case
   124  		return fmt.Errorf("Bad input to LABEL, too many args")
   125  	}
   126  
   127  	if err := b.BuilderFlags.Parse(); err != nil {
   128  		return err
   129  	}
   130  
   131  	commitStr := "LABEL"
   132  
   133  	if b.Config.Labels == nil {
   134  		b.Config.Labels = map[string]string{}
   135  	}
   136  
   137  	for j := 0; j < len(args); j++ {
   138  		// name  ==> args[j]
   139  		// value ==> args[j+1]
   140  		newVar := args[j] + "=" + args[j+1] + ""
   141  		commitStr += " " + newVar
   142  
   143  		b.Config.Labels[args[j]] = args[j+1]
   144  		j++
   145  	}
   146  	return b.commit("", b.Config.Cmd, commitStr)
   147  }
   148  
   149  // ADD foo /path
   150  //
   151  // Add the file 'foo' to '/path'. Tarball and Remote URL (git, http) handling
   152  // exist here. If you do not wish to have this automatic handling, use COPY.
   153  //
   154  func add(b *builder, args []string, attributes map[string]bool, original string) error {
   155  	if len(args) < 2 {
   156  		return fmt.Errorf("ADD requires at least two arguments")
   157  	}
   158  
   159  	if err := b.BuilderFlags.Parse(); err != nil {
   160  		return err
   161  	}
   162  
   163  	return b.runContextCommand(args, true, true, "ADD")
   164  }
   165  
   166  // COPY foo /path
   167  //
   168  // Same as 'ADD' but without the tar and remote url handling.
   169  //
   170  func dispatchCopy(b *builder, args []string, attributes map[string]bool, original string) error {
   171  	if len(args) < 2 {
   172  		return fmt.Errorf("COPY requires at least two arguments")
   173  	}
   174  
   175  	if err := b.BuilderFlags.Parse(); err != nil {
   176  		return err
   177  	}
   178  
   179  	return b.runContextCommand(args, false, false, "COPY")
   180  }
   181  
   182  // FROM imagename
   183  //
   184  // This sets the image the dockerfile will build on top of.
   185  //
   186  func from(b *builder, args []string, attributes map[string]bool, original string) error {
   187  	if len(args) != 1 {
   188  		return fmt.Errorf("FROM requires one argument")
   189  	}
   190  
   191  	if err := b.BuilderFlags.Parse(); err != nil {
   192  		return err
   193  	}
   194  
   195  	name := args[0]
   196  
   197  	if name == NoBaseImageSpecifier {
   198  		b.image = ""
   199  		b.noBaseImage = true
   200  		return nil
   201  	}
   202  
   203  	image, err := b.Daemon.Repositories().LookupImage(name)
   204  	if b.Pull {
   205  		image, err = b.pullImage(name)
   206  		if err != nil {
   207  			return err
   208  		}
   209  	}
   210  	if err != nil {
   211  		if b.Daemon.Graph().IsNotExist(err, name) {
   212  			image, err = b.pullImage(name)
   213  		}
   214  
   215  		// note that the top level err will still be !nil here if IsNotExist is
   216  		// not the error. This approach just simplifies the logic a bit.
   217  		if err != nil {
   218  			return err
   219  		}
   220  	}
   221  
   222  	return b.processImageFrom(image)
   223  }
   224  
   225  // ONBUILD RUN echo yo
   226  //
   227  // ONBUILD triggers run when the image is used in a FROM statement.
   228  //
   229  // ONBUILD handling has a lot of special-case functionality, the heading in
   230  // evaluator.go and comments around dispatch() in the same file explain the
   231  // special cases. search for 'OnBuild' in internals.go for additional special
   232  // cases.
   233  //
   234  func onbuild(b *builder, args []string, attributes map[string]bool, original string) error {
   235  	if len(args) == 0 {
   236  		return fmt.Errorf("ONBUILD requires at least one argument")
   237  	}
   238  
   239  	if err := b.BuilderFlags.Parse(); err != nil {
   240  		return err
   241  	}
   242  
   243  	triggerInstruction := strings.ToUpper(strings.TrimSpace(args[0]))
   244  	switch triggerInstruction {
   245  	case "ONBUILD":
   246  		return fmt.Errorf("Chaining ONBUILD via `ONBUILD ONBUILD` isn't allowed")
   247  	case "MAINTAINER", "FROM":
   248  		return fmt.Errorf("%s isn't allowed as an ONBUILD trigger", triggerInstruction)
   249  	}
   250  
   251  	original = regexp.MustCompile(`(?i)^\s*ONBUILD\s*`).ReplaceAllString(original, "")
   252  
   253  	b.Config.OnBuild = append(b.Config.OnBuild, original)
   254  	return b.commit("", b.Config.Cmd, fmt.Sprintf("ONBUILD %s", original))
   255  }
   256  
   257  // WORKDIR /tmp
   258  //
   259  // Set the working directory for future RUN/CMD/etc statements.
   260  //
   261  func workdir(b *builder, args []string, attributes map[string]bool, original string) error {
   262  	if len(args) != 1 {
   263  		return fmt.Errorf("WORKDIR requires exactly one argument")
   264  	}
   265  
   266  	if err := b.BuilderFlags.Parse(); err != nil {
   267  		return err
   268  	}
   269  
   270  	// Note that workdir passed comes from the Dockerfile. Hence it is in
   271  	// Linux format using forward-slashes, even on Windows. However,
   272  	// b.Config.WorkingDir is in platform-specific notation (in other words
   273  	// on Windows will use `\`
   274  	workdir := args[0]
   275  
   276  	isAbs := false
   277  	if runtime.GOOS == "windows" {
   278  		// Alternate processing for Windows here is necessary as we can't call
   279  		// filepath.IsAbs(workDir) as that would verify Windows style paths,
   280  		// along with drive-letters (eg c:\pathto\file.txt). We (arguably
   281  		// correctly or not) check for both forward and back slashes as this
   282  		// is what the 1.4.2 GoLang implementation of IsAbs() does in the
   283  		// isSlash() function.
   284  		isAbs = workdir[0] == '\\' || workdir[0] == '/'
   285  	} else {
   286  		isAbs = filepath.IsAbs(workdir)
   287  	}
   288  
   289  	if !isAbs {
   290  		current := b.Config.WorkingDir
   291  		if runtime.GOOS == "windows" {
   292  			// Convert to Linux format before join
   293  			current = strings.Replace(current, "\\", "/", -1)
   294  		}
   295  		// Must use path.Join so works correctly on Windows, not filepath
   296  		workdir = path.Join("/", current, workdir)
   297  	}
   298  
   299  	// Convert to platform specific format
   300  	if runtime.GOOS == "windows" {
   301  		workdir = strings.Replace(workdir, "/", "\\", -1)
   302  	}
   303  	b.Config.WorkingDir = workdir
   304  
   305  	return b.commit("", b.Config.Cmd, fmt.Sprintf("WORKDIR %v", workdir))
   306  }
   307  
   308  // RUN some command yo
   309  //
   310  // run a command and commit the image. Args are automatically prepended with
   311  // 'sh -c' under linux or 'cmd /S /C' under Windows, in the event there is
   312  // only one argument. The difference in processing:
   313  //
   314  // RUN echo hi          # sh -c echo hi       (Linux)
   315  // RUN echo hi          # cmd /S /C echo hi   (Windows)
   316  // RUN [ "echo", "hi" ] # echo hi
   317  //
   318  func run(b *builder, args []string, attributes map[string]bool, original string) error {
   319  	if b.image == "" && !b.noBaseImage {
   320  		return fmt.Errorf("Please provide a source image with `from` prior to run")
   321  	}
   322  
   323  	if err := b.BuilderFlags.Parse(); err != nil {
   324  		return err
   325  	}
   326  
   327  	args = handleJSONArgs(args, attributes)
   328  
   329  	if !attributes["json"] {
   330  		if runtime.GOOS != "windows" {
   331  			args = append([]string{"/bin/sh", "-c"}, args...)
   332  		} else {
   333  			args = append([]string{"cmd", "/S /C"}, args...)
   334  		}
   335  	}
   336  
   337  	runCmd := flag.NewFlagSet("run", flag.ContinueOnError)
   338  	runCmd.SetOutput(ioutil.Discard)
   339  	runCmd.Usage = nil
   340  
   341  	config, _, _, err := runconfig.Parse(runCmd, append([]string{b.image}, args...))
   342  	if err != nil {
   343  		return err
   344  	}
   345  
   346  	cmd := b.Config.Cmd
   347  	// set Cmd manually, this is special case only for Dockerfiles
   348  	b.Config.Cmd = config.Cmd
   349  	runconfig.Merge(b.Config, config)
   350  
   351  	defer func(cmd *runconfig.Command) { b.Config.Cmd = cmd }(cmd)
   352  
   353  	logrus.Debugf("[BUILDER] Command to be executed: %v", b.Config.Cmd)
   354  
   355  	hit, err := b.probeCache()
   356  	if err != nil {
   357  		return err
   358  	}
   359  	if hit {
   360  		return nil
   361  	}
   362  
   363  	c, err := b.create()
   364  	if err != nil {
   365  		return err
   366  	}
   367  
   368  	// Ensure that we keep the container mounted until the commit
   369  	// to avoid unmounting and then mounting directly again
   370  	c.Mount()
   371  	defer c.Unmount()
   372  
   373  	err = b.run(c)
   374  	if err != nil {
   375  		return err
   376  	}
   377  	if err := b.commit(c.ID, cmd, "run"); err != nil {
   378  		return err
   379  	}
   380  
   381  	return nil
   382  }
   383  
   384  // CMD foo
   385  //
   386  // Set the default command to run in the container (which may be empty).
   387  // Argument handling is the same as RUN.
   388  //
   389  func cmd(b *builder, args []string, attributes map[string]bool, original string) error {
   390  	if err := b.BuilderFlags.Parse(); err != nil {
   391  		return err
   392  	}
   393  
   394  	cmdSlice := handleJSONArgs(args, attributes)
   395  
   396  	if !attributes["json"] {
   397  		if runtime.GOOS != "windows" {
   398  			cmdSlice = append([]string{"/bin/sh", "-c"}, cmdSlice...)
   399  		} else {
   400  			cmdSlice = append([]string{"cmd", "/S /C"}, cmdSlice...)
   401  		}
   402  	}
   403  
   404  	b.Config.Cmd = runconfig.NewCommand(cmdSlice...)
   405  
   406  	if err := b.commit("", b.Config.Cmd, fmt.Sprintf("CMD %q", cmdSlice)); err != nil {
   407  		return err
   408  	}
   409  
   410  	if len(args) != 0 {
   411  		b.cmdSet = true
   412  	}
   413  
   414  	return nil
   415  }
   416  
   417  // ENTRYPOINT /usr/sbin/nginx
   418  //
   419  // Set the entrypoint (which defaults to sh -c on linux, or cmd /S /C on Windows) to
   420  // /usr/sbin/nginx. Will accept the CMD as the arguments to /usr/sbin/nginx.
   421  //
   422  // Handles command processing similar to CMD and RUN, only b.Config.Entrypoint
   423  // is initialized at NewBuilder time instead of through argument parsing.
   424  //
   425  func entrypoint(b *builder, args []string, attributes map[string]bool, original string) error {
   426  	if err := b.BuilderFlags.Parse(); err != nil {
   427  		return err
   428  	}
   429  
   430  	parsed := handleJSONArgs(args, attributes)
   431  
   432  	switch {
   433  	case attributes["json"]:
   434  		// ENTRYPOINT ["echo", "hi"]
   435  		b.Config.Entrypoint = runconfig.NewEntrypoint(parsed...)
   436  	case len(parsed) == 0:
   437  		// ENTRYPOINT []
   438  		b.Config.Entrypoint = nil
   439  	default:
   440  		// ENTRYPOINT echo hi
   441  		if runtime.GOOS != "windows" {
   442  			b.Config.Entrypoint = runconfig.NewEntrypoint("/bin/sh", "-c", parsed[0])
   443  		} else {
   444  			b.Config.Entrypoint = runconfig.NewEntrypoint("cmd", "/S /C", parsed[0])
   445  		}
   446  	}
   447  
   448  	// when setting the entrypoint if a CMD was not explicitly set then
   449  	// set the command to nil
   450  	if !b.cmdSet {
   451  		b.Config.Cmd = nil
   452  	}
   453  
   454  	if err := b.commit("", b.Config.Cmd, fmt.Sprintf("ENTRYPOINT %q", b.Config.Entrypoint)); err != nil {
   455  		return err
   456  	}
   457  
   458  	return nil
   459  }
   460  
   461  // EXPOSE 6667/tcp 7000/tcp
   462  //
   463  // Expose ports for links and port mappings. This all ends up in
   464  // b.Config.ExposedPorts for runconfig.
   465  //
   466  func expose(b *builder, args []string, attributes map[string]bool, original string) error {
   467  	portsTab := args
   468  
   469  	if len(args) == 0 {
   470  		return fmt.Errorf("EXPOSE requires at least one argument")
   471  	}
   472  
   473  	if err := b.BuilderFlags.Parse(); err != nil {
   474  		return err
   475  	}
   476  
   477  	if b.Config.ExposedPorts == nil {
   478  		b.Config.ExposedPorts = make(nat.PortSet)
   479  	}
   480  
   481  	ports, _, err := nat.ParsePortSpecs(portsTab)
   482  	if err != nil {
   483  		return err
   484  	}
   485  
   486  	// instead of using ports directly, we build a list of ports and sort it so
   487  	// the order is consistent. This prevents cache burst where map ordering
   488  	// changes between builds
   489  	portList := make([]string, len(ports))
   490  	var i int
   491  	for port := range ports {
   492  		if _, exists := b.Config.ExposedPorts[port]; !exists {
   493  			b.Config.ExposedPorts[port] = struct{}{}
   494  		}
   495  		portList[i] = string(port)
   496  		i++
   497  	}
   498  	sort.Strings(portList)
   499  	return b.commit("", b.Config.Cmd, fmt.Sprintf("EXPOSE %s", strings.Join(portList, " ")))
   500  }
   501  
   502  // USER foo
   503  //
   504  // Set the user to 'foo' for future commands and when running the
   505  // ENTRYPOINT/CMD at container run time.
   506  //
   507  func user(b *builder, args []string, attributes map[string]bool, original string) error {
   508  	if runtime.GOOS == "windows" {
   509  		return fmt.Errorf("USER is not supported on Windows")
   510  	}
   511  
   512  	if len(args) != 1 {
   513  		return fmt.Errorf("USER requires exactly one argument")
   514  	}
   515  
   516  	if err := b.BuilderFlags.Parse(); err != nil {
   517  		return err
   518  	}
   519  
   520  	b.Config.User = args[0]
   521  	return b.commit("", b.Config.Cmd, fmt.Sprintf("USER %v", args))
   522  }
   523  
   524  // VOLUME /foo
   525  //
   526  // Expose the volume /foo for use. Will also accept the JSON array form.
   527  //
   528  func volume(b *builder, args []string, attributes map[string]bool, original string) error {
   529  	if runtime.GOOS == "windows" {
   530  		return fmt.Errorf("VOLUME is not supported on Windows")
   531  	}
   532  	if len(args) == 0 {
   533  		return fmt.Errorf("VOLUME requires at least one argument")
   534  	}
   535  
   536  	if err := b.BuilderFlags.Parse(); err != nil {
   537  		return err
   538  	}
   539  
   540  	if b.Config.Volumes == nil {
   541  		b.Config.Volumes = map[string]struct{}{}
   542  	}
   543  	for _, v := range args {
   544  		v = strings.TrimSpace(v)
   545  		if v == "" {
   546  			return fmt.Errorf("Volume specified can not be an empty string")
   547  		}
   548  		b.Config.Volumes[v] = struct{}{}
   549  	}
   550  	if err := b.commit("", b.Config.Cmd, fmt.Sprintf("VOLUME %v", args)); err != nil {
   551  		return err
   552  	}
   553  	return nil
   554  }