internals.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574
  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, err := tarsum.NewTarSum(r, true, tarsum.Version0)
  147. if err != nil {
  148. return err
  149. }
  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 _, fileInfo := range sums {
  189. absFile := path.Join(b.contextPath, fileInfo.Name())
  190. absOrigPath := path.Join(b.contextPath, origPath)
  191. if strings.HasPrefix(absFile, absOrigPath) {
  192. subfiles = append(subfiles, fileInfo.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. // This will match on the first file in sums of the archive
  205. if fis := sums.GetFile(origPath); fis != nil {
  206. hash = "file:" + fis.Sum()
  207. }
  208. }
  209. b.Config.Cmd = []string{"/bin/sh", "-c", fmt.Sprintf("#(nop) %s %s in %s", cmdName, hash, dest)}
  210. hit, err := b.probeCache()
  211. if err != nil {
  212. return err
  213. }
  214. // If we do not have a hash, never use the cache
  215. if hit && hash != "" {
  216. return nil
  217. }
  218. }
  219. // Create the container
  220. container, _, err := b.Daemon.Create(b.Config, "")
  221. if err != nil {
  222. return err
  223. }
  224. b.TmpContainers[container.ID] = struct{}{}
  225. if err := container.Mount(); err != nil {
  226. return err
  227. }
  228. defer container.Unmount()
  229. if !allowDecompression || isRemote {
  230. decompress = false
  231. }
  232. if err := b.addContext(container, origPath, destPath, decompress); err != nil {
  233. return err
  234. }
  235. if err := b.commit(container.ID, cmd, fmt.Sprintf("%s %s in %s", cmdName, orig, dest)); err != nil {
  236. return err
  237. }
  238. return nil
  239. }
  240. func (b *Builder) pullImage(name string) (*imagepkg.Image, error) {
  241. remote, tag := parsers.ParseRepositoryTag(name)
  242. if tag == "" {
  243. tag = "latest"
  244. }
  245. pullRegistryAuth := b.AuthConfig
  246. if len(b.AuthConfigFile.Configs) > 0 {
  247. // The request came with a full auth config file, we prefer to use that
  248. endpoint, _, err := registry.ResolveRepositoryName(remote)
  249. if err != nil {
  250. return nil, err
  251. }
  252. resolvedAuth := b.AuthConfigFile.ResolveAuthConfig(endpoint)
  253. pullRegistryAuth = &resolvedAuth
  254. }
  255. job := b.Engine.Job("pull", remote, tag)
  256. job.SetenvBool("json", b.StreamFormatter.Json())
  257. job.SetenvBool("parallel", true)
  258. job.SetenvJson("authConfig", pullRegistryAuth)
  259. job.Stdout.Add(b.OutOld)
  260. if err := job.Run(); err != nil {
  261. return nil, err
  262. }
  263. image, err := b.Daemon.Repositories().LookupImage(name)
  264. if err != nil {
  265. return nil, err
  266. }
  267. return image, nil
  268. }
  269. func (b *Builder) processImageFrom(img *imagepkg.Image) error {
  270. b.image = img.ID
  271. if img.Config != nil {
  272. b.Config = img.Config
  273. }
  274. if len(b.Config.Env) == 0 {
  275. b.Config.Env = append(b.Config.Env, "PATH="+daemon.DefaultPathEnv)
  276. }
  277. // Process ONBUILD triggers if they exist
  278. if nTriggers := len(b.Config.OnBuild); nTriggers != 0 {
  279. fmt.Fprintf(b.ErrStream, "# Executing %d build triggers\n", nTriggers)
  280. }
  281. // Copy the ONBUILD triggers, and remove them from the config, since the config will be commited.
  282. onBuildTriggers := b.Config.OnBuild
  283. b.Config.OnBuild = []string{}
  284. // FIXME rewrite this so that builder/parser is used; right now steps in
  285. // onbuild are muted because we have no good way to represent the step
  286. // number
  287. for _, step := range onBuildTriggers {
  288. splitStep := strings.Split(step, " ")
  289. stepInstruction := strings.ToUpper(strings.Trim(splitStep[0], " "))
  290. switch stepInstruction {
  291. case "ONBUILD":
  292. return fmt.Errorf("Source image contains forbidden chained `ONBUILD ONBUILD` trigger: %s", step)
  293. case "MAINTAINER", "FROM":
  294. return fmt.Errorf("Source image contains forbidden %s trigger: %s", stepInstruction, step)
  295. }
  296. // FIXME we have to run the evaluator manually here. This does not belong
  297. // in this function. Once removed, the init() in evaluator.go should no
  298. // longer be necessary.
  299. if f, ok := evaluateTable[strings.ToLower(stepInstruction)]; ok {
  300. if err := f(b, splitStep[1:], nil); err != nil {
  301. return err
  302. }
  303. } else {
  304. return fmt.Errorf("%s doesn't appear to be a valid Dockerfile instruction", splitStep[0])
  305. }
  306. }
  307. return nil
  308. }
  309. // probeCache checks to see if image-caching is enabled (`b.UtilizeCache`)
  310. // and if so attempts to look up the current `b.image` and `b.Config` pair
  311. // in the current server `b.Daemon`. If an image is found, probeCache returns
  312. // `(true, nil)`. If no image is found, it returns `(false, nil)`. If there
  313. // is any error, it returns `(false, err)`.
  314. func (b *Builder) probeCache() (bool, error) {
  315. if b.UtilizeCache {
  316. if cache, err := b.Daemon.ImageGetCached(b.image, b.Config); err != nil {
  317. return false, err
  318. } else if cache != nil {
  319. fmt.Fprintf(b.OutStream, " ---> Using cache\n")
  320. log.Debugf("[BUILDER] Use cached version")
  321. b.image = cache.ID
  322. return true, nil
  323. } else {
  324. log.Debugf("[BUILDER] Cache miss")
  325. }
  326. }
  327. return false, nil
  328. }
  329. func (b *Builder) create() (*daemon.Container, error) {
  330. if b.image == "" {
  331. return nil, fmt.Errorf("Please provide a source image with `from` prior to run")
  332. }
  333. b.Config.Image = b.image
  334. config := *b.Config
  335. // Create the container
  336. c, warnings, err := b.Daemon.Create(b.Config, "")
  337. if err != nil {
  338. return nil, err
  339. }
  340. for _, warning := range warnings {
  341. fmt.Fprintf(b.OutStream, " ---> [Warning] %s\n", warning)
  342. }
  343. b.TmpContainers[c.ID] = struct{}{}
  344. fmt.Fprintf(b.OutStream, " ---> Running in %s\n", utils.TruncateID(c.ID))
  345. // override the entry point that may have been picked up from the base image
  346. c.Path = config.Cmd[0]
  347. c.Args = config.Cmd[1:]
  348. return c, nil
  349. }
  350. func (b *Builder) run(c *daemon.Container) error {
  351. var errCh chan error
  352. if b.Verbose {
  353. errCh = utils.Go(func() error {
  354. // FIXME: call the 'attach' job so that daemon.Attach can be made private
  355. //
  356. // FIXME (LK4D4): Also, maybe makes sense to call "logs" job, it is like attach
  357. // but without hijacking for stdin. Also, with attach there can be race
  358. // condition because of some output already was printed before it.
  359. return <-b.Daemon.Attach(&c.StreamConfig, c.Config.OpenStdin, c.Config.StdinOnce, c.Config.Tty, nil, nil, b.OutStream, b.ErrStream)
  360. })
  361. }
  362. //start the container
  363. if err := c.Start(); err != nil {
  364. return err
  365. }
  366. if errCh != nil {
  367. if err := <-errCh; err != nil {
  368. return err
  369. }
  370. }
  371. // Wait for it to finish
  372. if ret, _ := c.WaitStop(-1 * time.Second); ret != 0 {
  373. err := &utils.JSONError{
  374. Message: fmt.Sprintf("The command %v returned a non-zero code: %d", b.Config.Cmd, ret),
  375. Code: ret,
  376. }
  377. return err
  378. }
  379. return nil
  380. }
  381. func (b *Builder) checkPathForAddition(orig string) error {
  382. origPath := path.Join(b.contextPath, orig)
  383. origPath, err := filepath.EvalSymlinks(origPath)
  384. if err != nil {
  385. if os.IsNotExist(err) {
  386. return fmt.Errorf("%s: no such file or directory", orig)
  387. }
  388. return err
  389. }
  390. if !strings.HasPrefix(origPath, b.contextPath) {
  391. return fmt.Errorf("Forbidden path outside the build context: %s (%s)", orig, origPath)
  392. }
  393. if _, err := os.Stat(origPath); err != nil {
  394. if os.IsNotExist(err) {
  395. return fmt.Errorf("%s: no such file or directory", orig)
  396. }
  397. return err
  398. }
  399. return nil
  400. }
  401. func (b *Builder) addContext(container *daemon.Container, orig, dest string, decompress bool) error {
  402. var (
  403. err error
  404. destExists = true
  405. origPath = path.Join(b.contextPath, orig)
  406. destPath = path.Join(container.RootfsPath(), dest)
  407. )
  408. if destPath != container.RootfsPath() {
  409. destPath, err = symlink.FollowSymlinkInScope(destPath, container.RootfsPath())
  410. if err != nil {
  411. return err
  412. }
  413. }
  414. // Preserve the trailing '/'
  415. if strings.HasSuffix(dest, "/") || dest == "." {
  416. destPath = destPath + "/"
  417. }
  418. destStat, err := os.Stat(destPath)
  419. if err != nil {
  420. if !os.IsNotExist(err) {
  421. return err
  422. }
  423. destExists = false
  424. }
  425. fi, err := os.Stat(origPath)
  426. if err != nil {
  427. if os.IsNotExist(err) {
  428. return fmt.Errorf("%s: no such file or directory", orig)
  429. }
  430. return err
  431. }
  432. if fi.IsDir() {
  433. return copyAsDirectory(origPath, destPath, destExists)
  434. }
  435. // If we are adding a remote file (or we've been told not to decompress), do not try to untar it
  436. if decompress {
  437. // First try to unpack the source as an archive
  438. // to support the untar feature we need to clean up the path a little bit
  439. // because tar is very forgiving. First we need to strip off the archive's
  440. // filename from the path but this is only added if it does not end in / .
  441. tarDest := destPath
  442. if strings.HasSuffix(tarDest, "/") {
  443. tarDest = filepath.Dir(destPath)
  444. }
  445. // try to successfully untar the orig
  446. if err := archive.UntarPath(origPath, tarDest); err == nil {
  447. return nil
  448. } else if err != io.EOF {
  449. log.Debugf("Couldn't untar %s to %s: %s", origPath, tarDest, err)
  450. }
  451. }
  452. if err := os.MkdirAll(path.Dir(destPath), 0755); err != nil {
  453. return err
  454. }
  455. if err := archive.CopyWithTar(origPath, destPath); err != nil {
  456. return err
  457. }
  458. resPath := destPath
  459. if destExists && destStat.IsDir() {
  460. resPath = path.Join(destPath, path.Base(origPath))
  461. }
  462. return fixPermissions(resPath, 0, 0)
  463. }
  464. func copyAsDirectory(source, destination string, destinationExists bool) error {
  465. if err := archive.CopyWithTar(source, destination); err != nil {
  466. return err
  467. }
  468. if destinationExists {
  469. files, err := ioutil.ReadDir(source)
  470. if err != nil {
  471. return err
  472. }
  473. for _, file := range files {
  474. if err := fixPermissions(filepath.Join(destination, file.Name()), 0, 0); err != nil {
  475. return err
  476. }
  477. }
  478. return nil
  479. }
  480. return fixPermissions(destination, 0, 0)
  481. }
  482. func fixPermissions(destination string, uid, gid int) error {
  483. return filepath.Walk(destination, func(path string, info os.FileInfo, err error) error {
  484. if err := os.Lchown(path, uid, gid); err != nil && !os.IsNotExist(err) {
  485. return err
  486. }
  487. return nil
  488. })
  489. }
  490. func (b *Builder) clearTmp() {
  491. for c := range b.TmpContainers {
  492. tmp := b.Daemon.Get(c)
  493. if err := b.Daemon.Destroy(tmp); err != nil {
  494. fmt.Fprintf(b.OutStream, "Error removing intermediate container %s: %s\n", utils.TruncateID(c), err.Error())
  495. } else {
  496. delete(b.TmpContainers, c)
  497. fmt.Fprintf(b.OutStream, "Removing intermediate container %s\n", utils.TruncateID(c))
  498. }
  499. }
  500. }