evaluator.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  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 EnvMap map[string]string
  39. type UniqueMap map[string]struct{}
  40. var (
  41. ErrDockerfileEmpty = errors.New("Dockerfile cannot be empty")
  42. )
  43. var evaluateTable map[string]func(*BuildFile, []string) error
  44. func init() {
  45. evaluateTable = map[string]func(*BuildFile, []string) error{
  46. "env": env,
  47. "maintainer": maintainer,
  48. "add": add,
  49. "copy": dispatchCopy, // copy() is a go builtin
  50. "from": from,
  51. "onbuild": onbuild,
  52. "workdir": workdir,
  53. "docker-version": nullDispatch, // we don't care about docker-version
  54. "run": run,
  55. "cmd": cmd,
  56. "entrypoint": entrypoint,
  57. "expose": expose,
  58. "volume": volume,
  59. "user": user,
  60. "insert": insert,
  61. }
  62. }
  63. // internal struct, used to maintain configuration of the Dockerfile's
  64. // processing as it evaluates the parsing result.
  65. type BuildFile struct {
  66. Dockerfile *parser.Node // the syntax tree of the dockerfile
  67. Env EnvMap // map of environment variables
  68. Config *runconfig.Config // runconfig for cmd, run, entrypoint etc.
  69. Options *BuildOpts // see below
  70. // both of these are controlled by the Remove and ForceRemove options in BuildOpts
  71. TmpContainers UniqueMap // a map of containers used for removes
  72. TmpImages UniqueMap // a map of images used for removes
  73. image string // image name for commit processing
  74. maintainer string // maintainer name. could probably be removed.
  75. cmdSet bool // indicates is CMD was set in current Dockerfile
  76. context *tarsum.TarSum // the context is a tarball that is uploaded by the client
  77. contextPath string // the path of the temporary directory the local context is unpacked to (server side)
  78. }
  79. type BuildOpts struct {
  80. Daemon *daemon.Daemon
  81. Engine *engine.Engine
  82. // effectively stdio for the run. Because it is not stdio, I said
  83. // "Effectively". Do not use stdio anywhere in this package for any reason.
  84. OutStream io.Writer
  85. ErrStream io.Writer
  86. Verbose bool
  87. UtilizeCache bool
  88. // controls how images and containers are handled between steps.
  89. Remove bool
  90. ForceRemove bool
  91. AuthConfig *registry.AuthConfig
  92. AuthConfigFile *registry.ConfigFile
  93. // Deprecated, original writer used for ImagePull. To be removed.
  94. OutOld io.Writer
  95. StreamFormatter *utils.StreamFormatter
  96. }
  97. // Run the builder with the context. This is the lynchpin of this package. This
  98. // will (barring errors):
  99. //
  100. // * call readContext() which will set up the temporary directory and unpack
  101. // the context into it.
  102. // * read the dockerfile
  103. // * parse the dockerfile
  104. // * walk the parse tree and execute it by dispatching to handlers. If Remove
  105. // or ForceRemove is set, additional cleanup around containers happens after
  106. // processing.
  107. // * Print a happy message and return the image ID.
  108. //
  109. func (b *BuildFile) Run(context io.Reader) (string, error) {
  110. if err := b.readContext(context); err != nil {
  111. return "", err
  112. }
  113. filename := path.Join(b.contextPath, "Dockerfile")
  114. if _, err := os.Stat(filename); os.IsNotExist(err) {
  115. return "", fmt.Errorf("Cannot build a directory without a Dockerfile")
  116. }
  117. fileBytes, err := ioutil.ReadFile(filename)
  118. if err != nil {
  119. return "", err
  120. }
  121. if len(fileBytes) == 0 {
  122. return "", ErrDockerfileEmpty
  123. }
  124. ast, err := parser.Parse(bytes.NewReader(fileBytes))
  125. if err != nil {
  126. return "", err
  127. }
  128. b.Dockerfile = ast
  129. for i, n := range b.Dockerfile.Children {
  130. if err := b.dispatch(i, n); err != nil {
  131. if b.Options.ForceRemove {
  132. b.clearTmp(b.TmpContainers)
  133. }
  134. return "", err
  135. } else 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. strs := []string{}
  162. if cmd == "onbuild" {
  163. fmt.Fprintf(b.Options.OutStream, "%#v\n", ast.Next.Children[0].Value)
  164. ast = ast.Next.Children[0]
  165. strs = append(strs, ast.Value)
  166. }
  167. for ast.Next != nil {
  168. ast = ast.Next
  169. strs = append(strs, replaceEnv(b, ast.Value))
  170. }
  171. fmt.Fprintf(b.Options.OutStream, "Step %d : %s %s\n", stepN, strings.ToUpper(cmd), strings.Join(strs, " "))
  172. // XXX yes, we skip any cmds that are not valid; the parser should have
  173. // picked these out already.
  174. if f, ok := evaluateTable[cmd]; ok {
  175. return f(b, strs)
  176. }
  177. return nil
  178. }