internals.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562
  1. package evaluator
  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 *BuildFile) 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 *BuildFile) 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.Options.Daemon.Create(b.Config, "")
  62. if err != nil {
  63. return err
  64. }
  65. for _, warning := range warnings {
  66. fmt.Fprintf(b.Options.OutStream, " ---> [Warning] %s\n", warning)
  67. }
  68. b.TmpContainers[container.ID] = struct{}{}
  69. fmt.Fprintf(b.Options.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.Options.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.Options.Daemon.Commit(container, "", "", "", b.maintainer, true, &autoConfig)
  85. if err != nil {
  86. return err
  87. }
  88. b.TmpImages[image.ID] = struct{}{}
  89. b.image = image.ID
  90. return nil
  91. }
  92. func (b *BuildFile) runContextCommand(args []string, allowRemote bool, allowDecompression bool, cmdName string) error {
  93. if b.context == nil {
  94. return fmt.Errorf("No context given. Impossible to use %s", cmdName)
  95. }
  96. if len(args) != 2 {
  97. return fmt.Errorf("Invalid %s format", cmdName)
  98. }
  99. orig := args[0]
  100. dest := args[1]
  101. cmd := b.Config.Cmd
  102. b.Config.Cmd = []string{"/bin/sh", "-c", fmt.Sprintf("#(nop) %s %s in %s", cmdName, orig, dest)}
  103. defer func(cmd []string) { b.Config.Cmd = cmd }(cmd)
  104. b.Config.Image = b.image
  105. var (
  106. origPath = orig
  107. destPath = dest
  108. remoteHash string
  109. isRemote bool
  110. decompress = true
  111. )
  112. isRemote = utils.IsURL(orig)
  113. if isRemote && !allowRemote {
  114. return fmt.Errorf("Source can't be an URL for %s", cmdName)
  115. } else if utils.IsURL(orig) {
  116. // Initiate the download
  117. resp, err := utils.Download(orig)
  118. if err != nil {
  119. return err
  120. }
  121. // Create a tmp dir
  122. tmpDirName, err := ioutil.TempDir(b.contextPath, "docker-remote")
  123. if err != nil {
  124. return err
  125. }
  126. // Create a tmp file within our tmp dir
  127. tmpFileName := path.Join(tmpDirName, "tmp")
  128. tmpFile, err := os.OpenFile(tmpFileName, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0600)
  129. if err != nil {
  130. return err
  131. }
  132. defer os.RemoveAll(tmpDirName)
  133. // Download and dump result to tmp file
  134. if _, err := io.Copy(tmpFile, resp.Body); err != nil {
  135. tmpFile.Close()
  136. return err
  137. }
  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.Options.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.Options.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 *BuildFile) pullImage(name string) (*imagepkg.Image, error) {
  240. remote, tag := parsers.ParseRepositoryTag(name)
  241. pullRegistryAuth := b.Options.AuthConfig
  242. if len(b.Options.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.Options.AuthConfigFile.ResolveAuthConfig(endpoint)
  249. pullRegistryAuth = &resolvedAuth
  250. }
  251. job := b.Options.Engine.Job("pull", remote, tag)
  252. job.SetenvBool("json", b.Options.StreamFormatter.Json())
  253. job.SetenvBool("parallel", true)
  254. job.SetenvJson("authConfig", pullRegistryAuth)
  255. job.Stdout.Add(b.Options.OutOld)
  256. if err := job.Run(); err != nil {
  257. return nil, err
  258. }
  259. image, err := b.Options.Daemon.Repositories().LookupImage(name)
  260. if err != nil {
  261. return nil, err
  262. }
  263. return image, nil
  264. }
  265. func (b *BuildFile) processImageFrom(img *imagepkg.Image) error {
  266. b.image = img.ID
  267. if img.Config != nil {
  268. b.Config = img.Config
  269. }
  270. if b.Config.Env == nil || 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.Options.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.
  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.Options.UtilizeCache`)
  305. // and if so attempts to look up the current `b.image` and `b.Config` pair
  306. // in the current server `b.Options.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 *BuildFile) probeCache() (bool, error) {
  310. if b.Options.UtilizeCache {
  311. if cache, err := b.Options.Daemon.ImageGetCached(b.image, b.Config); err != nil {
  312. return false, err
  313. } else if cache != nil {
  314. fmt.Fprintf(b.Options.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 *BuildFile) 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.Options.Daemon.Create(b.Config, "")
  331. if err != nil {
  332. return nil, err
  333. }
  334. b.TmpContainers[c.ID] = struct{}{}
  335. fmt.Fprintf(b.Options.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 *BuildFile) run(c *daemon.Container) error {
  342. var errCh chan error
  343. if b.Options.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.Options.Daemon.Attach(c, nil, nil, b.Options.OutStream, b.Options.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 *BuildFile) 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 *BuildFile) 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 *BuildFile) clearTmp(containers map[string]struct{}) {
  482. for c := range containers {
  483. tmp := b.Options.Daemon.Get(c)
  484. if err := b.Options.Daemon.Destroy(tmp); err != nil {
  485. fmt.Fprintf(b.Options.OutStream, "Error removing intermediate container %s: %s\n", utils.TruncateID(c), err.Error())
  486. } else {
  487. delete(containers, c)
  488. fmt.Fprintf(b.Options.OutStream, "Removing intermediate container %s\n", utils.TruncateID(c))
  489. }
  490. }
  491. }