internals.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720
  1. package dockerfile
  2. // internals for handling commands. Covers many areas and a lot of
  3. // non-contiguous functionality. Please read the comments.
  4. import (
  5. "crypto/sha256"
  6. "encoding/hex"
  7. "errors"
  8. "fmt"
  9. "io"
  10. "io/ioutil"
  11. "net/http"
  12. "net/url"
  13. "os"
  14. "path/filepath"
  15. "runtime"
  16. "sort"
  17. "strings"
  18. "sync"
  19. "time"
  20. "github.com/Sirupsen/logrus"
  21. "github.com/docker/docker/api/types/backend"
  22. "github.com/docker/docker/builder"
  23. "github.com/docker/docker/builder/dockerfile/parser"
  24. "github.com/docker/docker/pkg/archive"
  25. "github.com/docker/docker/pkg/httputils"
  26. "github.com/docker/docker/pkg/ioutils"
  27. "github.com/docker/docker/pkg/jsonmessage"
  28. "github.com/docker/docker/pkg/progress"
  29. "github.com/docker/docker/pkg/streamformatter"
  30. "github.com/docker/docker/pkg/stringid"
  31. "github.com/docker/docker/pkg/system"
  32. "github.com/docker/docker/pkg/tarsum"
  33. "github.com/docker/docker/pkg/urlutil"
  34. "github.com/docker/docker/runconfig/opts"
  35. "github.com/docker/engine-api/types"
  36. "github.com/docker/engine-api/types/container"
  37. "github.com/docker/engine-api/types/strslice"
  38. )
  39. func (b *Builder) commit(id string, autoCmd strslice.StrSlice, comment string) error {
  40. if b.disableCommit {
  41. return nil
  42. }
  43. if b.image == "" && !b.noBaseImage {
  44. return fmt.Errorf("Please provide a source image with `from` prior to commit")
  45. }
  46. b.runConfig.Image = b.image
  47. if id == "" {
  48. cmd := b.runConfig.Cmd
  49. if runtime.GOOS != "windows" {
  50. b.runConfig.Cmd = strslice.StrSlice{"/bin/sh", "-c", "#(nop) " + comment}
  51. } else {
  52. b.runConfig.Cmd = strslice.StrSlice{"cmd", "/S /C", "REM (nop) " + comment}
  53. }
  54. defer func(cmd strslice.StrSlice) { b.runConfig.Cmd = cmd }(cmd)
  55. hit, err := b.probeCache()
  56. if err != nil {
  57. return err
  58. } else if hit {
  59. return nil
  60. }
  61. id, err = b.create()
  62. if err != nil {
  63. return err
  64. }
  65. }
  66. // Note: Actually copy the struct
  67. autoConfig := *b.runConfig
  68. autoConfig.Cmd = autoCmd
  69. commitCfg := &backend.ContainerCommitConfig{
  70. ContainerCommitConfig: types.ContainerCommitConfig{
  71. Author: b.maintainer,
  72. Pause: true,
  73. Config: &autoConfig,
  74. },
  75. }
  76. // Commit the container
  77. imageID, err := b.docker.Commit(id, commitCfg)
  78. if err != nil {
  79. return err
  80. }
  81. b.image = imageID
  82. return nil
  83. }
  84. type copyInfo struct {
  85. builder.FileInfo
  86. decompress bool
  87. }
  88. func (b *Builder) runContextCommand(args []string, allowRemote bool, allowLocalDecompression bool, cmdName string) error {
  89. if b.context == nil {
  90. return fmt.Errorf("No context given. Impossible to use %s", cmdName)
  91. }
  92. if len(args) < 2 {
  93. return fmt.Errorf("Invalid %s format - at least two arguments required", cmdName)
  94. }
  95. // Work in daemon-specific filepath semantics
  96. dest := filepath.FromSlash(args[len(args)-1]) // last one is always the dest
  97. b.runConfig.Image = b.image
  98. var infos []copyInfo
  99. // Loop through each src file and calculate the info we need to
  100. // do the copy (e.g. hash value if cached). Don't actually do
  101. // the copy until we've looked at all src files
  102. var err error
  103. for _, orig := range args[0 : len(args)-1] {
  104. var fi builder.FileInfo
  105. decompress := allowLocalDecompression
  106. if urlutil.IsURL(orig) {
  107. if !allowRemote {
  108. return fmt.Errorf("Source can't be a URL for %s", cmdName)
  109. }
  110. fi, err = b.download(orig)
  111. if err != nil {
  112. return err
  113. }
  114. defer os.RemoveAll(filepath.Dir(fi.Path()))
  115. decompress = false
  116. infos = append(infos, copyInfo{fi, decompress})
  117. continue
  118. }
  119. // not a URL
  120. subInfos, err := b.calcCopyInfo(cmdName, orig, allowLocalDecompression, true)
  121. if err != nil {
  122. return err
  123. }
  124. infos = append(infos, subInfos...)
  125. }
  126. if len(infos) == 0 {
  127. return fmt.Errorf("No source files were specified")
  128. }
  129. if len(infos) > 1 && !strings.HasSuffix(dest, string(os.PathSeparator)) {
  130. return fmt.Errorf("When using %s with more than one source file, the destination must be a directory and end with a /", cmdName)
  131. }
  132. // For backwards compat, if there's just one info then use it as the
  133. // cache look-up string, otherwise hash 'em all into one
  134. var srcHash string
  135. var origPaths string
  136. if len(infos) == 1 {
  137. fi := infos[0].FileInfo
  138. origPaths = fi.Name()
  139. if hfi, ok := fi.(builder.Hashed); ok {
  140. srcHash = hfi.Hash()
  141. }
  142. } else {
  143. var hashs []string
  144. var origs []string
  145. for _, info := range infos {
  146. fi := info.FileInfo
  147. origs = append(origs, fi.Name())
  148. if hfi, ok := fi.(builder.Hashed); ok {
  149. hashs = append(hashs, hfi.Hash())
  150. }
  151. }
  152. hasher := sha256.New()
  153. hasher.Write([]byte(strings.Join(hashs, ",")))
  154. srcHash = "multi:" + hex.EncodeToString(hasher.Sum(nil))
  155. origPaths = strings.Join(origs, " ")
  156. }
  157. cmd := b.runConfig.Cmd
  158. if runtime.GOOS != "windows" {
  159. b.runConfig.Cmd = strslice.StrSlice{"/bin/sh", "-c", fmt.Sprintf("#(nop) %s %s in %s", cmdName, srcHash, dest)}
  160. } else {
  161. b.runConfig.Cmd = strslice.StrSlice{"cmd", "/S", "/C", fmt.Sprintf("REM (nop) %s %s in %s", cmdName, srcHash, dest)}
  162. }
  163. defer func(cmd strslice.StrSlice) { b.runConfig.Cmd = cmd }(cmd)
  164. if hit, err := b.probeCache(); err != nil {
  165. return err
  166. } else if hit {
  167. return nil
  168. }
  169. container, err := b.docker.ContainerCreate(types.ContainerCreateConfig{Config: b.runConfig})
  170. if err != nil {
  171. return err
  172. }
  173. b.tmpContainers[container.ID] = struct{}{}
  174. comment := fmt.Sprintf("%s %s in %s", cmdName, origPaths, dest)
  175. // Twiddle the destination when its a relative path - meaning, make it
  176. // relative to the WORKINGDIR
  177. endsInSlash := strings.HasSuffix(dest, string(os.PathSeparator))
  178. if runtime.GOOS == "windows" {
  179. // On Windows, this is more complicated. We are guaranteed that the
  180. // WorkingDir is already platform consistent meaning in the format
  181. // UPPERCASEDriveLetter-Colon-Backslash-Foldername. However, Windows
  182. // for now also has the limitation that ADD/COPY can only be done to
  183. // the C: (system) drive, not any drives that might be present as a
  184. // result of bind mounts.
  185. //
  186. // So... if the path specified is Linux-style absolute (/foo or \\foo),
  187. // we assume it is the system drive. If it is a Windows-style absolute
  188. // (DRIVE:\\foo), error if DRIVE is not C. And finally, ensure we
  189. // strip any configured working directories drive letter so that it
  190. // can be subsequently legitimately converted to a Windows volume-style
  191. // pathname.
  192. // Not a typo - filepath.IsAbs, not system.IsAbs on this next check as
  193. // we only want to validate where the DriveColon part has been supplied.
  194. if filepath.IsAbs(dest) {
  195. if strings.ToUpper(string(dest[0])) != "C" {
  196. return fmt.Errorf("Windows does not support %s with a destinations not on the system drive (C:)", cmdName)
  197. }
  198. dest = dest[2:] // Strip the drive letter
  199. }
  200. // Cannot handle relative where WorkingDir is not the system drive.
  201. if len(b.runConfig.WorkingDir) > 0 {
  202. if !system.IsAbs(b.runConfig.WorkingDir[2:]) {
  203. return fmt.Errorf("Current WorkingDir %s is not platform consistent", b.runConfig.WorkingDir)
  204. }
  205. if !system.IsAbs(dest) {
  206. if string(b.runConfig.WorkingDir[0]) != "C" {
  207. return fmt.Errorf("Windows does not support %s with relative paths when WORKDIR is not the system drive", cmdName)
  208. }
  209. dest = filepath.Join(string(os.PathSeparator), b.runConfig.WorkingDir[2:], dest)
  210. // Make sure we preserve any trailing slash
  211. if endsInSlash {
  212. dest += string(os.PathSeparator)
  213. }
  214. }
  215. }
  216. } else {
  217. if !system.IsAbs(dest) {
  218. dest = filepath.Join(string(os.PathSeparator), filepath.FromSlash(b.runConfig.WorkingDir), dest)
  219. // Make sure we preserve any trailing slash
  220. if endsInSlash {
  221. dest += string(os.PathSeparator)
  222. }
  223. }
  224. }
  225. for _, info := range infos {
  226. if err := b.docker.CopyOnBuild(container.ID, dest, info.FileInfo, info.decompress); err != nil {
  227. return err
  228. }
  229. }
  230. return b.commit(container.ID, cmd, comment)
  231. }
  232. func (b *Builder) download(srcURL string) (fi builder.FileInfo, err error) {
  233. // get filename from URL
  234. u, err := url.Parse(srcURL)
  235. if err != nil {
  236. return
  237. }
  238. path := filepath.FromSlash(u.Path) // Ensure in platform semantics
  239. if strings.HasSuffix(path, string(os.PathSeparator)) {
  240. path = path[:len(path)-1]
  241. }
  242. parts := strings.Split(path, string(os.PathSeparator))
  243. filename := parts[len(parts)-1]
  244. if filename == "" {
  245. err = fmt.Errorf("cannot determine filename from url: %s", u)
  246. return
  247. }
  248. // Initiate the download
  249. resp, err := httputils.Download(srcURL)
  250. if err != nil {
  251. return
  252. }
  253. // Prepare file in a tmp dir
  254. tmpDir, err := ioutils.TempDir("", "docker-remote")
  255. if err != nil {
  256. return
  257. }
  258. defer func() {
  259. if err != nil {
  260. os.RemoveAll(tmpDir)
  261. }
  262. }()
  263. tmpFileName := filepath.Join(tmpDir, filename)
  264. tmpFile, err := os.OpenFile(tmpFileName, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0600)
  265. if err != nil {
  266. return
  267. }
  268. stdoutFormatter := b.Stdout.(*streamformatter.StdoutFormatter)
  269. progressOutput := stdoutFormatter.StreamFormatter.NewProgressOutput(stdoutFormatter.Writer, true)
  270. progressReader := progress.NewProgressReader(resp.Body, progressOutput, resp.ContentLength, "", "Downloading")
  271. // Download and dump result to tmp file
  272. if _, err = io.Copy(tmpFile, progressReader); err != nil {
  273. tmpFile.Close()
  274. return
  275. }
  276. fmt.Fprintln(b.Stdout)
  277. // ignoring error because the file was already opened successfully
  278. tmpFileSt, err := tmpFile.Stat()
  279. if err != nil {
  280. return
  281. }
  282. tmpFile.Close()
  283. // Set the mtime to the Last-Modified header value if present
  284. // Otherwise just remove atime and mtime
  285. mTime := time.Time{}
  286. lastMod := resp.Header.Get("Last-Modified")
  287. if lastMod != "" {
  288. // If we can't parse it then just let it default to 'zero'
  289. // otherwise use the parsed time value
  290. if parsedMTime, err := http.ParseTime(lastMod); err == nil {
  291. mTime = parsedMTime
  292. }
  293. }
  294. if err = system.Chtimes(tmpFileName, mTime, mTime); err != nil {
  295. return
  296. }
  297. // Calc the checksum, even if we're using the cache
  298. r, err := archive.Tar(tmpFileName, archive.Uncompressed)
  299. if err != nil {
  300. return
  301. }
  302. tarSum, err := tarsum.NewTarSum(r, true, tarsum.Version1)
  303. if err != nil {
  304. return
  305. }
  306. if _, err = io.Copy(ioutil.Discard, tarSum); err != nil {
  307. return
  308. }
  309. hash := tarSum.Sum(nil)
  310. r.Close()
  311. return &builder.HashedFileInfo{FileInfo: builder.PathFileInfo{FileInfo: tmpFileSt, FilePath: tmpFileName}, FileHash: hash}, nil
  312. }
  313. func (b *Builder) calcCopyInfo(cmdName, origPath string, allowLocalDecompression, allowWildcards bool) ([]copyInfo, error) {
  314. // Work in daemon-specific OS filepath semantics
  315. origPath = filepath.FromSlash(origPath)
  316. if origPath != "" && origPath[0] == os.PathSeparator && len(origPath) > 1 {
  317. origPath = origPath[1:]
  318. }
  319. origPath = strings.TrimPrefix(origPath, "."+string(os.PathSeparator))
  320. // Deal with wildcards
  321. if allowWildcards && containsWildcards(origPath) {
  322. var copyInfos []copyInfo
  323. if err := b.context.Walk("", func(path string, info builder.FileInfo, err error) error {
  324. if err != nil {
  325. return err
  326. }
  327. if info.Name() == "" {
  328. // Why are we doing this check?
  329. return nil
  330. }
  331. if match, _ := filepath.Match(origPath, path); !match {
  332. return nil
  333. }
  334. // Note we set allowWildcards to false in case the name has
  335. // a * in it
  336. subInfos, err := b.calcCopyInfo(cmdName, path, allowLocalDecompression, false)
  337. if err != nil {
  338. return err
  339. }
  340. copyInfos = append(copyInfos, subInfos...)
  341. return nil
  342. }); err != nil {
  343. return nil, err
  344. }
  345. return copyInfos, nil
  346. }
  347. // Must be a dir or a file
  348. statPath, fi, err := b.context.Stat(origPath)
  349. if err != nil {
  350. return nil, err
  351. }
  352. copyInfos := []copyInfo{{FileInfo: fi, decompress: allowLocalDecompression}}
  353. hfi, handleHash := fi.(builder.Hashed)
  354. if !handleHash {
  355. return copyInfos, nil
  356. }
  357. // Deal with the single file case
  358. if !fi.IsDir() {
  359. hfi.SetHash("file:" + hfi.Hash())
  360. return copyInfos, nil
  361. }
  362. // Must be a dir
  363. var subfiles []string
  364. err = b.context.Walk(statPath, func(path string, info builder.FileInfo, err error) error {
  365. if err != nil {
  366. return err
  367. }
  368. // we already checked handleHash above
  369. subfiles = append(subfiles, info.(builder.Hashed).Hash())
  370. return nil
  371. })
  372. if err != nil {
  373. return nil, err
  374. }
  375. sort.Strings(subfiles)
  376. hasher := sha256.New()
  377. hasher.Write([]byte(strings.Join(subfiles, ",")))
  378. hfi.SetHash("dir:" + hex.EncodeToString(hasher.Sum(nil)))
  379. return copyInfos, nil
  380. }
  381. func containsWildcards(name string) bool {
  382. for i := 0; i < len(name); i++ {
  383. ch := name[i]
  384. if ch == '\\' {
  385. i++
  386. } else if ch == '*' || ch == '?' || ch == '[' {
  387. return true
  388. }
  389. }
  390. return false
  391. }
  392. func (b *Builder) processImageFrom(img builder.Image) error {
  393. if img != nil {
  394. b.image = img.ImageID()
  395. if img.RunConfig() != nil {
  396. b.runConfig = img.RunConfig()
  397. }
  398. }
  399. // Check to see if we have a default PATH, note that windows won't
  400. // have one as its set by HCS
  401. if system.DefaultPathEnv != "" {
  402. // Convert the slice of strings that represent the current list
  403. // of env vars into a map so we can see if PATH is already set.
  404. // If its not set then go ahead and give it our default value
  405. configEnv := opts.ConvertKVStringsToMap(b.runConfig.Env)
  406. if _, ok := configEnv["PATH"]; !ok {
  407. b.runConfig.Env = append(b.runConfig.Env,
  408. "PATH="+system.DefaultPathEnv)
  409. }
  410. }
  411. if img == nil {
  412. // Typically this means they used "FROM scratch"
  413. return nil
  414. }
  415. // Process ONBUILD triggers if they exist
  416. if nTriggers := len(b.runConfig.OnBuild); nTriggers != 0 {
  417. word := "trigger"
  418. if nTriggers > 1 {
  419. word = "triggers"
  420. }
  421. fmt.Fprintf(b.Stderr, "# Executing %d build %s...\n", nTriggers, word)
  422. }
  423. // Copy the ONBUILD triggers, and remove them from the config, since the config will be committed.
  424. onBuildTriggers := b.runConfig.OnBuild
  425. b.runConfig.OnBuild = []string{}
  426. // parse the ONBUILD triggers by invoking the parser
  427. for _, step := range onBuildTriggers {
  428. ast, err := parser.Parse(strings.NewReader(step))
  429. if err != nil {
  430. return err
  431. }
  432. for i, n := range ast.Children {
  433. switch strings.ToUpper(n.Value) {
  434. case "ONBUILD":
  435. return fmt.Errorf("Chaining ONBUILD via `ONBUILD ONBUILD` isn't allowed")
  436. case "MAINTAINER", "FROM":
  437. return fmt.Errorf("%s isn't allowed as an ONBUILD trigger", n.Value)
  438. }
  439. if err := b.dispatch(i, n); err != nil {
  440. return err
  441. }
  442. }
  443. }
  444. return nil
  445. }
  446. // probeCache checks if `b.docker` implements builder.ImageCache and image-caching
  447. // is enabled (`b.UseCache`).
  448. // If so attempts to look up the current `b.image` and `b.runConfig` pair with `b.docker`.
  449. // If an image is found, probeCache returns `(true, nil)`.
  450. // If no image is found, it returns `(false, nil)`.
  451. // If there is any error, it returns `(false, err)`.
  452. func (b *Builder) probeCache() (bool, error) {
  453. c, ok := b.docker.(builder.ImageCache)
  454. if !ok || b.options.NoCache || b.cacheBusted {
  455. return false, nil
  456. }
  457. cache, err := c.GetCachedImageOnBuild(b.image, b.runConfig)
  458. if err != nil {
  459. return false, err
  460. }
  461. if len(cache) == 0 {
  462. logrus.Debugf("[BUILDER] Cache miss: %s", b.runConfig.Cmd)
  463. b.cacheBusted = true
  464. return false, nil
  465. }
  466. fmt.Fprintf(b.Stdout, " ---> Using cache\n")
  467. logrus.Debugf("[BUILDER] Use cached version: %s", b.runConfig.Cmd)
  468. b.image = string(cache)
  469. return true, nil
  470. }
  471. func (b *Builder) create() (string, error) {
  472. if b.image == "" && !b.noBaseImage {
  473. return "", fmt.Errorf("Please provide a source image with `from` prior to run")
  474. }
  475. b.runConfig.Image = b.image
  476. resources := container.Resources{
  477. CgroupParent: b.options.CgroupParent,
  478. CPUShares: b.options.CPUShares,
  479. CPUPeriod: b.options.CPUPeriod,
  480. CPUQuota: b.options.CPUQuota,
  481. CpusetCpus: b.options.CPUSetCPUs,
  482. CpusetMems: b.options.CPUSetMems,
  483. Memory: b.options.Memory,
  484. MemorySwap: b.options.MemorySwap,
  485. Ulimits: b.options.Ulimits,
  486. }
  487. // TODO: why not embed a hostconfig in builder?
  488. hostConfig := &container.HostConfig{
  489. Isolation: b.options.Isolation,
  490. ShmSize: b.options.ShmSize,
  491. Resources: resources,
  492. }
  493. config := *b.runConfig
  494. // Create the container
  495. c, err := b.docker.ContainerCreate(types.ContainerCreateConfig{
  496. Config: b.runConfig,
  497. HostConfig: hostConfig,
  498. })
  499. if err != nil {
  500. return "", err
  501. }
  502. for _, warning := range c.Warnings {
  503. fmt.Fprintf(b.Stdout, " ---> [Warning] %s\n", warning)
  504. }
  505. b.tmpContainers[c.ID] = struct{}{}
  506. fmt.Fprintf(b.Stdout, " ---> Running in %s\n", stringid.TruncateID(c.ID))
  507. // override the entry point that may have been picked up from the base image
  508. if err := b.docker.ContainerUpdateCmdOnBuild(c.ID, config.Cmd); err != nil {
  509. return "", err
  510. }
  511. return c.ID, nil
  512. }
  513. var errCancelled = errors.New("build cancelled")
  514. func (b *Builder) run(cID string) (err error) {
  515. errCh := make(chan error)
  516. go func() {
  517. errCh <- b.docker.ContainerAttachRaw(cID, nil, b.Stdout, b.Stderr, true)
  518. }()
  519. finished := make(chan struct{})
  520. var once sync.Once
  521. finish := func() { close(finished) }
  522. cancelErrCh := make(chan error, 1)
  523. defer once.Do(finish)
  524. go func() {
  525. select {
  526. case <-b.clientCtx.Done():
  527. logrus.Debugln("Build cancelled, killing and removing container:", cID)
  528. b.docker.ContainerKill(cID, 0)
  529. b.removeContainer(cID)
  530. cancelErrCh <- errCancelled
  531. case <-finished:
  532. cancelErrCh <- nil
  533. }
  534. }()
  535. if err := b.docker.ContainerStart(cID, nil); err != nil {
  536. return err
  537. }
  538. // Block on reading output from container, stop on err or chan closed
  539. if err := <-errCh; err != nil {
  540. return err
  541. }
  542. if ret, _ := b.docker.ContainerWait(cID, -1); ret != 0 {
  543. // TODO: change error type, because jsonmessage.JSONError assumes HTTP
  544. return &jsonmessage.JSONError{
  545. Message: fmt.Sprintf("The command '%s' returned a non-zero code: %d", strings.Join(b.runConfig.Cmd, " "), ret),
  546. Code: ret,
  547. }
  548. }
  549. once.Do(finish)
  550. return <-cancelErrCh
  551. }
  552. func (b *Builder) removeContainer(c string) error {
  553. rmConfig := &types.ContainerRmConfig{
  554. ForceRemove: true,
  555. RemoveVolume: true,
  556. }
  557. if err := b.docker.ContainerRm(c, rmConfig); err != nil {
  558. fmt.Fprintf(b.Stdout, "Error removing intermediate container %s: %v\n", stringid.TruncateID(c), err)
  559. return err
  560. }
  561. return nil
  562. }
  563. func (b *Builder) clearTmp() {
  564. for c := range b.tmpContainers {
  565. if err := b.removeContainer(c); err != nil {
  566. return
  567. }
  568. delete(b.tmpContainers, c)
  569. fmt.Fprintf(b.Stdout, "Removing intermediate container %s\n", stringid.TruncateID(c))
  570. }
  571. }
  572. // readDockerfile reads a Dockerfile from the current context.
  573. func (b *Builder) readDockerfile() error {
  574. // If no -f was specified then look for 'Dockerfile'. If we can't find
  575. // that then look for 'dockerfile'. If neither are found then default
  576. // back to 'Dockerfile' and use that in the error message.
  577. if b.options.Dockerfile == "" {
  578. b.options.Dockerfile = builder.DefaultDockerfileName
  579. if _, _, err := b.context.Stat(b.options.Dockerfile); os.IsNotExist(err) {
  580. lowercase := strings.ToLower(b.options.Dockerfile)
  581. if _, _, err := b.context.Stat(lowercase); err == nil {
  582. b.options.Dockerfile = lowercase
  583. }
  584. }
  585. }
  586. f, err := b.context.Open(b.options.Dockerfile)
  587. if err != nil {
  588. if os.IsNotExist(err) {
  589. return fmt.Errorf("Cannot locate specified Dockerfile: %s", b.options.Dockerfile)
  590. }
  591. return err
  592. }
  593. if f, ok := f.(*os.File); ok {
  594. // ignoring error because Open already succeeded
  595. fi, err := f.Stat()
  596. if err != nil {
  597. return fmt.Errorf("Unexpected error reading Dockerfile: %v", err)
  598. }
  599. if fi.Size() == 0 {
  600. return fmt.Errorf("The Dockerfile (%s) cannot be empty", b.options.Dockerfile)
  601. }
  602. }
  603. b.dockerfile, err = parser.Parse(f)
  604. f.Close()
  605. if err != nil {
  606. return err
  607. }
  608. // After the Dockerfile has been parsed, we need to check the .dockerignore
  609. // file for either "Dockerfile" or ".dockerignore", and if either are
  610. // present then erase them from the build context. These files should never
  611. // have been sent from the client but we did send them to make sure that
  612. // we had the Dockerfile to actually parse, and then we also need the
  613. // .dockerignore file to know whether either file should be removed.
  614. // Note that this assumes the Dockerfile has been read into memory and
  615. // is now safe to be removed.
  616. if dockerIgnore, ok := b.context.(builder.DockerIgnoreContext); ok {
  617. dockerIgnore.Process([]string{b.options.Dockerfile})
  618. }
  619. return nil
  620. }
  621. // determine if build arg is part of built-in args or user
  622. // defined args in Dockerfile at any point in time.
  623. func (b *Builder) isBuildArgAllowed(arg string) bool {
  624. if _, ok := BuiltinAllowedBuildArgs[arg]; ok {
  625. return true
  626. }
  627. if _, ok := b.allowedBuildArgs[arg]; ok {
  628. return true
  629. }
  630. return false
  631. }