evaluator.go 7.1 KB

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