internals.go 15 KB

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