internals.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563
  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, resp.Body); err != nil {
  134. tmpFile.Close()
  135. return err
  136. }
  137. tmpFile.Close()
  138. // Remove the mtime of the newly created tmp file
  139. if err := system.UtimesNano(tmpFileName, make([]syscall.Timespec, 2)); err != nil {
  140. return err
  141. }
  142. origPath = path.Join(filepath.Base(tmpDirName), filepath.Base(tmpFileName))
  143. // Process the checksum
  144. r, err := archive.Tar(tmpFileName, archive.Uncompressed)
  145. if err != nil {
  146. return err
  147. }
  148. tarSum := &tarsum.TarSum{Reader: r, DisableCompression: true}
  149. if _, err := io.Copy(ioutil.Discard, tarSum); err != nil {
  150. return err
  151. }
  152. remoteHash = tarSum.Sum(nil)
  153. r.Close()
  154. // If the destination is a directory, figure out the filename.
  155. if strings.HasSuffix(dest, "/") {
  156. u, err := url.Parse(orig)
  157. if err != nil {
  158. return err
  159. }
  160. path := u.Path
  161. if strings.HasSuffix(path, "/") {
  162. path = path[:len(path)-1]
  163. }
  164. parts := strings.Split(path, "/")
  165. filename := parts[len(parts)-1]
  166. if filename == "" {
  167. return fmt.Errorf("cannot determine filename from url: %s", u)
  168. }
  169. destPath = dest + filename
  170. }
  171. }
  172. if err := b.checkPathForAddition(origPath); err != nil {
  173. return err
  174. }
  175. // Hash path and check the cache
  176. if b.UtilizeCache {
  177. var (
  178. hash string
  179. sums = b.context.GetSums()
  180. )
  181. if remoteHash != "" {
  182. hash = remoteHash
  183. } else if fi, err := os.Stat(path.Join(b.contextPath, origPath)); err != nil {
  184. return err
  185. } else if fi.IsDir() {
  186. var subfiles []string
  187. for file, sum := range sums {
  188. absFile := path.Join(b.contextPath, file)
  189. absOrigPath := path.Join(b.contextPath, origPath)
  190. if strings.HasPrefix(absFile, absOrigPath) {
  191. subfiles = append(subfiles, sum)
  192. }
  193. }
  194. sort.Strings(subfiles)
  195. hasher := sha256.New()
  196. hasher.Write([]byte(strings.Join(subfiles, ",")))
  197. hash = "dir:" + hex.EncodeToString(hasher.Sum(nil))
  198. } else {
  199. if origPath[0] == '/' && len(origPath) > 1 {
  200. origPath = origPath[1:]
  201. }
  202. origPath = strings.TrimPrefix(origPath, "./")
  203. if h, ok := sums[origPath]; ok {
  204. hash = "file:" + h
  205. }
  206. }
  207. b.Config.Cmd = []string{"/bin/sh", "-c", fmt.Sprintf("#(nop) %s %s in %s", cmdName, hash, dest)}
  208. hit, err := b.probeCache()
  209. if err != nil {
  210. return err
  211. }
  212. // If we do not have a hash, never use the cache
  213. if hit && hash != "" {
  214. return nil
  215. }
  216. }
  217. // Create the container
  218. container, _, err := b.Daemon.Create(b.Config, "")
  219. if err != nil {
  220. return err
  221. }
  222. b.TmpContainers[container.ID] = struct{}{}
  223. if err := container.Mount(); err != nil {
  224. return err
  225. }
  226. defer container.Unmount()
  227. if !allowDecompression || isRemote {
  228. decompress = false
  229. }
  230. if err := b.addContext(container, origPath, destPath, decompress); err != nil {
  231. return err
  232. }
  233. if err := b.commit(container.ID, cmd, fmt.Sprintf("%s %s in %s", cmdName, orig, dest)); err != nil {
  234. return err
  235. }
  236. return nil
  237. }
  238. func (b *Builder) pullImage(name string) (*imagepkg.Image, error) {
  239. remote, tag := parsers.ParseRepositoryTag(name)
  240. pullRegistryAuth := b.AuthConfig
  241. if len(b.AuthConfigFile.Configs) > 0 {
  242. // The request came with a full auth config file, we prefer to use that
  243. endpoint, _, err := registry.ResolveRepositoryName(remote)
  244. if err != nil {
  245. return nil, err
  246. }
  247. resolvedAuth := b.AuthConfigFile.ResolveAuthConfig(endpoint)
  248. pullRegistryAuth = &resolvedAuth
  249. }
  250. job := b.Engine.Job("pull", remote, tag)
  251. job.SetenvBool("json", b.StreamFormatter.Json())
  252. job.SetenvBool("parallel", true)
  253. job.SetenvJson("authConfig", pullRegistryAuth)
  254. job.Stdout.Add(b.OutOld)
  255. if err := job.Run(); err != nil {
  256. return nil, err
  257. }
  258. image, err := b.Daemon.Repositories().LookupImage(name)
  259. if err != nil {
  260. return nil, err
  261. }
  262. return image, nil
  263. }
  264. func (b *Builder) processImageFrom(img *imagepkg.Image) error {
  265. b.image = img.ID
  266. if img.Config != nil {
  267. b.Config = img.Config
  268. }
  269. if len(b.Config.Env) == 0 {
  270. b.Config.Env = append(b.Config.Env, "PATH="+daemon.DefaultPathEnv)
  271. }
  272. // Process ONBUILD triggers if they exist
  273. if nTriggers := len(b.Config.OnBuild); nTriggers != 0 {
  274. fmt.Fprintf(b.ErrStream, "# Executing %d build triggers\n", nTriggers)
  275. }
  276. // Copy the ONBUILD triggers, and remove them from the config, since the config will be commited.
  277. onBuildTriggers := b.Config.OnBuild
  278. b.Config.OnBuild = []string{}
  279. // FIXME rewrite this so that builder/parser is used; right now steps in
  280. // onbuild are muted because we have no good way to represent the step
  281. // number
  282. for _, step := range onBuildTriggers {
  283. splitStep := strings.Split(step, " ")
  284. stepInstruction := strings.ToUpper(strings.Trim(splitStep[0], " "))
  285. switch stepInstruction {
  286. case "ONBUILD":
  287. return fmt.Errorf("Source image contains forbidden chained `ONBUILD ONBUILD` trigger: %s", step)
  288. case "MAINTAINER", "FROM":
  289. return fmt.Errorf("Source image contains forbidden %s trigger: %s", stepInstruction, step)
  290. }
  291. // FIXME we have to run the evaluator manually here. This does not belong
  292. // in this function. Once removed, the init() in evaluator.go should no
  293. // longer be necessary.
  294. if f, ok := evaluateTable[strings.ToLower(stepInstruction)]; ok {
  295. if err := f(b, splitStep[1:], nil); err != nil {
  296. return err
  297. }
  298. } else {
  299. return fmt.Errorf("%s doesn't appear to be a valid Dockerfile instruction", splitStep[0])
  300. }
  301. }
  302. return nil
  303. }
  304. // probeCache checks to see if image-caching is enabled (`b.UtilizeCache`)
  305. // and if so attempts to look up the current `b.image` and `b.Config` pair
  306. // in the current server `b.Daemon`. If an image is found, probeCache returns
  307. // `(true, nil)`. If no image is found, it returns `(false, nil)`. If there
  308. // is any error, it returns `(false, err)`.
  309. func (b *Builder) probeCache() (bool, error) {
  310. if b.UtilizeCache {
  311. if cache, err := b.Daemon.ImageGetCached(b.image, b.Config); err != nil {
  312. return false, err
  313. } else if cache != nil {
  314. fmt.Fprintf(b.OutStream, " ---> Using cache\n")
  315. log.Debugf("[BUILDER] Use cached version")
  316. b.image = cache.ID
  317. return true, nil
  318. } else {
  319. log.Debugf("[BUILDER] Cache miss")
  320. }
  321. }
  322. return false, nil
  323. }
  324. func (b *Builder) create() (*daemon.Container, error) {
  325. if b.image == "" {
  326. return nil, fmt.Errorf("Please provide a source image with `from` prior to run")
  327. }
  328. b.Config.Image = b.image
  329. // Create the container
  330. c, _, err := b.Daemon.Create(b.Config, "")
  331. if err != nil {
  332. return nil, err
  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 = b.Config.Cmd[0]
  338. c.Args = b.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.State.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. }