evaluator.go 9.4 KB

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