evaluator.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  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. import (
  22. "errors"
  23. "fmt"
  24. "strings"
  25. "github.com/docker/docker/builder/dockerfile/command"
  26. "github.com/docker/docker/builder/dockerfile/parser"
  27. )
  28. // Environment variable interpolation will happen on these statements only.
  29. var replaceEnvAllowed = map[string]bool{
  30. command.Env: true,
  31. command.Label: true,
  32. command.Add: true,
  33. command.Copy: true,
  34. command.Workdir: true,
  35. command.Expose: true,
  36. command.Volume: true,
  37. command.User: true,
  38. command.StopSignal: true,
  39. command.Arg: true,
  40. }
  41. // Certain commands are allowed to have their args split into more
  42. // words after env var replacements. Meaning:
  43. // ENV foo="123 456"
  44. // EXPOSE $foo
  45. // should result in the same thing as:
  46. // EXPOSE 123 456
  47. // and not treat "123 456" as a single word.
  48. // Note that: EXPOSE "$foo" and EXPOSE $foo are not the same thing.
  49. // Quotes will cause it to still be treated as single word.
  50. var allowWordExpansion = map[string]bool{
  51. command.Expose: true,
  52. }
  53. var evaluateTable map[string]func(*Builder, []string, map[string]bool, string) error
  54. func init() {
  55. evaluateTable = map[string]func(*Builder, []string, map[string]bool, string) error{
  56. command.Add: add,
  57. command.Arg: arg,
  58. command.Cmd: cmd,
  59. command.Copy: dispatchCopy, // copy() is a go builtin
  60. command.Entrypoint: entrypoint,
  61. command.Env: env,
  62. command.Expose: expose,
  63. command.From: from,
  64. command.Healthcheck: healthcheck,
  65. command.Label: label,
  66. command.Maintainer: maintainer,
  67. command.Onbuild: onbuild,
  68. command.Run: run,
  69. command.Shell: shell,
  70. command.StopSignal: stopSignal,
  71. command.User: user,
  72. command.Volume: volume,
  73. command.Workdir: workdir,
  74. }
  75. }
  76. // This method is the entrypoint to all statement handling routines.
  77. //
  78. // Almost all nodes will have this structure:
  79. // Child[Node, Node, Node] where Child is from parser.Node.Children and each
  80. // node comes from parser.Node.Next. This forms a "line" with a statement and
  81. // arguments and we process them in this normalized form by hitting
  82. // evaluateTable with the leaf nodes of the command and the Builder object.
  83. //
  84. // ONBUILD is a special case; in this case the parser will emit:
  85. // Child[Node, Child[Node, Node...]] where the first node is the literal
  86. // "onbuild" and the child entrypoint is the command of the ONBUILD statement,
  87. // such as `RUN` in ONBUILD RUN foo. There is special case logic in here to
  88. // deal with that, at least until it becomes more of a general concern with new
  89. // features.
  90. func (b *Builder) dispatch(stepN int, stepTotal int, ast *parser.Node) error {
  91. cmd := ast.Value
  92. upperCasedCmd := strings.ToUpper(cmd)
  93. // To ensure the user is given a decent error message if the platform
  94. // on which the daemon is running does not support a builder command.
  95. if err := platformSupports(strings.ToLower(cmd)); err != nil {
  96. return err
  97. }
  98. attrs := ast.Attributes
  99. original := ast.Original
  100. flags := ast.Flags
  101. strList := []string{}
  102. msg := fmt.Sprintf("Step %d/%d : %s", stepN+1, stepTotal, upperCasedCmd)
  103. if len(ast.Flags) > 0 {
  104. msg += " " + strings.Join(ast.Flags, " ")
  105. }
  106. if cmd == "onbuild" {
  107. if ast.Next == nil {
  108. return errors.New("ONBUILD requires at least one argument")
  109. }
  110. ast = ast.Next.Children[0]
  111. strList = append(strList, ast.Value)
  112. msg += " " + ast.Value
  113. if len(ast.Flags) > 0 {
  114. msg += " " + strings.Join(ast.Flags, " ")
  115. }
  116. }
  117. // count the number of nodes that we are going to traverse first
  118. // so we can pre-create the argument and message array. This speeds up the
  119. // allocation of those list a lot when they have a lot of arguments
  120. cursor := ast
  121. var n int
  122. for cursor.Next != nil {
  123. cursor = cursor.Next
  124. n++
  125. }
  126. msgList := make([]string, n)
  127. var i int
  128. // Append the build-time args to config-environment.
  129. // This allows builder config to override the variables, making the behavior similar to
  130. // a shell script i.e. `ENV foo bar` overrides value of `foo` passed in build
  131. // context. But `ENV foo $foo` will use the value from build context if one
  132. // isn't already been defined by a previous ENV primitive.
  133. // Note, we get this behavior because we know that ProcessWord() will
  134. // stop on the first occurrence of a variable name and not notice
  135. // a subsequent one. So, putting the buildArgs list after the Config.Env
  136. // list, in 'envs', is safe.
  137. envs := b.runConfig.Env
  138. for key, val := range b.options.BuildArgs {
  139. if !b.isBuildArgAllowed(key) {
  140. // skip build-args that are not in allowed list, meaning they have
  141. // not been defined by an "ARG" Dockerfile command yet.
  142. // This is an error condition but only if there is no "ARG" in the entire
  143. // Dockerfile, so we'll generate any necessary errors after we parsed
  144. // the entire file (see 'leftoverArgs' processing in evaluator.go )
  145. continue
  146. }
  147. envs = append(envs, fmt.Sprintf("%s=%s", key, *val))
  148. }
  149. for ast.Next != nil {
  150. ast = ast.Next
  151. var str string
  152. str = ast.Value
  153. if replaceEnvAllowed[cmd] {
  154. var err error
  155. var words []string
  156. if allowWordExpansion[cmd] {
  157. words, err = ProcessWords(str, envs, b.directive.EscapeToken)
  158. if err != nil {
  159. return err
  160. }
  161. strList = append(strList, words...)
  162. } else {
  163. str, err = ProcessWord(str, envs, b.directive.EscapeToken)
  164. if err != nil {
  165. return err
  166. }
  167. strList = append(strList, str)
  168. }
  169. } else {
  170. strList = append(strList, str)
  171. }
  172. msgList[i] = ast.Value
  173. i++
  174. }
  175. msg += " " + strings.Join(msgList, " ")
  176. fmt.Fprintln(b.Stdout, msg)
  177. // XXX yes, we skip any cmds that are not valid; the parser should have
  178. // picked these out already.
  179. if f, ok := evaluateTable[cmd]; ok {
  180. b.flags = NewBFlags()
  181. b.flags.Args = flags
  182. return f(b, strList, attrs, original)
  183. }
  184. return fmt.Errorf("Unknown instruction: %s", upperCasedCmd)
  185. }
  186. // checkDispatch does a simple check for syntax errors of the Dockerfile.
  187. // Because some of the instructions can only be validated through runtime,
  188. // arg, env, etc., this syntax check will not be complete and could not replace
  189. // the runtime check. Instead, this function is only a helper that allows
  190. // user to find out the obvious error in Dockerfile earlier on.
  191. // onbuild bool: indicate if instruction XXX is part of `ONBUILD XXX` trigger
  192. func (b *Builder) checkDispatch(ast *parser.Node, onbuild bool) error {
  193. cmd := ast.Value
  194. upperCasedCmd := strings.ToUpper(cmd)
  195. // To ensure the user is given a decent error message if the platform
  196. // on which the daemon is running does not support a builder command.
  197. if err := platformSupports(strings.ToLower(cmd)); err != nil {
  198. return err
  199. }
  200. // The instruction itself is ONBUILD, we will make sure it follows with at
  201. // least one argument
  202. if upperCasedCmd == "ONBUILD" {
  203. if ast.Next == nil {
  204. return errors.New("ONBUILD requires at least one argument")
  205. }
  206. }
  207. // The instruction is part of ONBUILD trigger (not the instruction itself)
  208. if onbuild {
  209. switch upperCasedCmd {
  210. case "ONBUILD":
  211. return errors.New("Chaining ONBUILD via `ONBUILD ONBUILD` isn't allowed")
  212. case "MAINTAINER", "FROM":
  213. return fmt.Errorf("%s isn't allowed as an ONBUILD trigger", upperCasedCmd)
  214. }
  215. }
  216. if _, ok := evaluateTable[cmd]; ok {
  217. return nil
  218. }
  219. return fmt.Errorf("Unknown instruction: %s", upperCasedCmd)
  220. }