evaluator.go 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  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/fileutils"
  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. var (
  39. ErrDockerfileEmpty = errors.New("Dockerfile cannot be empty")
  40. )
  41. // Environment variable interpolation will happen on these statements only.
  42. var replaceEnvAllowed = map[string]struct{}{
  43. "env": {},
  44. "add": {},
  45. "copy": {},
  46. "workdir": {},
  47. "expose": {},
  48. "volume": {},
  49. "user": {},
  50. }
  51. var evaluateTable map[string]func(*Builder, []string, map[string]bool, string) error
  52. func init() {
  53. evaluateTable = map[string]func(*Builder, []string, map[string]bool, string) error{
  54. "env": env,
  55. "maintainer": maintainer,
  56. "add": add,
  57. "copy": dispatchCopy, // copy() is a go builtin
  58. "from": from,
  59. "onbuild": onbuild,
  60. "workdir": workdir,
  61. "run": run,
  62. "cmd": cmd,
  63. "entrypoint": entrypoint,
  64. "expose": expose,
  65. "volume": volume,
  66. "user": user,
  67. "insert": insert,
  68. }
  69. }
  70. // internal struct, used to maintain configuration of the Dockerfile's
  71. // processing as it evaluates the parsing result.
  72. type Builder struct {
  73. Daemon *daemon.Daemon
  74. Engine *engine.Engine
  75. // effectively stdio for the run. Because it is not stdio, I said
  76. // "Effectively". Do not use stdio anywhere in this package for any reason.
  77. OutStream io.Writer
  78. ErrStream io.Writer
  79. Verbose bool
  80. UtilizeCache bool
  81. // controls how images and containers are handled between steps.
  82. Remove bool
  83. ForceRemove bool
  84. Pull bool
  85. AuthConfig *registry.AuthConfig
  86. AuthConfigFile *registry.ConfigFile
  87. // Deprecated, original writer used for ImagePull. To be removed.
  88. OutOld io.Writer
  89. StreamFormatter *utils.StreamFormatter
  90. Config *runconfig.Config // runconfig for cmd, run, entrypoint etc.
  91. // both of these are controlled by the Remove and ForceRemove options in BuildOpts
  92. TmpContainers map[string]struct{} // a map of containers used for removes
  93. dockerfileName string // name of Dockerfile
  94. dockerfile *parser.Node // the syntax tree of the dockerfile
  95. image string // image name for commit processing
  96. maintainer string // maintainer name. could probably be removed.
  97. cmdSet bool // indicates is CMD was set in current Dockerfile
  98. context tarsum.TarSum // the context is a tarball that is uploaded by the client
  99. contextPath string // the path of the temporary directory the local context is unpacked to (server side)
  100. noBaseImage bool // indicates that this build does not start from any base image, but is being built from an empty file system.
  101. }
  102. // Run the builder with the context. This is the lynchpin of this package. This
  103. // will (barring errors):
  104. //
  105. // * call readContext() which will set up the temporary directory and unpack
  106. // the context into it.
  107. // * read the dockerfile
  108. // * parse the dockerfile
  109. // * walk the parse tree and execute it by dispatching to handlers. If Remove
  110. // or ForceRemove is set, additional cleanup around containers happens after
  111. // processing.
  112. // * Print a happy message and return the image ID.
  113. //
  114. func (b *Builder) Run(context io.Reader) (string, error) {
  115. if err := b.readContext(context); err != nil {
  116. return "", err
  117. }
  118. defer func() {
  119. if err := os.RemoveAll(b.contextPath); err != nil {
  120. log.Debugf("[BUILDER] failed to remove temporary context: %s", err)
  121. }
  122. }()
  123. if err := b.readDockerfile(b.dockerfileName); err != nil {
  124. return "", err
  125. }
  126. // some initializations that would not have been supplied by the caller.
  127. b.Config = &runconfig.Config{}
  128. b.TmpContainers = map[string]struct{}{}
  129. for i, n := range b.dockerfile.Children {
  130. if err := b.dispatch(i, n); err != nil {
  131. if b.ForceRemove {
  132. b.clearTmp()
  133. }
  134. return "", err
  135. }
  136. fmt.Fprintf(b.OutStream, " ---> %s\n", utils.TruncateID(b.image))
  137. if b.Remove {
  138. b.clearTmp()
  139. }
  140. }
  141. if b.image == "" {
  142. return "", fmt.Errorf("No image was generated. Is your Dockerfile empty?\n")
  143. }
  144. fmt.Fprintf(b.OutStream, "Successfully built %s\n", utils.TruncateID(b.image))
  145. return b.image, nil
  146. }
  147. // Reads a Dockerfile from the current context. It assumes that the
  148. // 'filename' is a relative path from the root of the context
  149. func (b *Builder) readDockerfile(filename string) error {
  150. filename = path.Join(b.contextPath, filename)
  151. fi, err := os.Stat(filename)
  152. if os.IsNotExist(err) {
  153. return fmt.Errorf("Cannot build a directory without a Dockerfile")
  154. }
  155. if fi.Size() == 0 {
  156. return ErrDockerfileEmpty
  157. }
  158. f, err := os.Open(filename)
  159. if err != nil {
  160. return err
  161. }
  162. b.dockerfile, err = parser.Parse(f)
  163. f.Close()
  164. if err != nil {
  165. return err
  166. }
  167. // After the Dockerfile has been parsed, we need to check the .dockerignore
  168. // file for either "Dockerfile" or ".dockerignore", and if either are
  169. // present then erase them from the build context. These files should never
  170. // have been sent from the client but we did send them to make sure that
  171. // we had the Dockerfile to actually parse, and then we also need the
  172. // .dockerignore file to know whether either file should be removed.
  173. // Note that this assumes the Dockerfile has been read into memory and
  174. // is now safe to be removed.
  175. excludes, _ := utils.ReadDockerIgnore(path.Join(b.contextPath, ".dockerignore"))
  176. if rm, _ := fileutils.Matches(".dockerignore", excludes); rm == true {
  177. os.Remove(path.Join(b.contextPath, ".dockerignore"))
  178. b.context.(tarsum.BuilderContext).Remove(".dockerignore")
  179. }
  180. if rm, _ := fileutils.Matches(b.dockerfileName, excludes); rm == true {
  181. os.Remove(path.Join(b.contextPath, b.dockerfileName))
  182. b.context.(tarsum.BuilderContext).Remove(b.dockerfileName)
  183. }
  184. return nil
  185. }
  186. // This method is the entrypoint to all statement handling routines.
  187. //
  188. // Almost all nodes will have this structure:
  189. // Child[Node, Node, Node] where Child is from parser.Node.Children and each
  190. // node comes from parser.Node.Next. This forms a "line" with a statement and
  191. // arguments and we process them in this normalized form by hitting
  192. // evaluateTable with the leaf nodes of the command and the Builder object.
  193. //
  194. // ONBUILD is a special case; in this case the parser will emit:
  195. // Child[Node, Child[Node, Node...]] where the first node is the literal
  196. // "onbuild" and the child entrypoint is the command of the ONBUILD statmeent,
  197. // such as `RUN` in ONBUILD RUN foo. There is special case logic in here to
  198. // deal with that, at least until it becomes more of a general concern with new
  199. // features.
  200. func (b *Builder) dispatch(stepN int, ast *parser.Node) error {
  201. cmd := ast.Value
  202. attrs := ast.Attributes
  203. original := ast.Original
  204. strs := []string{}
  205. msg := fmt.Sprintf("Step %d : %s", stepN, strings.ToUpper(cmd))
  206. if cmd == "onbuild" {
  207. ast = ast.Next.Children[0]
  208. strs = append(strs, ast.Value)
  209. msg += " " + ast.Value
  210. }
  211. // count the number of nodes that we are going to traverse first
  212. // so we can pre-create the argument and message array. This speeds up the
  213. // allocation of those list a lot when they have a lot of arguments
  214. cursor := ast
  215. var n int
  216. for cursor.Next != nil {
  217. cursor = cursor.Next
  218. n++
  219. }
  220. l := len(strs)
  221. strList := make([]string, n+l)
  222. copy(strList, strs)
  223. msgList := make([]string, n)
  224. var i int
  225. for ast.Next != nil {
  226. ast = ast.Next
  227. var str string
  228. str = ast.Value
  229. if _, ok := replaceEnvAllowed[cmd]; ok {
  230. str = b.replaceEnv(ast.Value)
  231. }
  232. strList[i+l] = str
  233. msgList[i] = ast.Value
  234. i++
  235. }
  236. msg += " " + strings.Join(msgList, " ")
  237. fmt.Fprintln(b.OutStream, msg)
  238. // XXX yes, we skip any cmds that are not valid; the parser should have
  239. // picked these out already.
  240. if f, ok := evaluateTable[cmd]; ok {
  241. return f(b, strList, attrs, original)
  242. }
  243. fmt.Fprintf(b.ErrStream, "# Skipping unknown instruction %s\n", strings.ToUpper(cmd))
  244. return nil
  245. }