internals.go 17 KB

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