internals.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703
  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. stdoutFormatter := b.Stdout.(*streamformatter.StdoutFormatter)
  255. progressOutput := stdoutFormatter.StreamFormatter.NewProgressOutput(stdoutFormatter.Writer, true)
  256. progressReader := progress.NewProgressReader(resp.Body, progressOutput, resp.ContentLength, "", "Downloading")
  257. // Download and dump result to tmp file
  258. // TODO: add filehash directly
  259. if _, err = io.Copy(tmpFile, progressReader); err != nil {
  260. tmpFile.Close()
  261. return
  262. }
  263. fmt.Fprintln(b.Stdout)
  264. // Set the mtime to the Last-Modified header value if present
  265. // Otherwise just remove atime and mtime
  266. mTime := time.Time{}
  267. lastMod := resp.Header.Get("Last-Modified")
  268. if lastMod != "" {
  269. // If we can't parse it then just let it default to 'zero'
  270. // otherwise use the parsed time value
  271. if parsedMTime, err := http.ParseTime(lastMod); err == nil {
  272. mTime = parsedMTime
  273. }
  274. }
  275. tmpFile.Close()
  276. if err = system.Chtimes(tmpFileName, mTime, mTime); err != nil {
  277. return
  278. }
  279. lc, err := remotecontext.NewLazyContext(tmpDir)
  280. if err != nil {
  281. return
  282. }
  283. return lc, filename, nil
  284. }
  285. var windowsBlacklist = map[string]bool{
  286. "c:\\": true,
  287. "c:\\windows": true,
  288. }
  289. func (b *Builder) calcCopyInfo(cmdName, origPath string, allowLocalDecompression, allowWildcards bool, imageSource *imageMount) ([]copyInfo, error) {
  290. // Work in daemon-specific OS filepath semantics
  291. origPath = filepath.FromSlash(origPath)
  292. // validate windows paths from other images
  293. if imageSource != nil && runtime.GOOS == "windows" {
  294. p := strings.ToLower(filepath.Clean(origPath))
  295. if !filepath.IsAbs(p) {
  296. if filepath.VolumeName(p) != "" {
  297. if p[len(p)-2:] == ":." { // case where clean returns weird c:. paths
  298. p = p[:len(p)-1]
  299. }
  300. p += "\\"
  301. } else {
  302. p = filepath.Join("c:\\", p)
  303. }
  304. }
  305. if _, blacklisted := windowsBlacklist[p]; blacklisted {
  306. return nil, errors.New("copy from c:\\ or c:\\windows is not allowed on windows")
  307. }
  308. }
  309. if origPath != "" && origPath[0] == os.PathSeparator && len(origPath) > 1 {
  310. origPath = origPath[1:]
  311. }
  312. origPath = strings.TrimPrefix(origPath, "."+string(os.PathSeparator))
  313. source := b.source
  314. var err error
  315. if imageSource != nil {
  316. source, err = imageSource.context()
  317. if err != nil {
  318. return nil, err
  319. }
  320. }
  321. if source == nil {
  322. return nil, errors.Errorf("No context given. Impossible to use %s", cmdName)
  323. }
  324. // Deal with wildcards
  325. if allowWildcards && containsWildcards(origPath) {
  326. var copyInfos []copyInfo
  327. if err := filepath.Walk(source.Root(), func(path string, info os.FileInfo, err error) error {
  328. if err != nil {
  329. return err
  330. }
  331. rel, err := remotecontext.Rel(source.Root(), path)
  332. if err != nil {
  333. return err
  334. }
  335. if rel == "." {
  336. return nil
  337. }
  338. if match, _ := filepath.Match(origPath, rel); !match {
  339. return nil
  340. }
  341. // Note we set allowWildcards to false in case the name has
  342. // a * in it
  343. subInfos, err := b.calcCopyInfo(cmdName, rel, allowLocalDecompression, false, imageSource)
  344. if err != nil {
  345. return err
  346. }
  347. copyInfos = append(copyInfos, subInfos...)
  348. return nil
  349. }); err != nil {
  350. return nil, err
  351. }
  352. return copyInfos, nil
  353. }
  354. // Must be a dir or a file
  355. hash, err := source.Hash(origPath)
  356. if err != nil {
  357. return nil, err
  358. }
  359. fi, err := remotecontext.StatAt(source, origPath)
  360. if err != nil {
  361. return nil, err
  362. }
  363. // TODO: remove, handle dirs in Hash()
  364. copyInfos := []copyInfo{{root: source.Root(), path: origPath, hash: hash, decompress: allowLocalDecompression}}
  365. if imageSource != nil {
  366. // fast-cache based on imageID
  367. if h, ok := b.imageContexts.getCache(imageSource.id, origPath); ok {
  368. copyInfos[0].hash = h.(string)
  369. return copyInfos, nil
  370. }
  371. }
  372. // Deal with the single file case
  373. if !fi.IsDir() {
  374. copyInfos[0].hash = "file:" + copyInfos[0].hash
  375. return copyInfos, nil
  376. }
  377. fp, err := remotecontext.FullPath(source, origPath)
  378. if err != nil {
  379. return nil, err
  380. }
  381. // Must be a dir
  382. var subfiles []string
  383. err = filepath.Walk(fp, func(path string, info os.FileInfo, err error) error {
  384. if err != nil {
  385. return err
  386. }
  387. rel, err := remotecontext.Rel(source.Root(), path)
  388. if err != nil {
  389. return err
  390. }
  391. if rel == "." {
  392. return nil
  393. }
  394. hash, err := source.Hash(rel)
  395. if err != nil {
  396. return nil
  397. }
  398. // we already checked handleHash above
  399. subfiles = append(subfiles, hash)
  400. return nil
  401. })
  402. if err != nil {
  403. return nil, err
  404. }
  405. sort.Strings(subfiles)
  406. hasher := sha256.New()
  407. hasher.Write([]byte(strings.Join(subfiles, ",")))
  408. copyInfos[0].hash = "dir:" + hex.EncodeToString(hasher.Sum(nil))
  409. if imageSource != nil {
  410. b.imageContexts.setCache(imageSource.id, origPath, copyInfos[0].hash)
  411. }
  412. return copyInfos, nil
  413. }
  414. func (b *Builder) processImageFrom(img builder.Image) error {
  415. if img != nil {
  416. b.image = img.ImageID()
  417. if img.RunConfig() != nil {
  418. b.runConfig = img.RunConfig()
  419. }
  420. }
  421. // Check to see if we have a default PATH, note that windows won't
  422. // have one as it's set by HCS
  423. if system.DefaultPathEnv != "" {
  424. if _, ok := b.runConfigEnvMapping()["PATH"]; !ok {
  425. b.runConfig.Env = append(b.runConfig.Env,
  426. "PATH="+system.DefaultPathEnv)
  427. }
  428. }
  429. if img == nil {
  430. // Typically this means they used "FROM scratch"
  431. return nil
  432. }
  433. // Process ONBUILD triggers if they exist
  434. if nTriggers := len(b.runConfig.OnBuild); nTriggers != 0 {
  435. word := "trigger"
  436. if nTriggers > 1 {
  437. word = "triggers"
  438. }
  439. fmt.Fprintf(b.Stderr, "# Executing %d build %s...\n", nTriggers, word)
  440. }
  441. // Copy the ONBUILD triggers, and remove them from the config, since the config will be committed.
  442. onBuildTriggers := b.runConfig.OnBuild
  443. b.runConfig.OnBuild = []string{}
  444. // Reset stdin settings as all build actions run without stdin
  445. b.runConfig.OpenStdin = false
  446. b.runConfig.StdinOnce = false
  447. // parse the ONBUILD triggers by invoking the parser
  448. for _, step := range onBuildTriggers {
  449. result, err := parser.Parse(strings.NewReader(step))
  450. if err != nil {
  451. return err
  452. }
  453. for _, n := range result.AST.Children {
  454. if err := checkDispatch(n); err != nil {
  455. return err
  456. }
  457. upperCasedCmd := strings.ToUpper(n.Value)
  458. switch upperCasedCmd {
  459. case "ONBUILD":
  460. return errors.New("Chaining ONBUILD via `ONBUILD ONBUILD` isn't allowed")
  461. case "MAINTAINER", "FROM":
  462. return errors.Errorf("%s isn't allowed as an ONBUILD trigger", upperCasedCmd)
  463. }
  464. }
  465. if err := dispatchFromDockerfile(b, result); err != nil {
  466. return err
  467. }
  468. }
  469. return nil
  470. }
  471. // probeCache checks if cache match can be found for current build instruction.
  472. // If an image is found, probeCache returns `(true, nil)`.
  473. // If no image is found, it returns `(false, nil)`.
  474. // If there is any error, it returns `(false, err)`.
  475. func (b *Builder) probeCache(imageID string, runConfig *container.Config) (bool, error) {
  476. c := b.imageCache
  477. if c == nil || b.options.NoCache || b.cacheBusted {
  478. return false, nil
  479. }
  480. cache, err := c.GetCache(imageID, runConfig)
  481. if err != nil {
  482. return false, err
  483. }
  484. if len(cache) == 0 {
  485. logrus.Debugf("[BUILDER] Cache miss: %s", runConfig.Cmd)
  486. b.cacheBusted = true
  487. return false, nil
  488. }
  489. fmt.Fprint(b.Stdout, " ---> Using cache\n")
  490. logrus.Debugf("[BUILDER] Use cached version: %s", runConfig.Cmd)
  491. b.image = string(cache)
  492. b.imageContexts.update(b.image, runConfig)
  493. return true, nil
  494. }
  495. func (b *Builder) create(runConfig *container.Config) (string, error) {
  496. if !b.hasFromImage() {
  497. return "", errors.New("Please provide a source image with `from` prior to run")
  498. }
  499. resources := container.Resources{
  500. CgroupParent: b.options.CgroupParent,
  501. CPUShares: b.options.CPUShares,
  502. CPUPeriod: b.options.CPUPeriod,
  503. CPUQuota: b.options.CPUQuota,
  504. CpusetCpus: b.options.CPUSetCPUs,
  505. CpusetMems: b.options.CPUSetMems,
  506. Memory: b.options.Memory,
  507. MemorySwap: b.options.MemorySwap,
  508. Ulimits: b.options.Ulimits,
  509. }
  510. // TODO: why not embed a hostconfig in builder?
  511. hostConfig := &container.HostConfig{
  512. SecurityOpt: b.options.SecurityOpt,
  513. Isolation: b.options.Isolation,
  514. ShmSize: b.options.ShmSize,
  515. Resources: resources,
  516. NetworkMode: container.NetworkMode(b.options.NetworkMode),
  517. // Set a log config to override any default value set on the daemon
  518. LogConfig: defaultLogConfig,
  519. ExtraHosts: b.options.ExtraHosts,
  520. }
  521. // Create the container
  522. c, err := b.docker.ContainerCreate(types.ContainerCreateConfig{
  523. Config: runConfig,
  524. HostConfig: hostConfig,
  525. })
  526. if err != nil {
  527. return "", err
  528. }
  529. for _, warning := range c.Warnings {
  530. fmt.Fprintf(b.Stdout, " ---> [Warning] %s\n", warning)
  531. }
  532. b.tmpContainers[c.ID] = struct{}{}
  533. fmt.Fprintf(b.Stdout, " ---> Running in %s\n", stringid.TruncateID(c.ID))
  534. // override the entry point that may have been picked up from the base image
  535. if err := b.docker.ContainerUpdateCmdOnBuild(c.ID, runConfig.Cmd); err != nil {
  536. return "", err
  537. }
  538. return c.ID, nil
  539. }
  540. var errCancelled = errors.New("build cancelled")
  541. func (b *Builder) run(cID string, cmd []string) (err error) {
  542. attached := make(chan struct{})
  543. errCh := make(chan error)
  544. go func() {
  545. errCh <- b.docker.ContainerAttachRaw(cID, nil, b.Stdout, b.Stderr, true, attached)
  546. }()
  547. select {
  548. case err := <-errCh:
  549. return err
  550. case <-attached:
  551. }
  552. finished := make(chan struct{})
  553. cancelErrCh := make(chan error, 1)
  554. go func() {
  555. select {
  556. case <-b.clientCtx.Done():
  557. logrus.Debugln("Build cancelled, killing and removing container:", cID)
  558. b.docker.ContainerKill(cID, 0)
  559. b.removeContainer(cID)
  560. cancelErrCh <- errCancelled
  561. case <-finished:
  562. cancelErrCh <- nil
  563. }
  564. }()
  565. if err := b.docker.ContainerStart(cID, nil, "", ""); err != nil {
  566. close(finished)
  567. if cancelErr := <-cancelErrCh; cancelErr != nil {
  568. logrus.Debugf("Build cancelled (%v) and got an error from ContainerStart: %v",
  569. cancelErr, err)
  570. }
  571. return err
  572. }
  573. // Block on reading output from container, stop on err or chan closed
  574. if err := <-errCh; err != nil {
  575. close(finished)
  576. if cancelErr := <-cancelErrCh; cancelErr != nil {
  577. logrus.Debugf("Build cancelled (%v) and got an error from errCh: %v",
  578. cancelErr, err)
  579. }
  580. return err
  581. }
  582. if ret, _ := b.docker.ContainerWait(cID, -1); ret != 0 {
  583. close(finished)
  584. if cancelErr := <-cancelErrCh; cancelErr != nil {
  585. logrus.Debugf("Build cancelled (%v) and got a non-zero code from ContainerWait: %d",
  586. cancelErr, ret)
  587. }
  588. // TODO: change error type, because jsonmessage.JSONError assumes HTTP
  589. return &jsonmessage.JSONError{
  590. Message: fmt.Sprintf("The command '%s' returned a non-zero code: %d", strings.Join(cmd, " "), ret),
  591. Code: ret,
  592. }
  593. }
  594. close(finished)
  595. return <-cancelErrCh
  596. }
  597. func (b *Builder) removeContainer(c string) error {
  598. rmConfig := &types.ContainerRmConfig{
  599. ForceRemove: true,
  600. RemoveVolume: true,
  601. }
  602. if err := b.docker.ContainerRm(c, rmConfig); err != nil {
  603. fmt.Fprintf(b.Stdout, "Error removing intermediate container %s: %v\n", stringid.TruncateID(c), err)
  604. return err
  605. }
  606. return nil
  607. }
  608. func (b *Builder) clearTmp() {
  609. for c := range b.tmpContainers {
  610. if err := b.removeContainer(c); err != nil {
  611. return
  612. }
  613. delete(b.tmpContainers, c)
  614. fmt.Fprintf(b.Stdout, "Removing intermediate container %s\n", stringid.TruncateID(c))
  615. }
  616. }