evaluator.go 10.0 KB

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