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