evaluator.go 11 KB

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