evaluator.go 8.1 KB

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