internals.go 21 KB

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