internals.go 18 KB

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