evaluator.go 10 KB

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