evaluator.go 6.8 KB

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