internals.go 19 KB

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