github.com/hustcat/docker@v1.3.3-0.20160314103604-901c67a8eeab/builder/dockerfile/evaluator.go (about)

     1  // Package dockerfile is the evaluation step in the Dockerfile parse/evaluate pipeline.
     2  //
     3  // It incorporates a dispatch table based on the parser.Node values (see the
     4  // parser package for more information) that are yielded from the parser itself.
     5  // Calling NewBuilder with the BuildOpts struct can be used to customize the
     6  // experience for execution purposes only. Parsing is controlled in the parser
     7  // package, and this division of responsibility should be respected.
     8  //
     9  // Please see the jump table targets for the actual invocations, most of which
    10  // will call out to the functions in internals.go to deal with their tasks.
    11  //
    12  // ONBUILD is a special case, which is covered in the onbuild() func in
    13  // dispatchers.go.
    14  //
    15  // The evaluator uses the concept of "steps", which are usually each processable
    16  // line in the Dockerfile. Each step is numbered and certain actions are taken
    17  // before and after each step, such as creating an image ID and removing temporary
    18  // containers and images. Note that ONBUILD creates a kinda-sorta "sub run" which
    19  // includes its own set of steps (usually only one of them).
    20  package dockerfile
    21  
    22  import (
    23  	"fmt"
    24  	"runtime"
    25  	"strings"
    26  
    27  	"github.com/docker/docker/builder/dockerfile/command"
    28  	"github.com/docker/docker/builder/dockerfile/parser"
    29  )
    30  
    31  // Environment variable interpolation will happen on these statements only.
    32  var replaceEnvAllowed = map[string]bool{
    33  	command.Env:        true,
    34  	command.Label:      true,
    35  	command.Add:        true,
    36  	command.Copy:       true,
    37  	command.Workdir:    true,
    38  	command.Expose:     true,
    39  	command.Volume:     true,
    40  	command.User:       true,
    41  	command.StopSignal: true,
    42  	command.Arg:        true,
    43  }
    44  
    45  // Certain commands are allowed to have their args split into more
    46  // words after env var replacements. Meaning:
    47  //   ENV foo="123 456"
    48  //   EXPOSE $foo
    49  // should result in the same thing as:
    50  //   EXPOSE 123 456
    51  // and not treat "123 456" as a single word.
    52  // Note that: EXPOSE "$foo" and EXPOSE $foo are not the same thing.
    53  // Quotes will cause it to still be treated as single word.
    54  var allowWordExpansion = map[string]bool{
    55  	command.Expose: true,
    56  }
    57  
    58  var evaluateTable map[string]func(*Builder, []string, map[string]bool, string) error
    59  
    60  func init() {
    61  	evaluateTable = map[string]func(*Builder, []string, map[string]bool, string) error{
    62  		command.Env:        env,
    63  		command.Label:      label,
    64  		command.Maintainer: maintainer,
    65  		command.Add:        add,
    66  		command.Copy:       dispatchCopy, // copy() is a go builtin
    67  		command.From:       from,
    68  		command.Onbuild:    onbuild,
    69  		command.Workdir:    workdir,
    70  		command.Run:        run,
    71  		command.Cmd:        cmd,
    72  		command.Entrypoint: entrypoint,
    73  		command.Expose:     expose,
    74  		command.Volume:     volume,
    75  		command.User:       user,
    76  		command.StopSignal: stopSignal,
    77  		command.Arg:        arg,
    78  	}
    79  }
    80  
    81  // This method is the entrypoint to all statement handling routines.
    82  //
    83  // Almost all nodes will have this structure:
    84  // Child[Node, Node, Node] where Child is from parser.Node.Children and each
    85  // node comes from parser.Node.Next. This forms a "line" with a statement and
    86  // arguments and we process them in this normalized form by hitting
    87  // evaluateTable with the leaf nodes of the command and the Builder object.
    88  //
    89  // ONBUILD is a special case; in this case the parser will emit:
    90  // Child[Node, Child[Node, Node...]] where the first node is the literal
    91  // "onbuild" and the child entrypoint is the command of the ONBUILD statement,
    92  // such as `RUN` in ONBUILD RUN foo. There is special case logic in here to
    93  // deal with that, at least until it becomes more of a general concern with new
    94  // features.
    95  func (b *Builder) dispatch(stepN int, ast *parser.Node) error {
    96  	cmd := ast.Value
    97  	upperCasedCmd := strings.ToUpper(cmd)
    98  
    99  	// To ensure the user is given a decent error message if the platform
   100  	// on which the daemon is running does not support a builder command.
   101  	if err := platformSupports(strings.ToLower(cmd)); err != nil {
   102  		return err
   103  	}
   104  
   105  	attrs := ast.Attributes
   106  	original := ast.Original
   107  	flags := ast.Flags
   108  	strList := []string{}
   109  	msg := fmt.Sprintf("Step %d : %s", stepN+1, upperCasedCmd)
   110  
   111  	if len(ast.Flags) > 0 {
   112  		msg += " " + strings.Join(ast.Flags, " ")
   113  	}
   114  
   115  	if cmd == "onbuild" {
   116  		if ast.Next == nil {
   117  			return fmt.Errorf("ONBUILD requires at least one argument")
   118  		}
   119  		ast = ast.Next.Children[0]
   120  		strList = append(strList, ast.Value)
   121  		msg += " " + ast.Value
   122  
   123  		if len(ast.Flags) > 0 {
   124  			msg += " " + strings.Join(ast.Flags, " ")
   125  		}
   126  
   127  	}
   128  
   129  	// count the number of nodes that we are going to traverse first
   130  	// so we can pre-create the argument and message array. This speeds up the
   131  	// allocation of those list a lot when they have a lot of arguments
   132  	cursor := ast
   133  	var n int
   134  	for cursor.Next != nil {
   135  		cursor = cursor.Next
   136  		n++
   137  	}
   138  	msgList := make([]string, n)
   139  
   140  	var i int
   141  	// Append the build-time args to config-environment.
   142  	// This allows builder config to override the variables, making the behavior similar to
   143  	// a shell script i.e. `ENV foo bar` overrides value of `foo` passed in build
   144  	// context. But `ENV foo $foo` will use the value from build context if one
   145  	// isn't already been defined by a previous ENV primitive.
   146  	// Note, we get this behavior because we know that ProcessWord() will
   147  	// stop on the first occurrence of a variable name and not notice
   148  	// a subsequent one. So, putting the buildArgs list after the Config.Env
   149  	// list, in 'envs', is safe.
   150  	envs := b.runConfig.Env
   151  	for key, val := range b.options.BuildArgs {
   152  		if !b.isBuildArgAllowed(key) {
   153  			// skip build-args that are not in allowed list, meaning they have
   154  			// not been defined by an "ARG" Dockerfile command yet.
   155  			// This is an error condition but only if there is no "ARG" in the entire
   156  			// Dockerfile, so we'll generate any necessary errors after we parsed
   157  			// the entire file (see 'leftoverArgs' processing in evaluator.go )
   158  			continue
   159  		}
   160  		envs = append(envs, fmt.Sprintf("%s=%s", key, val))
   161  	}
   162  	for ast.Next != nil {
   163  		ast = ast.Next
   164  		var str string
   165  		str = ast.Value
   166  		if replaceEnvAllowed[cmd] {
   167  			var err error
   168  			var words []string
   169  
   170  			if allowWordExpansion[cmd] {
   171  				words, err = ProcessWords(str, envs)
   172  				if err != nil {
   173  					return err
   174  				}
   175  				strList = append(strList, words...)
   176  			} else {
   177  				str, err = ProcessWord(str, envs)
   178  				if err != nil {
   179  					return err
   180  				}
   181  				strList = append(strList, str)
   182  			}
   183  		} else {
   184  			strList = append(strList, str)
   185  		}
   186  		msgList[i] = ast.Value
   187  		i++
   188  	}
   189  
   190  	msg += " " + strings.Join(msgList, " ")
   191  	fmt.Fprintln(b.Stdout, msg)
   192  
   193  	// XXX yes, we skip any cmds that are not valid; the parser should have
   194  	// picked these out already.
   195  	if f, ok := evaluateTable[cmd]; ok {
   196  		b.flags = NewBFlags()
   197  		b.flags.Args = flags
   198  		return f(b, strList, attrs, original)
   199  	}
   200  
   201  	return fmt.Errorf("Unknown instruction: %s", upperCasedCmd)
   202  }
   203  
   204  // platformSupports is a short-term function to give users a quality error
   205  // message if a Dockerfile uses a command not supported on the platform.
   206  func platformSupports(command string) error {
   207  	if runtime.GOOS != "windows" {
   208  		return nil
   209  	}
   210  	switch command {
   211  	case "expose", "user", "stopsignal", "arg":
   212  		return fmt.Errorf("The daemon on this platform does not support the command '%s'", command)
   213  	}
   214  	return nil
   215  }