evaluator.go 9.9 KB

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