internals.go 19 KB

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