internals.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564
  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/url"
  11. "os"
  12. "path"
  13. "path/filepath"
  14. "sort"
  15. "strings"
  16. "syscall"
  17. "time"
  18. "github.com/docker/docker/archive"
  19. "github.com/docker/docker/daemon"
  20. imagepkg "github.com/docker/docker/image"
  21. "github.com/docker/docker/pkg/log"
  22. "github.com/docker/docker/pkg/parsers"
  23. "github.com/docker/docker/pkg/symlink"
  24. "github.com/docker/docker/pkg/system"
  25. "github.com/docker/docker/pkg/tarsum"
  26. "github.com/docker/docker/registry"
  27. "github.com/docker/docker/utils"
  28. )
  29. func (b *Builder) readContext(context io.Reader) error {
  30. tmpdirPath, err := ioutil.TempDir("", "docker-build")
  31. if err != nil {
  32. return err
  33. }
  34. decompressedStream, err := archive.DecompressStream(context)
  35. if err != nil {
  36. return err
  37. }
  38. b.context = &tarsum.TarSum{Reader: decompressedStream, DisableCompression: true}
  39. if err := archive.Untar(b.context, tmpdirPath, nil); err != nil {
  40. return err
  41. }
  42. b.contextPath = tmpdirPath
  43. return nil
  44. }
  45. func (b *Builder) commit(id string, autoCmd []string, comment string) error {
  46. if b.image == "" {
  47. return fmt.Errorf("Please provide a source image with `from` prior to commit")
  48. }
  49. b.Config.Image = b.image
  50. if id == "" {
  51. cmd := b.Config.Cmd
  52. b.Config.Cmd = []string{"/bin/sh", "-c", "#(nop) " + comment}
  53. defer func(cmd []string) { b.Config.Cmd = cmd }(cmd)
  54. hit, err := b.probeCache()
  55. if err != nil {
  56. return err
  57. }
  58. if hit {
  59. return nil
  60. }
  61. container, err := b.create()
  62. if err != nil {
  63. return err
  64. }
  65. id = container.ID
  66. if err := container.Mount(); err != nil {
  67. return err
  68. }
  69. defer container.Unmount()
  70. }
  71. container := b.Daemon.Get(id)
  72. if container == nil {
  73. return fmt.Errorf("An error occured while creating the container")
  74. }
  75. // Note: Actually copy the struct
  76. autoConfig := *b.Config
  77. autoConfig.Cmd = autoCmd
  78. // Commit the container
  79. image, err := b.Daemon.Commit(container, "", "", "", b.maintainer, true, &autoConfig)
  80. if err != nil {
  81. return err
  82. }
  83. b.image = image.ID
  84. return nil
  85. }
  86. func (b *Builder) runContextCommand(args []string, allowRemote bool, allowDecompression bool, cmdName string) error {
  87. if b.context == nil {
  88. return fmt.Errorf("No context given. Impossible to use %s", cmdName)
  89. }
  90. if len(args) != 2 {
  91. return fmt.Errorf("Invalid %s format", cmdName)
  92. }
  93. orig := args[0]
  94. dest := args[1]
  95. cmd := b.Config.Cmd
  96. b.Config.Cmd = []string{"/bin/sh", "-c", fmt.Sprintf("#(nop) %s %s in %s", cmdName, orig, dest)}
  97. defer func(cmd []string) { b.Config.Cmd = cmd }(cmd)
  98. b.Config.Image = b.image
  99. var (
  100. origPath = orig
  101. destPath = dest
  102. remoteHash string
  103. isRemote bool
  104. decompress = true
  105. )
  106. isRemote = utils.IsURL(orig)
  107. if isRemote && !allowRemote {
  108. return fmt.Errorf("Source can't be an URL for %s", cmdName)
  109. } else if utils.IsURL(orig) {
  110. // Initiate the download
  111. resp, err := utils.Download(orig)
  112. if err != nil {
  113. return err
  114. }
  115. // Create a tmp dir
  116. tmpDirName, err := ioutil.TempDir(b.contextPath, "docker-remote")
  117. if err != nil {
  118. return err
  119. }
  120. // Create a tmp file within our tmp dir
  121. tmpFileName := path.Join(tmpDirName, "tmp")
  122. tmpFile, err := os.OpenFile(tmpFileName, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0600)
  123. if err != nil {
  124. return err
  125. }
  126. defer os.RemoveAll(tmpDirName)
  127. // Download and dump result to tmp file
  128. if _, err := io.Copy(tmpFile, utils.ProgressReader(resp.Body, int(resp.ContentLength), b.OutOld, b.StreamFormatter, true, "", "Downloading")); err != nil {
  129. tmpFile.Close()
  130. return err
  131. }
  132. fmt.Fprintf(b.OutStream, "\n")
  133. tmpFile.Close()
  134. // Remove the mtime of the newly created tmp file
  135. if err := system.UtimesNano(tmpFileName, make([]syscall.Timespec, 2)); err != nil {
  136. return err
  137. }
  138. origPath = path.Join(filepath.Base(tmpDirName), filepath.Base(tmpFileName))
  139. // Process the checksum
  140. r, err := archive.Tar(tmpFileName, archive.Uncompressed)
  141. if err != nil {
  142. return err
  143. }
  144. tarSum := &tarsum.TarSum{Reader: r, DisableCompression: true}
  145. if _, err := io.Copy(ioutil.Discard, tarSum); err != nil {
  146. return err
  147. }
  148. remoteHash = tarSum.Sum(nil)
  149. r.Close()
  150. // If the destination is a directory, figure out the filename.
  151. if strings.HasSuffix(dest, "/") {
  152. u, err := url.Parse(orig)
  153. if err != nil {
  154. return err
  155. }
  156. path := u.Path
  157. if strings.HasSuffix(path, "/") {
  158. path = path[:len(path)-1]
  159. }
  160. parts := strings.Split(path, "/")
  161. filename := parts[len(parts)-1]
  162. if filename == "" {
  163. return fmt.Errorf("cannot determine filename from url: %s", u)
  164. }
  165. destPath = dest + filename
  166. }
  167. }
  168. if err := b.checkPathForAddition(origPath); err != nil {
  169. return err
  170. }
  171. // Hash path and check the cache
  172. if b.UtilizeCache {
  173. var (
  174. hash string
  175. sums = b.context.GetSums()
  176. )
  177. if remoteHash != "" {
  178. hash = remoteHash
  179. } else if fi, err := os.Stat(path.Join(b.contextPath, origPath)); err != nil {
  180. return err
  181. } else if fi.IsDir() {
  182. var subfiles []string
  183. for file, sum := range sums {
  184. absFile := path.Join(b.contextPath, file)
  185. absOrigPath := path.Join(b.contextPath, origPath)
  186. if strings.HasPrefix(absFile, absOrigPath) {
  187. subfiles = append(subfiles, sum)
  188. }
  189. }
  190. sort.Strings(subfiles)
  191. hasher := sha256.New()
  192. hasher.Write([]byte(strings.Join(subfiles, ",")))
  193. hash = "dir:" + hex.EncodeToString(hasher.Sum(nil))
  194. } else {
  195. if origPath[0] == '/' && len(origPath) > 1 {
  196. origPath = origPath[1:]
  197. }
  198. origPath = strings.TrimPrefix(origPath, "./")
  199. if h, ok := sums[origPath]; ok {
  200. hash = "file:" + h
  201. }
  202. }
  203. b.Config.Cmd = []string{"/bin/sh", "-c", fmt.Sprintf("#(nop) %s %s in %s", cmdName, hash, dest)}
  204. hit, err := b.probeCache()
  205. if err != nil {
  206. return err
  207. }
  208. // If we do not have a hash, never use the cache
  209. if hit && hash != "" {
  210. return nil
  211. }
  212. }
  213. // Create the container
  214. container, _, err := b.Daemon.Create(b.Config, "")
  215. if err != nil {
  216. return err
  217. }
  218. b.TmpContainers[container.ID] = struct{}{}
  219. if err := container.Mount(); err != nil {
  220. return err
  221. }
  222. defer container.Unmount()
  223. if !allowDecompression || isRemote {
  224. decompress = false
  225. }
  226. if err := b.addContext(container, origPath, destPath, decompress); err != nil {
  227. return err
  228. }
  229. if err := b.commit(container.ID, cmd, fmt.Sprintf("%s %s in %s", cmdName, orig, dest)); err != nil {
  230. return err
  231. }
  232. return nil
  233. }
  234. func (b *Builder) pullImage(name string) (*imagepkg.Image, error) {
  235. remote, tag := parsers.ParseRepositoryTag(name)
  236. pullRegistryAuth := b.AuthConfig
  237. if len(b.AuthConfigFile.Configs) > 0 {
  238. // The request came with a full auth config file, we prefer to use that
  239. endpoint, _, err := registry.ResolveRepositoryName(remote)
  240. if err != nil {
  241. return nil, err
  242. }
  243. resolvedAuth := b.AuthConfigFile.ResolveAuthConfig(endpoint)
  244. pullRegistryAuth = &resolvedAuth
  245. }
  246. job := b.Engine.Job("pull", remote, tag)
  247. job.SetenvBool("json", b.StreamFormatter.Json())
  248. job.SetenvBool("parallel", true)
  249. job.SetenvJson("authConfig", pullRegistryAuth)
  250. job.Stdout.Add(b.OutOld)
  251. if err := job.Run(); err != nil {
  252. return nil, err
  253. }
  254. image, err := b.Daemon.Repositories().LookupImage(name)
  255. if err != nil {
  256. return nil, err
  257. }
  258. return image, nil
  259. }
  260. func (b *Builder) processImageFrom(img *imagepkg.Image) error {
  261. b.image = img.ID
  262. if img.Config != nil {
  263. b.Config = img.Config
  264. }
  265. if len(b.Config.Env) == 0 {
  266. b.Config.Env = append(b.Config.Env, "PATH="+daemon.DefaultPathEnv)
  267. }
  268. // Process ONBUILD triggers if they exist
  269. if nTriggers := len(b.Config.OnBuild); nTriggers != 0 {
  270. fmt.Fprintf(b.ErrStream, "# Executing %d build triggers\n", nTriggers)
  271. }
  272. // Copy the ONBUILD triggers, and remove them from the config, since the config will be commited.
  273. onBuildTriggers := b.Config.OnBuild
  274. b.Config.OnBuild = []string{}
  275. // FIXME rewrite this so that builder/parser is used; right now steps in
  276. // onbuild are muted because we have no good way to represent the step
  277. // number
  278. for _, step := range onBuildTriggers {
  279. splitStep := strings.Split(step, " ")
  280. stepInstruction := strings.ToUpper(strings.Trim(splitStep[0], " "))
  281. switch stepInstruction {
  282. case "ONBUILD":
  283. return fmt.Errorf("Source image contains forbidden chained `ONBUILD ONBUILD` trigger: %s", step)
  284. case "MAINTAINER", "FROM":
  285. return fmt.Errorf("Source image contains forbidden %s trigger: %s", stepInstruction, step)
  286. }
  287. // FIXME we have to run the evaluator manually here. This does not belong
  288. // in this function. Once removed, the init() in evaluator.go should no
  289. // longer be necessary.
  290. if f, ok := evaluateTable[strings.ToLower(stepInstruction)]; ok {
  291. if err := f(b, splitStep[1:], nil); err != nil {
  292. return err
  293. }
  294. } else {
  295. return fmt.Errorf("%s doesn't appear to be a valid Dockerfile instruction", splitStep[0])
  296. }
  297. }
  298. return nil
  299. }
  300. // probeCache checks to see if image-caching is enabled (`b.UtilizeCache`)
  301. // and if so attempts to look up the current `b.image` and `b.Config` pair
  302. // in the current server `b.Daemon`. If an image is found, probeCache returns
  303. // `(true, nil)`. If no image is found, it returns `(false, nil)`. If there
  304. // is any error, it returns `(false, err)`.
  305. func (b *Builder) probeCache() (bool, error) {
  306. if b.UtilizeCache {
  307. if cache, err := b.Daemon.ImageGetCached(b.image, b.Config); err != nil {
  308. return false, err
  309. } else if cache != nil {
  310. fmt.Fprintf(b.OutStream, " ---> Using cache\n")
  311. log.Debugf("[BUILDER] Use cached version")
  312. b.image = cache.ID
  313. return true, nil
  314. } else {
  315. log.Debugf("[BUILDER] Cache miss")
  316. }
  317. }
  318. return false, nil
  319. }
  320. func (b *Builder) create() (*daemon.Container, error) {
  321. if b.image == "" {
  322. return nil, fmt.Errorf("Please provide a source image with `from` prior to run")
  323. }
  324. b.Config.Image = b.image
  325. config := *b.Config
  326. // Create the container
  327. c, warnings, err := b.Daemon.Create(b.Config, "")
  328. if err != nil {
  329. return nil, err
  330. }
  331. for _, warning := range warnings {
  332. fmt.Fprintf(b.OutStream, " ---> [Warning] %s\n", warning)
  333. }
  334. b.TmpContainers[c.ID] = struct{}{}
  335. fmt.Fprintf(b.OutStream, " ---> Running in %s\n", utils.TruncateID(c.ID))
  336. // override the entry point that may have been picked up from the base image
  337. c.Path = config.Cmd[0]
  338. c.Args = config.Cmd[1:]
  339. return c, nil
  340. }
  341. func (b *Builder) run(c *daemon.Container) error {
  342. var errCh chan error
  343. if b.Verbose {
  344. errCh = utils.Go(func() error {
  345. // FIXME: call the 'attach' job so that daemon.Attach can be made private
  346. //
  347. // FIXME (LK4D4): Also, maybe makes sense to call "logs" job, it is like attach
  348. // but without hijacking for stdin. Also, with attach there can be race
  349. // condition because of some output already was printed before it.
  350. return <-b.Daemon.Attach(c, nil, nil, b.OutStream, b.ErrStream)
  351. })
  352. }
  353. //start the container
  354. if err := c.Start(); err != nil {
  355. return err
  356. }
  357. if errCh != nil {
  358. if err := <-errCh; err != nil {
  359. return err
  360. }
  361. }
  362. // Wait for it to finish
  363. if ret, _ := c.WaitStop(-1 * time.Second); ret != 0 {
  364. err := &utils.JSONError{
  365. Message: fmt.Sprintf("The command %v returned a non-zero code: %d", b.Config.Cmd, ret),
  366. Code: ret,
  367. }
  368. return err
  369. }
  370. return nil
  371. }
  372. func (b *Builder) checkPathForAddition(orig string) error {
  373. origPath := path.Join(b.contextPath, orig)
  374. origPath, err := filepath.EvalSymlinks(origPath)
  375. if err != nil {
  376. if os.IsNotExist(err) {
  377. return fmt.Errorf("%s: no such file or directory", orig)
  378. }
  379. return err
  380. }
  381. if !strings.HasPrefix(origPath, b.contextPath) {
  382. return fmt.Errorf("Forbidden path outside the build context: %s (%s)", orig, origPath)
  383. }
  384. if _, err := os.Stat(origPath); err != nil {
  385. if os.IsNotExist(err) {
  386. return fmt.Errorf("%s: no such file or directory", orig)
  387. }
  388. return err
  389. }
  390. return nil
  391. }
  392. func (b *Builder) addContext(container *daemon.Container, orig, dest string, decompress bool) error {
  393. var (
  394. err error
  395. destExists = true
  396. origPath = path.Join(b.contextPath, orig)
  397. destPath = path.Join(container.RootfsPath(), dest)
  398. )
  399. if destPath != container.RootfsPath() {
  400. destPath, err = symlink.FollowSymlinkInScope(destPath, container.RootfsPath())
  401. if err != nil {
  402. return err
  403. }
  404. }
  405. // Preserve the trailing '/'
  406. if strings.HasSuffix(dest, "/") || dest == "." {
  407. destPath = destPath + "/"
  408. }
  409. destStat, err := os.Stat(destPath)
  410. if err != nil {
  411. if !os.IsNotExist(err) {
  412. return err
  413. }
  414. destExists = false
  415. }
  416. fi, err := os.Stat(origPath)
  417. if err != nil {
  418. if os.IsNotExist(err) {
  419. return fmt.Errorf("%s: no such file or directory", orig)
  420. }
  421. return err
  422. }
  423. if fi.IsDir() {
  424. return copyAsDirectory(origPath, destPath, destExists)
  425. }
  426. // If we are adding a remote file (or we've been told not to decompress), do not try to untar it
  427. if decompress {
  428. // First try to unpack the source as an archive
  429. // to support the untar feature we need to clean up the path a little bit
  430. // because tar is very forgiving. First we need to strip off the archive's
  431. // filename from the path but this is only added if it does not end in / .
  432. tarDest := destPath
  433. if strings.HasSuffix(tarDest, "/") {
  434. tarDest = filepath.Dir(destPath)
  435. }
  436. // try to successfully untar the orig
  437. if err := archive.UntarPath(origPath, tarDest); err == nil {
  438. return nil
  439. } else if err != io.EOF {
  440. log.Debugf("Couldn't untar %s to %s: %s", origPath, tarDest, err)
  441. }
  442. }
  443. if err := os.MkdirAll(path.Dir(destPath), 0755); err != nil {
  444. return err
  445. }
  446. if err := archive.CopyWithTar(origPath, destPath); err != nil {
  447. return err
  448. }
  449. resPath := destPath
  450. if destExists && destStat.IsDir() {
  451. resPath = path.Join(destPath, path.Base(origPath))
  452. }
  453. return fixPermissions(resPath, 0, 0)
  454. }
  455. func copyAsDirectory(source, destination string, destinationExists bool) error {
  456. if err := archive.CopyWithTar(source, destination); err != nil {
  457. return err
  458. }
  459. if destinationExists {
  460. files, err := ioutil.ReadDir(source)
  461. if err != nil {
  462. return err
  463. }
  464. for _, file := range files {
  465. if err := fixPermissions(filepath.Join(destination, file.Name()), 0, 0); err != nil {
  466. return err
  467. }
  468. }
  469. return nil
  470. }
  471. return fixPermissions(destination, 0, 0)
  472. }
  473. func fixPermissions(destination string, uid, gid int) error {
  474. return filepath.Walk(destination, func(path string, info os.FileInfo, err error) error {
  475. if err := os.Lchown(path, uid, gid); err != nil && !os.IsNotExist(err) {
  476. return err
  477. }
  478. return nil
  479. })
  480. }
  481. func (b *Builder) clearTmp() {
  482. for c := range b.TmpContainers {
  483. tmp := b.Daemon.Get(c)
  484. if err := b.Daemon.Destroy(tmp); err != nil {
  485. fmt.Fprintf(b.OutStream, "Error removing intermediate container %s: %s\n", utils.TruncateID(c), err.Error())
  486. } else {
  487. delete(b.TmpContainers, c)
  488. fmt.Fprintf(b.OutStream, "Removing intermediate container %s\n", utils.TruncateID(c))
  489. }
  490. }
  491. }