internals.go 19 KB

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