evaluator.go 10 KB

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