internals.go 19 KB

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