builder.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926
  1. package builder
  2. import (
  3. "crypto/sha256"
  4. "encoding/hex"
  5. "encoding/json"
  6. "errors"
  7. "fmt"
  8. "io"
  9. "io/ioutil"
  10. "net/url"
  11. "os"
  12. "path"
  13. "path/filepath"
  14. "reflect"
  15. "regexp"
  16. "sort"
  17. "strings"
  18. "syscall"
  19. "time"
  20. "github.com/docker/docker/archive"
  21. "github.com/docker/docker/daemon"
  22. "github.com/docker/docker/engine"
  23. "github.com/docker/docker/nat"
  24. "github.com/docker/docker/pkg/parsers"
  25. "github.com/docker/docker/pkg/symlink"
  26. "github.com/docker/docker/pkg/system"
  27. "github.com/docker/docker/pkg/tarsum"
  28. "github.com/docker/docker/registry"
  29. "github.com/docker/docker/runconfig"
  30. "github.com/docker/docker/utils"
  31. )
  32. var (
  33. ErrDockerfileEmpty = errors.New("Dockerfile cannot be empty")
  34. )
  35. type BuildFile interface {
  36. Build(io.Reader) (string, error)
  37. CmdFrom(string) error
  38. CmdRun(string) error
  39. }
  40. type buildFile struct {
  41. daemon *daemon.Daemon
  42. eng *engine.Engine
  43. image string
  44. maintainer string
  45. config *runconfig.Config
  46. contextPath string
  47. context *tarsum.TarSum
  48. verbose bool
  49. utilizeCache bool
  50. rm bool
  51. forceRm bool
  52. authConfig *registry.AuthConfig
  53. configFile *registry.ConfigFile
  54. tmpContainers map[string]struct{}
  55. tmpImages map[string]struct{}
  56. outStream io.Writer
  57. errStream io.Writer
  58. // Deprecated, original writer used for ImagePull. To be removed.
  59. outOld io.Writer
  60. sf *utils.StreamFormatter
  61. // cmdSet indicates is CMD was setted in current Dockerfile
  62. cmdSet bool
  63. }
  64. func (b *buildFile) clearTmp(containers map[string]struct{}) {
  65. for c := range containers {
  66. tmp := b.daemon.Get(c)
  67. if err := b.daemon.Destroy(tmp); err != nil {
  68. fmt.Fprintf(b.outStream, "Error removing intermediate container %s: %s\n", utils.TruncateID(c), err.Error())
  69. } else {
  70. delete(containers, c)
  71. fmt.Fprintf(b.outStream, "Removing intermediate container %s\n", utils.TruncateID(c))
  72. }
  73. }
  74. }
  75. func (b *buildFile) CmdFrom(name string) error {
  76. image, err := b.daemon.Repositories().LookupImage(name)
  77. if err != nil {
  78. if b.daemon.Graph().IsNotExist(err) {
  79. remote, tag := parsers.ParseRepositoryTag(name)
  80. pullRegistryAuth := b.authConfig
  81. if len(b.configFile.Configs) > 0 {
  82. // The request came with a full auth config file, we prefer to use that
  83. endpoint, _, err := registry.ResolveRepositoryName(remote)
  84. if err != nil {
  85. return err
  86. }
  87. resolvedAuth := b.configFile.ResolveAuthConfig(endpoint)
  88. pullRegistryAuth = &resolvedAuth
  89. }
  90. job := b.eng.Job("pull", remote, tag)
  91. job.SetenvBool("json", b.sf.Json())
  92. job.SetenvBool("parallel", true)
  93. job.SetenvJson("authConfig", pullRegistryAuth)
  94. job.Stdout.Add(b.outOld)
  95. if err := job.Run(); err != nil {
  96. return err
  97. }
  98. image, err = b.daemon.Repositories().LookupImage(name)
  99. if err != nil {
  100. return err
  101. }
  102. } else {
  103. return err
  104. }
  105. }
  106. b.image = image.ID
  107. b.config = &runconfig.Config{}
  108. if image.Config != nil {
  109. b.config = image.Config
  110. }
  111. if b.config.Env == nil || len(b.config.Env) == 0 {
  112. b.config.Env = append(b.config.Env, "PATH="+daemon.DefaultPathEnv)
  113. }
  114. // Process ONBUILD triggers if they exist
  115. if nTriggers := len(b.config.OnBuild); nTriggers != 0 {
  116. fmt.Fprintf(b.errStream, "# Executing %d build triggers\n", nTriggers)
  117. }
  118. // Copy the ONBUILD triggers, and remove them from the config, since the config will be commited.
  119. onBuildTriggers := b.config.OnBuild
  120. b.config.OnBuild = []string{}
  121. for n, step := range onBuildTriggers {
  122. splitStep := strings.Split(step, " ")
  123. stepInstruction := strings.ToUpper(strings.Trim(splitStep[0], " "))
  124. switch stepInstruction {
  125. case "ONBUILD":
  126. return fmt.Errorf("Source image contains forbidden chained `ONBUILD ONBUILD` trigger: %s", step)
  127. case "MAINTAINER", "FROM":
  128. return fmt.Errorf("Source image contains forbidden %s trigger: %s", stepInstruction, step)
  129. }
  130. if err := b.BuildStep(fmt.Sprintf("onbuild-%d", n), step); err != nil {
  131. return err
  132. }
  133. }
  134. return nil
  135. }
  136. // The ONBUILD command declares a build instruction to be executed in any future build
  137. // using the current image as a base.
  138. func (b *buildFile) CmdOnbuild(trigger string) error {
  139. splitTrigger := strings.Split(trigger, " ")
  140. triggerInstruction := strings.ToUpper(strings.Trim(splitTrigger[0], " "))
  141. switch triggerInstruction {
  142. case "ONBUILD":
  143. return fmt.Errorf("Chaining ONBUILD via `ONBUILD ONBUILD` isn't allowed")
  144. case "MAINTAINER", "FROM":
  145. return fmt.Errorf("%s isn't allowed as an ONBUILD trigger", triggerInstruction)
  146. }
  147. b.config.OnBuild = append(b.config.OnBuild, trigger)
  148. return b.commit("", b.config.Cmd, fmt.Sprintf("ONBUILD %s", trigger))
  149. }
  150. func (b *buildFile) CmdMaintainer(name string) error {
  151. b.maintainer = name
  152. return b.commit("", b.config.Cmd, fmt.Sprintf("MAINTAINER %s", name))
  153. }
  154. // probeCache checks to see if image-caching is enabled (`b.utilizeCache`)
  155. // and if so attempts to look up the current `b.image` and `b.config` pair
  156. // in the current server `b.daemon`. If an image is found, probeCache returns
  157. // `(true, nil)`. If no image is found, it returns `(false, nil)`. If there
  158. // is any error, it returns `(false, err)`.
  159. func (b *buildFile) probeCache() (bool, error) {
  160. if b.utilizeCache {
  161. if cache, err := b.daemon.ImageGetCached(b.image, b.config); err != nil {
  162. return false, err
  163. } else if cache != nil {
  164. fmt.Fprintf(b.outStream, " ---> Using cache\n")
  165. utils.Debugf("[BUILDER] Use cached version")
  166. b.image = cache.ID
  167. return true, nil
  168. } else {
  169. utils.Debugf("[BUILDER] Cache miss")
  170. }
  171. }
  172. return false, nil
  173. }
  174. func (b *buildFile) CmdRun(args string) error {
  175. if b.image == "" {
  176. return fmt.Errorf("Please provide a source image with `from` prior to run")
  177. }
  178. config, _, _, err := runconfig.Parse(append([]string{b.image}, b.buildCmdFromJson(args)...), nil)
  179. if err != nil {
  180. return err
  181. }
  182. cmd := b.config.Cmd
  183. b.config.Cmd = nil
  184. runconfig.Merge(b.config, config)
  185. defer func(cmd []string) { b.config.Cmd = cmd }(cmd)
  186. utils.Debugf("Command to be executed: %v", b.config.Cmd)
  187. hit, err := b.probeCache()
  188. if err != nil {
  189. return err
  190. }
  191. if hit {
  192. return nil
  193. }
  194. c, err := b.create()
  195. if err != nil {
  196. return err
  197. }
  198. // Ensure that we keep the container mounted until the commit
  199. // to avoid unmounting and then mounting directly again
  200. c.Mount()
  201. defer c.Unmount()
  202. err = b.run(c)
  203. if err != nil {
  204. return err
  205. }
  206. if err := b.commit(c.ID, cmd, "run"); err != nil {
  207. return err
  208. }
  209. return nil
  210. }
  211. func (b *buildFile) FindEnvKey(key string) int {
  212. for k, envVar := range b.config.Env {
  213. envParts := strings.SplitN(envVar, "=", 2)
  214. if key == envParts[0] {
  215. return k
  216. }
  217. }
  218. return -1
  219. }
  220. func (b *buildFile) ReplaceEnvMatches(value string) (string, error) {
  221. exp, err := regexp.Compile("(\\\\\\\\+|[^\\\\]|\\b|\\A)\\$({?)([[:alnum:]_]+)(}?)")
  222. if err != nil {
  223. return value, err
  224. }
  225. matches := exp.FindAllString(value, -1)
  226. for _, match := range matches {
  227. match = match[strings.Index(match, "$"):]
  228. matchKey := strings.Trim(match, "${}")
  229. for _, envVar := range b.config.Env {
  230. envParts := strings.SplitN(envVar, "=", 2)
  231. envKey := envParts[0]
  232. envValue := envParts[1]
  233. if envKey == matchKey {
  234. value = strings.Replace(value, match, envValue, -1)
  235. break
  236. }
  237. }
  238. }
  239. return value, nil
  240. }
  241. func (b *buildFile) CmdEnv(args string) error {
  242. tmp := strings.SplitN(args, " ", 2)
  243. if len(tmp) != 2 {
  244. return fmt.Errorf("Invalid ENV format")
  245. }
  246. key := strings.Trim(tmp[0], " \t")
  247. value := strings.Trim(tmp[1], " \t")
  248. envKey := b.FindEnvKey(key)
  249. replacedValue, err := b.ReplaceEnvMatches(value)
  250. if err != nil {
  251. return err
  252. }
  253. replacedVar := fmt.Sprintf("%s=%s", key, replacedValue)
  254. if envKey >= 0 {
  255. b.config.Env[envKey] = replacedVar
  256. } else {
  257. b.config.Env = append(b.config.Env, replacedVar)
  258. }
  259. return b.commit("", b.config.Cmd, fmt.Sprintf("ENV %s", replacedVar))
  260. }
  261. func (b *buildFile) buildCmdFromJson(args string) []string {
  262. var cmd []string
  263. if err := json.Unmarshal([]byte(args), &cmd); err != nil {
  264. utils.Debugf("Error unmarshalling: %s, setting to /bin/sh -c", err)
  265. cmd = []string{"/bin/sh", "-c", args}
  266. }
  267. return cmd
  268. }
  269. func (b *buildFile) CmdCmd(args string) error {
  270. cmd := b.buildCmdFromJson(args)
  271. b.config.Cmd = cmd
  272. if err := b.commit("", b.config.Cmd, fmt.Sprintf("CMD %v", cmd)); err != nil {
  273. return err
  274. }
  275. b.cmdSet = true
  276. return nil
  277. }
  278. func (b *buildFile) CmdEntrypoint(args string) error {
  279. entrypoint := b.buildCmdFromJson(args)
  280. b.config.Entrypoint = entrypoint
  281. // if there is no cmd in current Dockerfile - cleanup cmd
  282. if !b.cmdSet {
  283. b.config.Cmd = nil
  284. }
  285. if err := b.commit("", b.config.Cmd, fmt.Sprintf("ENTRYPOINT %v", entrypoint)); err != nil {
  286. return err
  287. }
  288. return nil
  289. }
  290. func (b *buildFile) CmdExpose(args string) error {
  291. portsTab := strings.Split(args, " ")
  292. if b.config.ExposedPorts == nil {
  293. b.config.ExposedPorts = make(nat.PortSet)
  294. }
  295. ports, _, err := nat.ParsePortSpecs(append(portsTab, b.config.PortSpecs...))
  296. if err != nil {
  297. return err
  298. }
  299. for port := range ports {
  300. if _, exists := b.config.ExposedPorts[port]; !exists {
  301. b.config.ExposedPorts[port] = struct{}{}
  302. }
  303. }
  304. b.config.PortSpecs = nil
  305. return b.commit("", b.config.Cmd, fmt.Sprintf("EXPOSE %v", ports))
  306. }
  307. func (b *buildFile) CmdUser(args string) error {
  308. b.config.User = args
  309. return b.commit("", b.config.Cmd, fmt.Sprintf("USER %v", args))
  310. }
  311. func (b *buildFile) CmdInsert(args string) error {
  312. return fmt.Errorf("INSERT has been deprecated. Please use ADD instead")
  313. }
  314. func (b *buildFile) CmdCopy(args string) error {
  315. return b.runContextCommand(args, false, false, "COPY")
  316. }
  317. func (b *buildFile) CmdWorkdir(workdir string) error {
  318. if workdir[0] == '/' {
  319. b.config.WorkingDir = workdir
  320. } else {
  321. if b.config.WorkingDir == "" {
  322. b.config.WorkingDir = "/"
  323. }
  324. b.config.WorkingDir = filepath.Join(b.config.WorkingDir, workdir)
  325. }
  326. return b.commit("", b.config.Cmd, fmt.Sprintf("WORKDIR %v", workdir))
  327. }
  328. func (b *buildFile) CmdVolume(args string) error {
  329. if args == "" {
  330. return fmt.Errorf("Volume cannot be empty")
  331. }
  332. var volume []string
  333. if err := json.Unmarshal([]byte(args), &volume); err != nil {
  334. volume = []string{args}
  335. }
  336. if b.config.Volumes == nil {
  337. b.config.Volumes = map[string]struct{}{}
  338. }
  339. for _, v := range volume {
  340. b.config.Volumes[v] = struct{}{}
  341. }
  342. if err := b.commit("", b.config.Cmd, fmt.Sprintf("VOLUME %s", args)); err != nil {
  343. return err
  344. }
  345. return nil
  346. }
  347. func (b *buildFile) checkPathForAddition(orig string) error {
  348. origPath := path.Join(b.contextPath, orig)
  349. if p, err := filepath.EvalSymlinks(origPath); err != nil {
  350. if os.IsNotExist(err) {
  351. return fmt.Errorf("%s: no such file or directory", orig)
  352. }
  353. return err
  354. } else {
  355. origPath = p
  356. }
  357. if !strings.HasPrefix(origPath, b.contextPath) {
  358. return fmt.Errorf("Forbidden path outside the build context: %s (%s)", orig, origPath)
  359. }
  360. _, err := os.Stat(origPath)
  361. if err != nil {
  362. if os.IsNotExist(err) {
  363. return fmt.Errorf("%s: no such file or directory", orig)
  364. }
  365. return err
  366. }
  367. return nil
  368. }
  369. func (b *buildFile) addContext(container *daemon.Container, orig, dest string, decompress bool) error {
  370. var (
  371. err error
  372. destExists = true
  373. origPath = path.Join(b.contextPath, orig)
  374. destPath = path.Join(container.RootfsPath(), dest)
  375. )
  376. if destPath != container.RootfsPath() {
  377. destPath, err = symlink.FollowSymlinkInScope(destPath, container.RootfsPath())
  378. if err != nil {
  379. return err
  380. }
  381. }
  382. // Preserve the trailing '/'
  383. if strings.HasSuffix(dest, "/") || dest == "." {
  384. destPath = destPath + "/"
  385. }
  386. destStat, err := os.Stat(destPath)
  387. if err != nil {
  388. if !os.IsNotExist(err) {
  389. return err
  390. }
  391. destExists = false
  392. }
  393. fi, err := os.Stat(origPath)
  394. if err != nil {
  395. if os.IsNotExist(err) {
  396. return fmt.Errorf("%s: no such file or directory", orig)
  397. }
  398. return err
  399. }
  400. if fi.IsDir() {
  401. return copyAsDirectory(origPath, destPath, destExists)
  402. }
  403. // If we are adding a remote file (or we've been told not to decompress), do not try to untar it
  404. if decompress {
  405. // First try to unpack the source as an archive
  406. // to support the untar feature we need to clean up the path a little bit
  407. // because tar is very forgiving. First we need to strip off the archive's
  408. // filename from the path but this is only added if it does not end in / .
  409. tarDest := destPath
  410. if strings.HasSuffix(tarDest, "/") {
  411. tarDest = filepath.Dir(destPath)
  412. }
  413. // try to successfully untar the orig
  414. if err := archive.UntarPath(origPath, tarDest); err == nil {
  415. return nil
  416. } else if err != io.EOF {
  417. utils.Debugf("Couldn't untar %s to %s: %s", origPath, tarDest, err)
  418. }
  419. }
  420. if err := os.MkdirAll(path.Dir(destPath), 0755); err != nil {
  421. return err
  422. }
  423. if err := archive.CopyWithTar(origPath, destPath); err != nil {
  424. return err
  425. }
  426. resPath := destPath
  427. if destExists && destStat.IsDir() {
  428. resPath = path.Join(destPath, path.Base(origPath))
  429. }
  430. return fixPermissions(resPath, 0, 0)
  431. }
  432. func (b *buildFile) runContextCommand(args string, allowRemote bool, allowDecompression bool, cmdName string) error {
  433. if b.context == nil {
  434. return fmt.Errorf("No context given. Impossible to use %s", cmdName)
  435. }
  436. tmp := strings.SplitN(args, " ", 2)
  437. if len(tmp) != 2 {
  438. return fmt.Errorf("Invalid %s format", cmdName)
  439. }
  440. orig, err := b.ReplaceEnvMatches(strings.Trim(tmp[0], " \t"))
  441. if err != nil {
  442. return err
  443. }
  444. dest, err := b.ReplaceEnvMatches(strings.Trim(tmp[1], " \t"))
  445. if err != nil {
  446. return err
  447. }
  448. cmd := b.config.Cmd
  449. b.config.Cmd = []string{"/bin/sh", "-c", fmt.Sprintf("#(nop) %s %s in %s", cmdName, orig, dest)}
  450. defer func(cmd []string) { b.config.Cmd = cmd }(cmd)
  451. b.config.Image = b.image
  452. var (
  453. origPath = orig
  454. destPath = dest
  455. remoteHash string
  456. isRemote bool
  457. decompress = true
  458. )
  459. isRemote = utils.IsURL(orig)
  460. if isRemote && !allowRemote {
  461. return fmt.Errorf("Source can't be an URL for %s", cmdName)
  462. } else if utils.IsURL(orig) {
  463. // Initiate the download
  464. resp, err := utils.Download(orig)
  465. if err != nil {
  466. return err
  467. }
  468. // Create a tmp dir
  469. tmpDirName, err := ioutil.TempDir(b.contextPath, "docker-remote")
  470. if err != nil {
  471. return err
  472. }
  473. // Create a tmp file within our tmp dir
  474. tmpFileName := path.Join(tmpDirName, "tmp")
  475. tmpFile, err := os.OpenFile(tmpFileName, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0600)
  476. if err != nil {
  477. return err
  478. }
  479. defer os.RemoveAll(tmpDirName)
  480. // Download and dump result to tmp file
  481. if _, err := io.Copy(tmpFile, resp.Body); err != nil {
  482. tmpFile.Close()
  483. return err
  484. }
  485. tmpFile.Close()
  486. // Remove the mtime of the newly created tmp file
  487. if err := system.UtimesNano(tmpFileName, make([]syscall.Timespec, 2)); err != nil {
  488. return err
  489. }
  490. origPath = path.Join(filepath.Base(tmpDirName), filepath.Base(tmpFileName))
  491. // Process the checksum
  492. r, err := archive.Tar(tmpFileName, archive.Uncompressed)
  493. if err != nil {
  494. return err
  495. }
  496. tarSum := &tarsum.TarSum{Reader: r, DisableCompression: true}
  497. if _, err := io.Copy(ioutil.Discard, tarSum); err != nil {
  498. return err
  499. }
  500. remoteHash = tarSum.Sum(nil)
  501. r.Close()
  502. // If the destination is a directory, figure out the filename.
  503. if strings.HasSuffix(dest, "/") {
  504. u, err := url.Parse(orig)
  505. if err != nil {
  506. return err
  507. }
  508. path := u.Path
  509. if strings.HasSuffix(path, "/") {
  510. path = path[:len(path)-1]
  511. }
  512. parts := strings.Split(path, "/")
  513. filename := parts[len(parts)-1]
  514. if filename == "" {
  515. return fmt.Errorf("cannot determine filename from url: %s", u)
  516. }
  517. destPath = dest + filename
  518. }
  519. }
  520. if err := b.checkPathForAddition(origPath); err != nil {
  521. return err
  522. }
  523. // Hash path and check the cache
  524. if b.utilizeCache {
  525. var (
  526. hash string
  527. sums = b.context.GetSums()
  528. )
  529. if remoteHash != "" {
  530. hash = remoteHash
  531. } else if fi, err := os.Stat(path.Join(b.contextPath, origPath)); err != nil {
  532. return err
  533. } else if fi.IsDir() {
  534. var subfiles []string
  535. for file, sum := range sums {
  536. absFile := path.Join(b.contextPath, file)
  537. absOrigPath := path.Join(b.contextPath, origPath)
  538. if strings.HasPrefix(absFile, absOrigPath) {
  539. subfiles = append(subfiles, sum)
  540. }
  541. }
  542. sort.Strings(subfiles)
  543. hasher := sha256.New()
  544. hasher.Write([]byte(strings.Join(subfiles, ",")))
  545. hash = "dir:" + hex.EncodeToString(hasher.Sum(nil))
  546. } else {
  547. if origPath[0] == '/' && len(origPath) > 1 {
  548. origPath = origPath[1:]
  549. }
  550. origPath = strings.TrimPrefix(origPath, "./")
  551. if h, ok := sums[origPath]; ok {
  552. hash = "file:" + h
  553. }
  554. }
  555. b.config.Cmd = []string{"/bin/sh", "-c", fmt.Sprintf("#(nop) %s %s in %s", cmdName, hash, dest)}
  556. hit, err := b.probeCache()
  557. if err != nil {
  558. return err
  559. }
  560. // If we do not have a hash, never use the cache
  561. if hit && hash != "" {
  562. return nil
  563. }
  564. }
  565. // Create the container
  566. container, _, err := b.daemon.Create(b.config, "")
  567. if err != nil {
  568. return err
  569. }
  570. b.tmpContainers[container.ID] = struct{}{}
  571. if err := container.Mount(); err != nil {
  572. return err
  573. }
  574. defer container.Unmount()
  575. if !allowDecompression || isRemote {
  576. decompress = false
  577. }
  578. if err := b.addContext(container, origPath, destPath, decompress); err != nil {
  579. return err
  580. }
  581. if err := b.commit(container.ID, cmd, fmt.Sprintf("%s %s in %s", cmdName, orig, dest)); err != nil {
  582. return err
  583. }
  584. return nil
  585. }
  586. func (b *buildFile) CmdAdd(args string) error {
  587. return b.runContextCommand(args, true, true, "ADD")
  588. }
  589. func (b *buildFile) create() (*daemon.Container, error) {
  590. if b.image == "" {
  591. return nil, fmt.Errorf("Please provide a source image with `from` prior to run")
  592. }
  593. b.config.Image = b.image
  594. // Create the container
  595. c, _, err := b.daemon.Create(b.config, "")
  596. if err != nil {
  597. return nil, err
  598. }
  599. b.tmpContainers[c.ID] = struct{}{}
  600. fmt.Fprintf(b.outStream, " ---> Running in %s\n", utils.TruncateID(c.ID))
  601. // override the entry point that may have been picked up from the base image
  602. c.Path = b.config.Cmd[0]
  603. c.Args = b.config.Cmd[1:]
  604. return c, nil
  605. }
  606. func (b *buildFile) run(c *daemon.Container) error {
  607. var errCh chan error
  608. if b.verbose {
  609. errCh = utils.Go(func() error {
  610. // FIXME: call the 'attach' job so that daemon.Attach can be made private
  611. //
  612. // FIXME (LK4D4): Also, maybe makes sense to call "logs" job, it is like attach
  613. // but without hijacking for stdin. Also, with attach there can be race
  614. // condition because of some output already was printed before it.
  615. return <-b.daemon.Attach(c, nil, nil, b.outStream, b.errStream)
  616. })
  617. }
  618. //start the container
  619. if err := c.Start(); err != nil {
  620. return err
  621. }
  622. if errCh != nil {
  623. if err := <-errCh; err != nil {
  624. return err
  625. }
  626. }
  627. // Wait for it to finish
  628. if ret, _ := c.State.WaitStop(-1 * time.Second); ret != 0 {
  629. err := &utils.JSONError{
  630. Message: fmt.Sprintf("The command %v returned a non-zero code: %d", b.config.Cmd, ret),
  631. Code: ret,
  632. }
  633. return err
  634. }
  635. return nil
  636. }
  637. // Commit the container <id> with the autorun command <autoCmd>
  638. func (b *buildFile) commit(id string, autoCmd []string, comment string) error {
  639. if b.image == "" {
  640. return fmt.Errorf("Please provide a source image with `from` prior to commit")
  641. }
  642. b.config.Image = b.image
  643. if id == "" {
  644. cmd := b.config.Cmd
  645. b.config.Cmd = []string{"/bin/sh", "-c", "#(nop) " + comment}
  646. defer func(cmd []string) { b.config.Cmd = cmd }(cmd)
  647. hit, err := b.probeCache()
  648. if err != nil {
  649. return err
  650. }
  651. if hit {
  652. return nil
  653. }
  654. container, warnings, err := b.daemon.Create(b.config, "")
  655. if err != nil {
  656. return err
  657. }
  658. for _, warning := range warnings {
  659. fmt.Fprintf(b.outStream, " ---> [Warning] %s\n", warning)
  660. }
  661. b.tmpContainers[container.ID] = struct{}{}
  662. fmt.Fprintf(b.outStream, " ---> Running in %s\n", utils.TruncateID(container.ID))
  663. id = container.ID
  664. if err := container.Mount(); err != nil {
  665. return err
  666. }
  667. defer container.Unmount()
  668. }
  669. container := b.daemon.Get(id)
  670. if container == nil {
  671. return fmt.Errorf("An error occured while creating the container")
  672. }
  673. // Note: Actually copy the struct
  674. autoConfig := *b.config
  675. autoConfig.Cmd = autoCmd
  676. // Commit the container
  677. image, err := b.daemon.Commit(container, "", "", "", b.maintainer, true, &autoConfig)
  678. if err != nil {
  679. return err
  680. }
  681. b.tmpImages[image.ID] = struct{}{}
  682. b.image = image.ID
  683. return nil
  684. }
  685. // Long lines can be split with a backslash
  686. var lineContinuation = regexp.MustCompile(`\\\s*\n`)
  687. func (b *buildFile) Build(context io.Reader) (string, error) {
  688. tmpdirPath, err := ioutil.TempDir("", "docker-build")
  689. if err != nil {
  690. return "", err
  691. }
  692. decompressedStream, err := archive.DecompressStream(context)
  693. if err != nil {
  694. return "", err
  695. }
  696. b.context = &tarsum.TarSum{Reader: decompressedStream, DisableCompression: true}
  697. if err := archive.Untar(b.context, tmpdirPath, nil); err != nil {
  698. return "", err
  699. }
  700. defer os.RemoveAll(tmpdirPath)
  701. b.contextPath = tmpdirPath
  702. filename := path.Join(tmpdirPath, "Dockerfile")
  703. if _, err := os.Stat(filename); os.IsNotExist(err) {
  704. return "", fmt.Errorf("Can't build a directory with no Dockerfile")
  705. }
  706. fileBytes, err := ioutil.ReadFile(filename)
  707. if err != nil {
  708. return "", err
  709. }
  710. if len(fileBytes) == 0 {
  711. return "", ErrDockerfileEmpty
  712. }
  713. var (
  714. dockerfile = lineContinuation.ReplaceAllString(stripComments(fileBytes), "")
  715. stepN = 0
  716. )
  717. for _, line := range strings.Split(dockerfile, "\n") {
  718. line = strings.Trim(strings.Replace(line, "\t", " ", -1), " \t\r\n")
  719. if len(line) == 0 {
  720. continue
  721. }
  722. if err := b.BuildStep(fmt.Sprintf("%d", stepN), line); err != nil {
  723. if b.forceRm {
  724. b.clearTmp(b.tmpContainers)
  725. }
  726. return "", err
  727. } else if b.rm {
  728. b.clearTmp(b.tmpContainers)
  729. }
  730. stepN += 1
  731. }
  732. if b.image != "" {
  733. fmt.Fprintf(b.outStream, "Successfully built %s\n", utils.TruncateID(b.image))
  734. return b.image, nil
  735. }
  736. return "", fmt.Errorf("No image was generated. This may be because the Dockerfile does not, like, do anything.\n")
  737. }
  738. // BuildStep parses a single build step from `instruction` and executes it in the current context.
  739. func (b *buildFile) BuildStep(name, expression string) error {
  740. fmt.Fprintf(b.outStream, "Step %s : %s\n", name, expression)
  741. tmp := strings.SplitN(expression, " ", 2)
  742. if len(tmp) != 2 {
  743. return fmt.Errorf("Invalid Dockerfile format")
  744. }
  745. instruction := strings.ToLower(strings.Trim(tmp[0], " "))
  746. arguments := strings.Trim(tmp[1], " ")
  747. method, exists := reflect.TypeOf(b).MethodByName("Cmd" + strings.ToUpper(instruction[:1]) + strings.ToLower(instruction[1:]))
  748. if !exists {
  749. fmt.Fprintf(b.errStream, "# Skipping unknown instruction %s\n", strings.ToUpper(instruction))
  750. return nil
  751. }
  752. ret := method.Func.Call([]reflect.Value{reflect.ValueOf(b), reflect.ValueOf(arguments)})[0].Interface()
  753. if ret != nil {
  754. return ret.(error)
  755. }
  756. fmt.Fprintf(b.outStream, " ---> %s\n", utils.TruncateID(b.image))
  757. return nil
  758. }
  759. func stripComments(raw []byte) string {
  760. var (
  761. out []string
  762. lines = strings.Split(string(raw), "\n")
  763. )
  764. for _, l := range lines {
  765. if len(l) == 0 || l[0] == '#' {
  766. continue
  767. }
  768. out = append(out, l)
  769. }
  770. return strings.Join(out, "\n")
  771. }
  772. func copyAsDirectory(source, destination string, destinationExists bool) error {
  773. if err := archive.CopyWithTar(source, destination); err != nil {
  774. return err
  775. }
  776. if destinationExists {
  777. files, err := ioutil.ReadDir(source)
  778. if err != nil {
  779. return err
  780. }
  781. for _, file := range files {
  782. if err := fixPermissions(filepath.Join(destination, file.Name()), 0, 0); err != nil {
  783. return err
  784. }
  785. }
  786. return nil
  787. }
  788. return fixPermissions(destination, 0, 0)
  789. }
  790. func fixPermissions(destination string, uid, gid int) error {
  791. return filepath.Walk(destination, func(path string, info os.FileInfo, err error) error {
  792. if err := os.Lchown(path, uid, gid); err != nil && !os.IsNotExist(err) {
  793. return err
  794. }
  795. return nil
  796. })
  797. }
  798. func NewBuildFile(d *daemon.Daemon, eng *engine.Engine, outStream, errStream io.Writer, verbose, utilizeCache, rm bool, forceRm bool, outOld io.Writer, sf *utils.StreamFormatter, auth *registry.AuthConfig, authConfigFile *registry.ConfigFile) BuildFile {
  799. return &buildFile{
  800. daemon: d,
  801. eng: eng,
  802. config: &runconfig.Config{},
  803. outStream: outStream,
  804. errStream: errStream,
  805. tmpContainers: make(map[string]struct{}),
  806. tmpImages: make(map[string]struct{}),
  807. verbose: verbose,
  808. utilizeCache: utilizeCache,
  809. rm: rm,
  810. forceRm: forceRm,
  811. sf: sf,
  812. authConfig: auth,
  813. configFile: authConfigFile,
  814. outOld: outOld,
  815. }
  816. }