builder.go 23 KB

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