evaluator.go 7.8 KB

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