evaluator.go 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. // builder 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 resposibility 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 builder
  21. import (
  22. "errors"
  23. "fmt"
  24. "io"
  25. "os"
  26. "path"
  27. "strings"
  28. "github.com/docker/docker/builder/parser"
  29. "github.com/docker/docker/daemon"
  30. "github.com/docker/docker/engine"
  31. "github.com/docker/docker/pkg/log"
  32. "github.com/docker/docker/pkg/tarsum"
  33. "github.com/docker/docker/registry"
  34. "github.com/docker/docker/runconfig"
  35. "github.com/docker/docker/utils"
  36. )
  37. var (
  38. ErrDockerfileEmpty = errors.New("Dockerfile cannot be empty")
  39. )
  40. var evaluateTable map[string]func(*Builder, []string, map[string]bool) error
  41. func init() {
  42. evaluateTable = map[string]func(*Builder, []string, map[string]bool) error{
  43. "env": env,
  44. "maintainer": maintainer,
  45. "add": add,
  46. "copy": dispatchCopy, // copy() is a go builtin
  47. "from": from,
  48. "onbuild": onbuild,
  49. "workdir": workdir,
  50. "docker-version": nullDispatch, // we don't care about docker-version
  51. "run": run,
  52. "cmd": cmd,
  53. "entrypoint": entrypoint,
  54. "expose": expose,
  55. "volume": volume,
  56. "user": user,
  57. "insert": insert,
  58. }
  59. }
  60. // internal struct, used to maintain configuration of the Dockerfile's
  61. // processing as it evaluates the parsing result.
  62. type Builder struct {
  63. Daemon *daemon.Daemon
  64. Engine *engine.Engine
  65. // effectively stdio for the run. Because it is not stdio, I said
  66. // "Effectively". Do not use stdio anywhere in this package for any reason.
  67. OutStream io.Writer
  68. ErrStream io.Writer
  69. Verbose bool
  70. UtilizeCache bool
  71. // controls how images and containers are handled between steps.
  72. Remove bool
  73. ForceRemove bool
  74. AuthConfig *registry.AuthConfig
  75. AuthConfigFile *registry.ConfigFile
  76. // Deprecated, original writer used for ImagePull. To be removed.
  77. OutOld io.Writer
  78. StreamFormatter *utils.StreamFormatter
  79. Config *runconfig.Config // runconfig for cmd, run, entrypoint etc.
  80. // both of these are controlled by the Remove and ForceRemove options in BuildOpts
  81. TmpContainers map[string]struct{} // a map of containers used for removes
  82. dockerfile *parser.Node // the syntax tree of the dockerfile
  83. image string // image name for commit processing
  84. maintainer string // maintainer name. could probably be removed.
  85. cmdSet bool // indicates is CMD was set in current Dockerfile
  86. context tarsum.TarSum // the context is a tarball that is uploaded by the client
  87. contextPath string // the path of the temporary directory the local context is unpacked to (server side)
  88. }
  89. // Run the builder with the context. This is the lynchpin of this package. This
  90. // will (barring errors):
  91. //
  92. // * call readContext() which will set up the temporary directory and unpack
  93. // the context into it.
  94. // * read the dockerfile
  95. // * parse the dockerfile
  96. // * walk the parse tree and execute it by dispatching to handlers. If Remove
  97. // or ForceRemove is set, additional cleanup around containers happens after
  98. // processing.
  99. // * Print a happy message and return the image ID.
  100. //
  101. func (b *Builder) Run(context io.Reader) (string, error) {
  102. if err := b.readContext(context); err != nil {
  103. return "", err
  104. }
  105. defer func() {
  106. if err := os.RemoveAll(b.contextPath); err != nil {
  107. log.Debugf("[BUILDER] failed to remove temporary context: %s", err)
  108. }
  109. }()
  110. filename := path.Join(b.contextPath, "Dockerfile")
  111. fi, err := os.Stat(filename)
  112. if os.IsNotExist(err) {
  113. return "", fmt.Errorf("Cannot build a directory without a Dockerfile")
  114. }
  115. if fi.Size() == 0 {
  116. return "", ErrDockerfileEmpty
  117. }
  118. f, err := os.Open(filename)
  119. if err != nil {
  120. return "", err
  121. }
  122. defer f.Close()
  123. ast, err := parser.Parse(f)
  124. if err != nil {
  125. return "", err
  126. }
  127. b.dockerfile = ast
  128. // some initializations that would not have been supplied by the caller.
  129. b.Config = &runconfig.Config{Entrypoint: []string{}, Cmd: []string{"/bin/sh", "-c"}}
  130. b.TmpContainers = map[string]struct{}{}
  131. for i, n := range b.dockerfile.Children {
  132. if err := b.dispatch(i, n); err != nil {
  133. if b.ForceRemove {
  134. b.clearTmp()
  135. }
  136. return "", err
  137. }
  138. fmt.Fprintf(b.OutStream, " ---> %s\n", utils.TruncateID(b.image))
  139. if b.Remove {
  140. b.clearTmp()
  141. }
  142. }
  143. if b.image == "" {
  144. return "", fmt.Errorf("No image was generated. Is your Dockerfile empty?\n")
  145. }
  146. fmt.Fprintf(b.OutStream, "Successfully built %s\n", utils.TruncateID(b.image))
  147. return b.image, nil
  148. }
  149. // This method is the entrypoint to all statement handling routines.
  150. //
  151. // Almost all nodes will have this structure:
  152. // Child[Node, Node, Node] where Child is from parser.Node.Children and each
  153. // node comes from parser.Node.Next. This forms a "line" with a statement and
  154. // arguments and we process them in this normalized form by hitting
  155. // evaluateTable with the leaf nodes of the command and the Builder object.
  156. //
  157. // ONBUILD is a special case; in this case the parser will emit:
  158. // Child[Node, Child[Node, Node...]] where the first node is the literal
  159. // "onbuild" and the child entrypoint is the command of the ONBUILD statmeent,
  160. // such as `RUN` in ONBUILD RUN foo. There is special case logic in here to
  161. // deal with that, at least until it becomes more of a general concern with new
  162. // features.
  163. func (b *Builder) dispatch(stepN int, ast *parser.Node) error {
  164. cmd := ast.Value
  165. attrs := ast.Attributes
  166. strs := []string{}
  167. msg := fmt.Sprintf("Step %d : %s", stepN, strings.ToUpper(cmd))
  168. if cmd == "onbuild" {
  169. ast = ast.Next.Children[0]
  170. strs = append(strs, b.replaceEnv(ast.Value))
  171. msg += " " + ast.Value
  172. }
  173. for ast.Next != nil {
  174. ast = ast.Next
  175. strs = append(strs, b.replaceEnv(ast.Value))
  176. msg += " " + ast.Value
  177. }
  178. fmt.Fprintln(b.OutStream, msg)
  179. // XXX yes, we skip any cmds that are not valid; the parser should have
  180. // picked these out already.
  181. if f, ok := evaluateTable[cmd]; ok {
  182. return f(b, strs, attrs)
  183. }
  184. fmt.Fprintf(b.ErrStream, "# Skipping unknown instruction %s\n", strings.ToUpper(cmd))
  185. return nil
  186. }