evaluator.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  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"
  27. "github.com/docker/docker/builder/dockerfile/command"
  28. "github.com/docker/docker/builder/dockerfile/parser"
  29. "github.com/docker/docker/runconfig/opts"
  30. "github.com/pkg/errors"
  31. )
  32. // Environment variable interpolation will happen on these statements only.
  33. var replaceEnvAllowed = map[string]bool{
  34. command.Env: true,
  35. command.Label: true,
  36. command.Add: true,
  37. command.Copy: true,
  38. command.Workdir: true,
  39. command.Expose: true,
  40. command.Volume: true,
  41. command.User: true,
  42. command.StopSignal: true,
  43. command.Arg: true,
  44. }
  45. // Certain commands are allowed to have their args split into more
  46. // words after env var replacements. Meaning:
  47. // ENV foo="123 456"
  48. // EXPOSE $foo
  49. // should result in the same thing as:
  50. // EXPOSE 123 456
  51. // and not treat "123 456" as a single word.
  52. // Note that: EXPOSE "$foo" and EXPOSE $foo are not the same thing.
  53. // Quotes will cause it to still be treated as single word.
  54. var allowWordExpansion = map[string]bool{
  55. command.Expose: true,
  56. }
  57. type dispatchRequest struct {
  58. builder *Builder // TODO: replace this with a smaller interface
  59. args []string
  60. attributes map[string]bool
  61. flags *BFlags
  62. original string
  63. shlex *ShellLex
  64. state *dispatchState
  65. }
  66. func newDispatchRequestFromOptions(options dispatchOptions, builder *Builder, args []string) dispatchRequest {
  67. return dispatchRequest{
  68. builder: builder,
  69. args: args,
  70. attributes: options.node.Attributes,
  71. original: options.node.Original,
  72. flags: NewBFlagsWithArgs(options.node.Flags),
  73. shlex: options.shlex,
  74. state: options.state,
  75. }
  76. }
  77. type dispatcher func(dispatchRequest) error
  78. var evaluateTable map[string]dispatcher
  79. func init() {
  80. evaluateTable = map[string]dispatcher{
  81. command.Add: add,
  82. command.Arg: arg,
  83. command.Cmd: cmd,
  84. command.Copy: dispatchCopy, // copy() is a go builtin
  85. command.Entrypoint: entrypoint,
  86. command.Env: env,
  87. command.Expose: expose,
  88. command.From: from,
  89. command.Healthcheck: healthcheck,
  90. command.Label: label,
  91. command.Maintainer: maintainer,
  92. command.Onbuild: onbuild,
  93. command.Run: run,
  94. command.Shell: shell,
  95. command.StopSignal: stopSignal,
  96. command.User: user,
  97. command.Volume: volume,
  98. command.Workdir: workdir,
  99. }
  100. }
  101. func formatStep(stepN int, stepTotal int) string {
  102. return fmt.Sprintf("%d/%d", stepN+1, stepTotal)
  103. }
  104. // This method is the entrypoint to all statement handling routines.
  105. //
  106. // Almost all nodes will have this structure:
  107. // Child[Node, Node, Node] where Child is from parser.Node.Children and each
  108. // node comes from parser.Node.Next. This forms a "line" with a statement and
  109. // arguments and we process them in this normalized form by hitting
  110. // evaluateTable with the leaf nodes of the command and the Builder object.
  111. //
  112. // ONBUILD is a special case; in this case the parser will emit:
  113. // Child[Node, Child[Node, Node...]] where the first node is the literal
  114. // "onbuild" and the child entrypoint is the command of the ONBUILD statement,
  115. // such as `RUN` in ONBUILD RUN foo. There is special case logic in here to
  116. // deal with that, at least until it becomes more of a general concern with new
  117. // features.
  118. func (b *Builder) dispatch(options dispatchOptions) (*dispatchState, error) {
  119. node := options.node
  120. cmd := node.Value
  121. upperCasedCmd := strings.ToUpper(cmd)
  122. // To ensure the user is given a decent error message if the platform
  123. // on which the daemon is running does not support a builder command.
  124. if err := platformSupports(strings.ToLower(cmd)); err != nil {
  125. buildsFailed.WithValues(metricsCommandNotSupportedError).Inc()
  126. return nil, err
  127. }
  128. msg := bytes.NewBufferString(fmt.Sprintf("Step %s : %s%s",
  129. options.stepMsg, upperCasedCmd, formatFlags(node.Flags)))
  130. args := []string{}
  131. ast := node
  132. if cmd == command.Onbuild {
  133. var err error
  134. ast, args, err = handleOnBuildNode(node, msg)
  135. if err != nil {
  136. return nil, err
  137. }
  138. }
  139. runConfigEnv := options.state.runConfig.Env
  140. envs := append(runConfigEnv, b.buildArgs.FilterAllowed(runConfigEnv)...)
  141. processFunc := createProcessWordFunc(options.shlex, cmd, envs)
  142. words, err := getDispatchArgsFromNode(ast, processFunc, msg)
  143. if err != nil {
  144. buildsFailed.WithValues(metricsErrorProcessingCommandsError).Inc()
  145. return nil, err
  146. }
  147. args = append(args, words...)
  148. fmt.Fprintln(b.Stdout, msg.String())
  149. f, ok := evaluateTable[cmd]
  150. if !ok {
  151. buildsFailed.WithValues(metricsUnknownInstructionError).Inc()
  152. return nil, fmt.Errorf("unknown instruction: %s", upperCasedCmd)
  153. }
  154. if err := f(newDispatchRequestFromOptions(options, b, args)); err != nil {
  155. return nil, err
  156. }
  157. options.state.updateRunConfig()
  158. return options.state, nil
  159. }
  160. type dispatchOptions struct {
  161. state *dispatchState
  162. stepMsg string
  163. node *parser.Node
  164. shlex *ShellLex
  165. }
  166. // dispatchState is a data object which is modified by dispatchers
  167. type dispatchState struct {
  168. runConfig *container.Config
  169. maintainer string
  170. cmdSet bool
  171. noBaseImage bool
  172. imageID string
  173. baseImage builder.Image
  174. stageName string
  175. }
  176. func newDispatchState() *dispatchState {
  177. return &dispatchState{runConfig: &container.Config{}}
  178. }
  179. func (r *dispatchState) updateRunConfig() {
  180. r.runConfig.Image = r.imageID
  181. }
  182. // hasFromImage returns true if the builder has processed a `FROM <image>` line
  183. func (r *dispatchState) hasFromImage() bool {
  184. return r.imageID != "" || r.noBaseImage
  185. }
  186. func (r *dispatchState) runConfigEnvMapping() map[string]string {
  187. return opts.ConvertKVStringsToMap(r.runConfig.Env)
  188. }
  189. func (r *dispatchState) isCurrentStage(target string) bool {
  190. if target == "" {
  191. return false
  192. }
  193. return strings.EqualFold(r.stageName, target)
  194. }
  195. func handleOnBuildNode(ast *parser.Node, msg *bytes.Buffer) (*parser.Node, []string, error) {
  196. if ast.Next == nil {
  197. return nil, nil, errors.New("ONBUILD requires at least one argument")
  198. }
  199. ast = ast.Next.Children[0]
  200. msg.WriteString(" " + ast.Value + formatFlags(ast.Flags))
  201. return ast, []string{ast.Value}, nil
  202. }
  203. func formatFlags(flags []string) string {
  204. if len(flags) > 0 {
  205. return " " + strings.Join(flags, " ")
  206. }
  207. return ""
  208. }
  209. func getDispatchArgsFromNode(ast *parser.Node, processFunc processWordFunc, msg *bytes.Buffer) ([]string, error) {
  210. args := []string{}
  211. for i := 0; ast.Next != nil; i++ {
  212. ast = ast.Next
  213. words, err := processFunc(ast.Value)
  214. if err != nil {
  215. return nil, err
  216. }
  217. args = append(args, words...)
  218. msg.WriteString(" " + ast.Value)
  219. }
  220. return args, nil
  221. }
  222. type processWordFunc func(string) ([]string, error)
  223. func createProcessWordFunc(shlex *ShellLex, cmd string, envs []string) processWordFunc {
  224. switch {
  225. case !replaceEnvAllowed[cmd]:
  226. return func(word string) ([]string, error) {
  227. return []string{word}, nil
  228. }
  229. case allowWordExpansion[cmd]:
  230. return func(word string) ([]string, error) {
  231. return shlex.ProcessWords(word, envs)
  232. }
  233. default:
  234. return func(word string) ([]string, error) {
  235. word, err := shlex.ProcessWord(word, envs)
  236. return []string{word}, err
  237. }
  238. }
  239. }
  240. // checkDispatch does a simple check for syntax errors of the Dockerfile.
  241. // Because some of the instructions can only be validated through runtime,
  242. // arg, env, etc., this syntax check will not be complete and could not replace
  243. // the runtime check. Instead, this function is only a helper that allows
  244. // user to find out the obvious error in Dockerfile earlier on.
  245. func checkDispatch(ast *parser.Node) error {
  246. cmd := ast.Value
  247. upperCasedCmd := strings.ToUpper(cmd)
  248. // To ensure the user is given a decent error message if the platform
  249. // on which the daemon is running does not support a builder command.
  250. if err := platformSupports(strings.ToLower(cmd)); err != nil {
  251. return err
  252. }
  253. // The instruction itself is ONBUILD, we will make sure it follows with at
  254. // least one argument
  255. if upperCasedCmd == "ONBUILD" {
  256. if ast.Next == nil {
  257. buildsFailed.WithValues(metricsMissingOnbuildArgumentsError).Inc()
  258. return errors.New("ONBUILD requires at least one argument")
  259. }
  260. }
  261. if _, ok := evaluateTable[cmd]; ok {
  262. return nil
  263. }
  264. buildsFailed.WithValues(metricsUnknownInstructionError).Inc()
  265. return errors.Errorf("unknown instruction: %s", upperCasedCmd)
  266. }