internals.go 20 KB

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