internals.go 21 KB

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