internals.go 20 KB

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