internals.go 15 KB

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