evaluator.go 8.3 KB

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