internals.go 19 KB

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