evaluator.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  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. "github.com/docker/docker/runconfig/opts"
  27. "github.com/pkg/errors"
  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. msgList := initMsgList(ast)
  119. // Append build args to runConfig environment variables
  120. envs := append(b.runConfig.Env, b.buildArgsWithoutConfigEnv()...)
  121. for i := 0; ast.Next != nil; i++ {
  122. ast = ast.Next
  123. words, err := b.evaluateEnv(cmd, ast.Value, envs)
  124. if err != nil {
  125. return err
  126. }
  127. strList = append(strList, words...)
  128. msgList[i] = ast.Value
  129. }
  130. msg += " " + strings.Join(msgList, " ")
  131. fmt.Fprintln(b.Stdout, msg)
  132. // XXX yes, we skip any cmds that are not valid; the parser should have
  133. // picked these out already.
  134. if f, ok := evaluateTable[cmd]; ok {
  135. b.flags = NewBFlags()
  136. b.flags.Args = flags
  137. return f(b, strList, attrs, original)
  138. }
  139. return fmt.Errorf("Unknown instruction: %s", upperCasedCmd)
  140. }
  141. // count the number of nodes that we are going to traverse first
  142. // allocation of those list a lot when they have a lot of arguments
  143. func initMsgList(cursor *parser.Node) []string {
  144. var n int
  145. for ; cursor.Next != nil; n++ {
  146. cursor = cursor.Next
  147. }
  148. return make([]string, n)
  149. }
  150. func (b *Builder) evaluateEnv(cmd string, str string, envs []string) ([]string, error) {
  151. if !replaceEnvAllowed[cmd] {
  152. return []string{str}, nil
  153. }
  154. var processFunc func(string, []string, rune) ([]string, error)
  155. if allowWordExpansion[cmd] {
  156. processFunc = ProcessWords
  157. } else {
  158. processFunc = func(word string, envs []string, escape rune) ([]string, error) {
  159. word, err := ProcessWord(word, envs, escape)
  160. return []string{word}, err
  161. }
  162. }
  163. return processFunc(str, envs, b.directive.EscapeToken)
  164. }
  165. // buildArgsWithoutConfigEnv returns a list of key=value pairs for all the build
  166. // args that are not overriden by runConfig environment variables.
  167. func (b *Builder) buildArgsWithoutConfigEnv() []string {
  168. envs := []string{}
  169. configEnv := b.runConfigEnvMapping()
  170. for key, val := range b.buildArgs.GetAllAllowed() {
  171. if _, ok := configEnv[key]; !ok {
  172. envs = append(envs, fmt.Sprintf("%s=%s", key, val))
  173. }
  174. }
  175. return envs
  176. }
  177. func (b *Builder) runConfigEnvMapping() map[string]string {
  178. return opts.ConvertKVStringsToMap(b.runConfig.Env)
  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. func checkDispatch(ast *parser.Node) error {
  186. cmd := ast.Value
  187. upperCasedCmd := strings.ToUpper(cmd)
  188. // To ensure the user is given a decent error message if the platform
  189. // on which the daemon is running does not support a builder command.
  190. if err := platformSupports(strings.ToLower(cmd)); err != nil {
  191. return err
  192. }
  193. // The instruction itself is ONBUILD, we will make sure it follows with at
  194. // least one argument
  195. if upperCasedCmd == "ONBUILD" {
  196. if ast.Next == nil {
  197. return errors.New("ONBUILD requires at least one argument")
  198. }
  199. }
  200. if _, ok := evaluateTable[cmd]; ok {
  201. return nil
  202. }
  203. return errors.Errorf("unknown instruction: %s", upperCasedCmd)
  204. }