internals.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721
  1. package builder
  2. // internals for handling commands. Covers many areas and a lot of
  3. // non-contiguous functionality. Please read the comments.
  4. import (
  5. "crypto/sha256"
  6. "encoding/hex"
  7. "fmt"
  8. "io"
  9. "io/ioutil"
  10. "net/http"
  11. "net/url"
  12. "os"
  13. "path"
  14. "path/filepath"
  15. "sort"
  16. "strings"
  17. "syscall"
  18. "time"
  19. log "github.com/Sirupsen/logrus"
  20. "github.com/docker/docker/builder/parser"
  21. "github.com/docker/docker/daemon"
  22. imagepkg "github.com/docker/docker/image"
  23. "github.com/docker/docker/pkg/archive"
  24. "github.com/docker/docker/pkg/chrootarchive"
  25. "github.com/docker/docker/pkg/parsers"
  26. "github.com/docker/docker/pkg/symlink"
  27. "github.com/docker/docker/pkg/system"
  28. "github.com/docker/docker/pkg/tarsum"
  29. "github.com/docker/docker/pkg/urlutil"
  30. "github.com/docker/docker/registry"
  31. "github.com/docker/docker/utils"
  32. )
  33. func (b *Builder) readContext(context io.Reader) error {
  34. tmpdirPath, err := ioutil.TempDir("", "docker-build")
  35. if err != nil {
  36. return err
  37. }
  38. decompressedStream, err := archive.DecompressStream(context)
  39. if err != nil {
  40. return err
  41. }
  42. if b.context, err = tarsum.NewTarSum(decompressedStream, true, tarsum.Version0); err != nil {
  43. return err
  44. }
  45. if err := chrootarchive.Untar(b.context, tmpdirPath, nil); err != nil {
  46. return err
  47. }
  48. b.contextPath = tmpdirPath
  49. return nil
  50. }
  51. func (b *Builder) commit(id string, autoCmd []string, comment string) error {
  52. if b.image == "" && !b.noBaseImage {
  53. return fmt.Errorf("Please provide a source image with `from` prior to commit")
  54. }
  55. b.Config.Image = b.image
  56. if id == "" {
  57. cmd := b.Config.Cmd
  58. b.Config.Cmd = []string{"/bin/sh", "-c", "#(nop) " + comment}
  59. defer func(cmd []string) { b.Config.Cmd = cmd }(cmd)
  60. hit, err := b.probeCache()
  61. if err != nil {
  62. return err
  63. }
  64. if hit {
  65. return nil
  66. }
  67. container, err := b.create()
  68. if err != nil {
  69. return err
  70. }
  71. id = container.ID
  72. if err := container.Mount(); err != nil {
  73. return err
  74. }
  75. defer container.Unmount()
  76. }
  77. container := b.Daemon.Get(id)
  78. if container == nil {
  79. return fmt.Errorf("An error occured while creating the container")
  80. }
  81. // Note: Actually copy the struct
  82. autoConfig := *b.Config
  83. autoConfig.Cmd = autoCmd
  84. // Commit the container
  85. image, err := b.Daemon.Commit(container, "", "", "", b.maintainer, true, &autoConfig)
  86. if err != nil {
  87. return err
  88. }
  89. b.image = image.ID
  90. return nil
  91. }
  92. type copyInfo struct {
  93. origPath string
  94. destPath string
  95. hash string
  96. decompress bool
  97. tmpDir string
  98. }
  99. func (b *Builder) runContextCommand(args []string, allowRemote bool, allowDecompression bool, cmdName string) error {
  100. if b.context == nil {
  101. return fmt.Errorf("No context given. Impossible to use %s", cmdName)
  102. }
  103. if len(args) < 2 {
  104. return fmt.Errorf("Invalid %s format - at least two arguments required", cmdName)
  105. }
  106. dest := args[len(args)-1] // last one is always the dest
  107. copyInfos := []*copyInfo{}
  108. b.Config.Image = b.image
  109. defer func() {
  110. for _, ci := range copyInfos {
  111. if ci.tmpDir != "" {
  112. os.RemoveAll(ci.tmpDir)
  113. }
  114. }
  115. }()
  116. // Loop through each src file and calculate the info we need to
  117. // do the copy (e.g. hash value if cached). Don't actually do
  118. // the copy until we've looked at all src files
  119. for _, orig := range args[0 : len(args)-1] {
  120. err := calcCopyInfo(b, cmdName, &copyInfos, orig, dest, allowRemote, allowDecompression)
  121. if err != nil {
  122. return err
  123. }
  124. }
  125. if len(copyInfos) == 0 {
  126. return fmt.Errorf("No source files were specified")
  127. }
  128. if len(copyInfos) > 1 && !strings.HasSuffix(dest, "/") {
  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 CI then use it as the
  132. // cache look-up string, otherwise hash 'em all into one
  133. var srcHash string
  134. var origPaths string
  135. if len(copyInfos) == 1 {
  136. srcHash = copyInfos[0].hash
  137. origPaths = copyInfos[0].origPath
  138. } else {
  139. var hashs []string
  140. var origs []string
  141. for _, ci := range copyInfos {
  142. hashs = append(hashs, ci.hash)
  143. origs = append(origs, ci.origPath)
  144. }
  145. hasher := sha256.New()
  146. hasher.Write([]byte(strings.Join(hashs, ",")))
  147. srcHash = "multi:" + hex.EncodeToString(hasher.Sum(nil))
  148. origPaths = strings.Join(origs, " ")
  149. }
  150. cmd := b.Config.Cmd
  151. b.Config.Cmd = []string{"/bin/sh", "-c", fmt.Sprintf("#(nop) %s %s in %s", cmdName, srcHash, dest)}
  152. defer func(cmd []string) { b.Config.Cmd = cmd }(cmd)
  153. hit, err := b.probeCache()
  154. if err != nil {
  155. return err
  156. }
  157. // If we do not have at least one hash, never use the cache
  158. if hit && b.UtilizeCache {
  159. return nil
  160. }
  161. container, _, err := b.Daemon.Create(b.Config, nil, "")
  162. if err != nil {
  163. return err
  164. }
  165. b.TmpContainers[container.ID] = struct{}{}
  166. if err := container.Mount(); err != nil {
  167. return err
  168. }
  169. defer container.Unmount()
  170. for _, ci := range copyInfos {
  171. if err := b.addContext(container, ci.origPath, ci.destPath, ci.decompress); err != nil {
  172. return err
  173. }
  174. }
  175. if err := b.commit(container.ID, cmd, fmt.Sprintf("%s %s in %s", cmdName, origPaths, dest)); err != nil {
  176. return err
  177. }
  178. return nil
  179. }
  180. func calcCopyInfo(b *Builder, cmdName string, cInfos *[]*copyInfo, origPath string, destPath string, allowRemote bool, allowDecompression bool) error {
  181. if origPath != "" && origPath[0] == '/' && len(origPath) > 1 {
  182. origPath = origPath[1:]
  183. }
  184. origPath = strings.TrimPrefix(origPath, "./")
  185. // Twiddle the destPath when its a relative path - meaning, make it
  186. // relative to the WORKINGDIR
  187. if !filepath.IsAbs(destPath) {
  188. hasSlash := strings.HasSuffix(destPath, "/")
  189. destPath = filepath.Join("/", b.Config.WorkingDir, destPath)
  190. // Make sure we preserve any trailing slash
  191. if hasSlash {
  192. destPath += "/"
  193. }
  194. }
  195. // In the remote/URL case, download it and gen its hashcode
  196. if urlutil.IsURL(origPath) {
  197. if !allowRemote {
  198. return fmt.Errorf("Source can't be a URL for %s", cmdName)
  199. }
  200. ci := copyInfo{}
  201. ci.origPath = origPath
  202. ci.hash = origPath // default to this but can change
  203. ci.destPath = destPath
  204. ci.decompress = false
  205. *cInfos = append(*cInfos, &ci)
  206. // Initiate the download
  207. resp, err := utils.Download(ci.origPath)
  208. if err != nil {
  209. return err
  210. }
  211. // Create a tmp dir
  212. tmpDirName, err := ioutil.TempDir(b.contextPath, "docker-remote")
  213. if err != nil {
  214. return err
  215. }
  216. ci.tmpDir = tmpDirName
  217. // Create a tmp file within our tmp dir
  218. tmpFileName := path.Join(tmpDirName, "tmp")
  219. tmpFile, err := os.OpenFile(tmpFileName, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0600)
  220. if err != nil {
  221. return err
  222. }
  223. // Download and dump result to tmp file
  224. if _, err := io.Copy(tmpFile, utils.ProgressReader(resp.Body, int(resp.ContentLength), b.OutOld, b.StreamFormatter, true, "", "Downloading")); err != nil {
  225. tmpFile.Close()
  226. return err
  227. }
  228. fmt.Fprintf(b.OutStream, "\n")
  229. tmpFile.Close()
  230. // Set the mtime to the Last-Modified header value if present
  231. // Otherwise just remove atime and mtime
  232. times := make([]syscall.Timespec, 2)
  233. lastMod := resp.Header.Get("Last-Modified")
  234. if lastMod != "" {
  235. mTime, err := http.ParseTime(lastMod)
  236. // If we can't parse it then just let it default to 'zero'
  237. // otherwise use the parsed time value
  238. if err == nil {
  239. times[1] = syscall.NsecToTimespec(mTime.UnixNano())
  240. }
  241. }
  242. if err := system.UtimesNano(tmpFileName, times); err != nil {
  243. return err
  244. }
  245. ci.origPath = path.Join(filepath.Base(tmpDirName), filepath.Base(tmpFileName))
  246. // If the destination is a directory, figure out the filename.
  247. if strings.HasSuffix(ci.destPath, "/") {
  248. u, err := url.Parse(origPath)
  249. if err != nil {
  250. return err
  251. }
  252. path := u.Path
  253. if strings.HasSuffix(path, "/") {
  254. path = path[:len(path)-1]
  255. }
  256. parts := strings.Split(path, "/")
  257. filename := parts[len(parts)-1]
  258. if filename == "" {
  259. return fmt.Errorf("cannot determine filename from url: %s", u)
  260. }
  261. ci.destPath = ci.destPath + filename
  262. }
  263. // Calc the checksum, even if we're using the cache
  264. r, err := archive.Tar(tmpFileName, archive.Uncompressed)
  265. if err != nil {
  266. return err
  267. }
  268. tarSum, err := tarsum.NewTarSum(r, true, tarsum.Version0)
  269. if err != nil {
  270. return err
  271. }
  272. if _, err := io.Copy(ioutil.Discard, tarSum); err != nil {
  273. return err
  274. }
  275. ci.hash = tarSum.Sum(nil)
  276. r.Close()
  277. return nil
  278. }
  279. // Deal with wildcards
  280. if ContainsWildcards(origPath) {
  281. for _, fileInfo := range b.context.GetSums() {
  282. if fileInfo.Name() == "" {
  283. continue
  284. }
  285. match, _ := path.Match(origPath, fileInfo.Name())
  286. if !match {
  287. continue
  288. }
  289. calcCopyInfo(b, cmdName, cInfos, fileInfo.Name(), destPath, allowRemote, allowDecompression)
  290. }
  291. return nil
  292. }
  293. // Must be a dir or a file
  294. if err := b.checkPathForAddition(origPath); err != nil {
  295. return err
  296. }
  297. fi, _ := os.Stat(path.Join(b.contextPath, origPath))
  298. ci := copyInfo{}
  299. ci.origPath = origPath
  300. ci.hash = origPath
  301. ci.destPath = destPath
  302. ci.decompress = allowDecompression
  303. *cInfos = append(*cInfos, &ci)
  304. // Deal with the single file case
  305. if !fi.IsDir() {
  306. // This will match first file in sums of the archive
  307. fis := b.context.GetSums().GetFile(ci.origPath)
  308. if fis != nil {
  309. ci.hash = "file:" + fis.Sum()
  310. }
  311. return nil
  312. }
  313. // Must be a dir
  314. var subfiles []string
  315. absOrigPath := path.Join(b.contextPath, ci.origPath)
  316. // Add a trailing / to make sure we only pick up nested files under
  317. // the dir and not sibling files of the dir that just happen to
  318. // start with the same chars
  319. if !strings.HasSuffix(absOrigPath, "/") {
  320. absOrigPath += "/"
  321. }
  322. // Need path w/o / too to find matching dir w/o trailing /
  323. absOrigPathNoSlash := absOrigPath[:len(absOrigPath)-1]
  324. for _, fileInfo := range b.context.GetSums() {
  325. absFile := path.Join(b.contextPath, fileInfo.Name())
  326. // Any file in the context that starts with the given path will be
  327. // picked up and its hashcode used. However, we'll exclude the
  328. // root dir itself. We do this for a coupel of reasons:
  329. // 1 - ADD/COPY will not copy the dir itself, just its children
  330. // so there's no reason to include it in the hash calc
  331. // 2 - the metadata on the dir will change when any child file
  332. // changes. This will lead to a miss in the cache check if that
  333. // child file is in the .dockerignore list.
  334. if strings.HasPrefix(absFile, absOrigPath) && absFile != absOrigPathNoSlash {
  335. subfiles = append(subfiles, fileInfo.Sum())
  336. }
  337. }
  338. sort.Strings(subfiles)
  339. hasher := sha256.New()
  340. hasher.Write([]byte(strings.Join(subfiles, ",")))
  341. ci.hash = "dir:" + hex.EncodeToString(hasher.Sum(nil))
  342. return nil
  343. }
  344. func ContainsWildcards(name string) bool {
  345. for i := 0; i < len(name); i++ {
  346. ch := name[i]
  347. if ch == '\\' {
  348. i++
  349. } else if ch == '*' || ch == '?' || ch == '[' {
  350. return true
  351. }
  352. }
  353. return false
  354. }
  355. func (b *Builder) pullImage(name string) (*imagepkg.Image, error) {
  356. remote, tag := parsers.ParseRepositoryTag(name)
  357. if tag == "" {
  358. tag = "latest"
  359. }
  360. job := b.Engine.Job("pull", remote, tag)
  361. pullRegistryAuth := b.AuthConfig
  362. if len(b.AuthConfigFile.Configs) > 0 {
  363. // The request came with a full auth config file, we prefer to use that
  364. repoInfo, err := registry.ResolveRepositoryInfo(job, remote)
  365. if err != nil {
  366. return nil, err
  367. }
  368. resolvedAuth := b.AuthConfigFile.ResolveAuthConfig(repoInfo.Index)
  369. pullRegistryAuth = &resolvedAuth
  370. }
  371. job.SetenvBool("json", b.StreamFormatter.Json())
  372. job.SetenvBool("parallel", true)
  373. job.SetenvJson("authConfig", pullRegistryAuth)
  374. job.Stdout.Add(b.OutOld)
  375. if err := job.Run(); err != nil {
  376. return nil, err
  377. }
  378. image, err := b.Daemon.Repositories().LookupImage(name)
  379. if err != nil {
  380. return nil, err
  381. }
  382. return image, nil
  383. }
  384. func (b *Builder) processImageFrom(img *imagepkg.Image) error {
  385. b.image = img.ID
  386. if img.Config != nil {
  387. b.Config = img.Config
  388. }
  389. if len(b.Config.Env) == 0 {
  390. b.Config.Env = append(b.Config.Env, "PATH="+daemon.DefaultPathEnv)
  391. }
  392. // Process ONBUILD triggers if they exist
  393. if nTriggers := len(b.Config.OnBuild); nTriggers != 0 {
  394. fmt.Fprintf(b.ErrStream, "# Executing %d build triggers\n", nTriggers)
  395. }
  396. // Copy the ONBUILD triggers, and remove them from the config, since the config will be commited.
  397. onBuildTriggers := b.Config.OnBuild
  398. b.Config.OnBuild = []string{}
  399. // parse the ONBUILD triggers by invoking the parser
  400. for stepN, step := range onBuildTriggers {
  401. ast, err := parser.Parse(strings.NewReader(step))
  402. if err != nil {
  403. return err
  404. }
  405. for i, n := range ast.Children {
  406. switch strings.ToUpper(n.Value) {
  407. case "ONBUILD":
  408. return fmt.Errorf("Chaining ONBUILD via `ONBUILD ONBUILD` isn't allowed")
  409. case "MAINTAINER", "FROM":
  410. return fmt.Errorf("%s isn't allowed as an ONBUILD trigger", n.Value)
  411. }
  412. fmt.Fprintf(b.OutStream, "Trigger %d, %s\n", stepN, step)
  413. if err := b.dispatch(i, n); err != nil {
  414. return err
  415. }
  416. }
  417. }
  418. return nil
  419. }
  420. // probeCache checks to see if image-caching is enabled (`b.UtilizeCache`)
  421. // and if so attempts to look up the current `b.image` and `b.Config` pair
  422. // in the current server `b.Daemon`. If an image is found, probeCache returns
  423. // `(true, nil)`. If no image is found, it returns `(false, nil)`. If there
  424. // is any error, it returns `(false, err)`.
  425. func (b *Builder) probeCache() (bool, error) {
  426. if b.UtilizeCache {
  427. if cache, err := b.Daemon.ImageGetCached(b.image, b.Config); err != nil {
  428. return false, err
  429. } else if cache != nil {
  430. fmt.Fprintf(b.OutStream, " ---> Using cache\n")
  431. log.Debugf("[BUILDER] Use cached version")
  432. b.image = cache.ID
  433. return true, nil
  434. } else {
  435. log.Debugf("[BUILDER] Cache miss")
  436. }
  437. }
  438. return false, nil
  439. }
  440. func (b *Builder) create() (*daemon.Container, error) {
  441. if b.image == "" && !b.noBaseImage {
  442. return nil, fmt.Errorf("Please provide a source image with `from` prior to run")
  443. }
  444. b.Config.Image = b.image
  445. config := *b.Config
  446. // Create the container
  447. c, warnings, err := b.Daemon.Create(b.Config, nil, "")
  448. if err != nil {
  449. return nil, err
  450. }
  451. for _, warning := range warnings {
  452. fmt.Fprintf(b.OutStream, " ---> [Warning] %s\n", warning)
  453. }
  454. b.TmpContainers[c.ID] = struct{}{}
  455. fmt.Fprintf(b.OutStream, " ---> Running in %s\n", utils.TruncateID(c.ID))
  456. if len(config.Cmd) > 0 {
  457. // override the entry point that may have been picked up from the base image
  458. c.Path = config.Cmd[0]
  459. c.Args = config.Cmd[1:]
  460. } else {
  461. config.Cmd = []string{}
  462. }
  463. return c, nil
  464. }
  465. func (b *Builder) run(c *daemon.Container) error {
  466. //start the container
  467. if err := c.Start(); err != nil {
  468. return err
  469. }
  470. if b.Verbose {
  471. logsJob := b.Engine.Job("logs", c.ID)
  472. logsJob.Setenv("follow", "1")
  473. logsJob.Setenv("stdout", "1")
  474. logsJob.Setenv("stderr", "1")
  475. logsJob.Stdout.Add(b.OutStream)
  476. logsJob.Stderr.Set(b.ErrStream)
  477. if err := logsJob.Run(); err != nil {
  478. return err
  479. }
  480. }
  481. // Wait for it to finish
  482. if ret, _ := c.WaitStop(-1 * time.Second); ret != 0 {
  483. err := &utils.JSONError{
  484. Message: fmt.Sprintf("The command %v returned a non-zero code: %d", b.Config.Cmd, ret),
  485. Code: ret,
  486. }
  487. return err
  488. }
  489. return nil
  490. }
  491. func (b *Builder) checkPathForAddition(orig string) error {
  492. origPath := path.Join(b.contextPath, orig)
  493. origPath, err := filepath.EvalSymlinks(origPath)
  494. if err != nil {
  495. if os.IsNotExist(err) {
  496. return fmt.Errorf("%s: no such file or directory", orig)
  497. }
  498. return err
  499. }
  500. if !strings.HasPrefix(origPath, b.contextPath) {
  501. return fmt.Errorf("Forbidden path outside the build context: %s (%s)", orig, origPath)
  502. }
  503. if _, err := os.Stat(origPath); err != nil {
  504. if os.IsNotExist(err) {
  505. return fmt.Errorf("%s: no such file or directory", orig)
  506. }
  507. return err
  508. }
  509. return nil
  510. }
  511. func (b *Builder) addContext(container *daemon.Container, orig, dest string, decompress bool) error {
  512. var (
  513. err error
  514. destExists = true
  515. origPath = path.Join(b.contextPath, orig)
  516. destPath = path.Join(container.RootfsPath(), dest)
  517. )
  518. if destPath != container.RootfsPath() {
  519. destPath, err = symlink.FollowSymlinkInScope(destPath, container.RootfsPath())
  520. if err != nil {
  521. return err
  522. }
  523. }
  524. // Preserve the trailing '/'
  525. if strings.HasSuffix(dest, "/") || dest == "." {
  526. destPath = destPath + "/"
  527. }
  528. destStat, err := os.Stat(destPath)
  529. if err != nil {
  530. if !os.IsNotExist(err) {
  531. return err
  532. }
  533. destExists = false
  534. }
  535. fi, err := os.Stat(origPath)
  536. if err != nil {
  537. if os.IsNotExist(err) {
  538. return fmt.Errorf("%s: no such file or directory", orig)
  539. }
  540. return err
  541. }
  542. if fi.IsDir() {
  543. return copyAsDirectory(origPath, destPath, destExists)
  544. }
  545. // If we are adding a remote file (or we've been told not to decompress), do not try to untar it
  546. if decompress {
  547. // First try to unpack the source as an archive
  548. // to support the untar feature we need to clean up the path a little bit
  549. // because tar is very forgiving. First we need to strip off the archive's
  550. // filename from the path but this is only added if it does not end in / .
  551. tarDest := destPath
  552. if strings.HasSuffix(tarDest, "/") {
  553. tarDest = filepath.Dir(destPath)
  554. }
  555. // try to successfully untar the orig
  556. if err := chrootarchive.UntarPath(origPath, tarDest); err == nil {
  557. return nil
  558. } else if err != io.EOF {
  559. log.Debugf("Couldn't untar %s to %s: %s", origPath, tarDest, err)
  560. }
  561. }
  562. if err := os.MkdirAll(path.Dir(destPath), 0755); err != nil {
  563. return err
  564. }
  565. if err := chrootarchive.CopyWithTar(origPath, destPath); err != nil {
  566. return err
  567. }
  568. resPath := destPath
  569. if destExists && destStat.IsDir() {
  570. resPath = path.Join(destPath, path.Base(origPath))
  571. }
  572. return fixPermissions(origPath, resPath, 0, 0, destExists)
  573. }
  574. func copyAsDirectory(source, destination string, destExisted bool) error {
  575. if err := chrootarchive.CopyWithTar(source, destination); err != nil {
  576. return err
  577. }
  578. return fixPermissions(source, destination, 0, 0, destExisted)
  579. }
  580. func fixPermissions(source, destination string, uid, gid int, destExisted bool) error {
  581. // If the destination didn't already exist, or the destination isn't a
  582. // directory, then we should Lchown the destination. Otherwise, we shouldn't
  583. // Lchown the destination.
  584. destStat, err := os.Stat(destination)
  585. if err != nil {
  586. // This should *never* be reached, because the destination must've already
  587. // been created while untar-ing the context.
  588. return err
  589. }
  590. doChownDestination := !destExisted || !destStat.IsDir()
  591. // We Walk on the source rather than on the destination because we don't
  592. // want to change permissions on things we haven't created or modified.
  593. return filepath.Walk(source, func(fullpath string, info os.FileInfo, err error) error {
  594. // Do not alter the walk root iff. it existed before, as it doesn't fall under
  595. // the domain of "things we should chown".
  596. if !doChownDestination && (source == fullpath) {
  597. return nil
  598. }
  599. // Path is prefixed by source: substitute with destination instead.
  600. cleaned, err := filepath.Rel(source, fullpath)
  601. if err != nil {
  602. return err
  603. }
  604. fullpath = path.Join(destination, cleaned)
  605. return os.Lchown(fullpath, uid, gid)
  606. })
  607. }
  608. func (b *Builder) clearTmp() {
  609. for c := range b.TmpContainers {
  610. tmp := b.Daemon.Get(c)
  611. if err := b.Daemon.Destroy(tmp); err != nil {
  612. fmt.Fprintf(b.OutStream, "Error removing intermediate container %s: %s\n", utils.TruncateID(c), err.Error())
  613. return
  614. }
  615. b.Daemon.DeleteVolumes(tmp.VolumePaths())
  616. delete(b.TmpContainers, c)
  617. fmt.Fprintf(b.OutStream, "Removing intermediate container %s\n", utils.TruncateID(c))
  618. }
  619. }