evaluator.go 11 KB

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