internals.go 21 KB

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