builder.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927
  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 set 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. // set Cmd manually, this is special case only for Dockerfiles
  184. b.config.Cmd = config.Cmd
  185. runconfig.Merge(b.config, config)
  186. defer func(cmd []string) { b.config.Cmd = cmd }(cmd)
  187. utils.Debugf("Command to be executed: %v", b.config.Cmd)
  188. hit, err := b.probeCache()
  189. if err != nil {
  190. return err
  191. }
  192. if hit {
  193. return nil
  194. }
  195. c, err := b.create()
  196. if err != nil {
  197. return err
  198. }
  199. // Ensure that we keep the container mounted until the commit
  200. // to avoid unmounting and then mounting directly again
  201. c.Mount()
  202. defer c.Unmount()
  203. err = b.run(c)
  204. if err != nil {
  205. return err
  206. }
  207. if err := b.commit(c.ID, cmd, "run"); err != nil {
  208. return err
  209. }
  210. return nil
  211. }
  212. func (b *buildFile) FindEnvKey(key string) int {
  213. for k, envVar := range b.config.Env {
  214. envParts := strings.SplitN(envVar, "=", 2)
  215. if key == envParts[0] {
  216. return k
  217. }
  218. }
  219. return -1
  220. }
  221. func (b *buildFile) ReplaceEnvMatches(value string) (string, error) {
  222. exp, err := regexp.Compile("(\\\\\\\\+|[^\\\\]|\\b|\\A)\\$({?)([[:alnum:]_]+)(}?)")
  223. if err != nil {
  224. return value, err
  225. }
  226. matches := exp.FindAllString(value, -1)
  227. for _, match := range matches {
  228. match = match[strings.Index(match, "$"):]
  229. matchKey := strings.Trim(match, "${}")
  230. for _, envVar := range b.config.Env {
  231. envParts := strings.SplitN(envVar, "=", 2)
  232. envKey := envParts[0]
  233. envValue := envParts[1]
  234. if envKey == matchKey {
  235. value = strings.Replace(value, match, envValue, -1)
  236. break
  237. }
  238. }
  239. }
  240. return value, nil
  241. }
  242. func (b *buildFile) CmdEnv(args string) error {
  243. tmp := strings.SplitN(args, " ", 2)
  244. if len(tmp) != 2 {
  245. return fmt.Errorf("Invalid ENV format")
  246. }
  247. key := strings.Trim(tmp[0], " \t")
  248. value := strings.Trim(tmp[1], " \t")
  249. envKey := b.FindEnvKey(key)
  250. replacedValue, err := b.ReplaceEnvMatches(value)
  251. if err != nil {
  252. return err
  253. }
  254. replacedVar := fmt.Sprintf("%s=%s", key, replacedValue)
  255. if envKey >= 0 {
  256. b.config.Env[envKey] = replacedVar
  257. } else {
  258. b.config.Env = append(b.config.Env, replacedVar)
  259. }
  260. return b.commit("", b.config.Cmd, fmt.Sprintf("ENV %s", replacedVar))
  261. }
  262. func (b *buildFile) buildCmdFromJson(args string) []string {
  263. var cmd []string
  264. if err := json.Unmarshal([]byte(args), &cmd); err != nil {
  265. utils.Debugf("Error unmarshalling: %s, setting to /bin/sh -c", err)
  266. cmd = []string{"/bin/sh", "-c", args}
  267. }
  268. return cmd
  269. }
  270. func (b *buildFile) CmdCmd(args string) error {
  271. cmd := b.buildCmdFromJson(args)
  272. b.config.Cmd = cmd
  273. if err := b.commit("", b.config.Cmd, fmt.Sprintf("CMD %v", cmd)); err != nil {
  274. return err
  275. }
  276. b.cmdSet = true
  277. return nil
  278. }
  279. func (b *buildFile) CmdEntrypoint(args string) error {
  280. entrypoint := b.buildCmdFromJson(args)
  281. b.config.Entrypoint = entrypoint
  282. // if there is no cmd in current Dockerfile - cleanup cmd
  283. if !b.cmdSet {
  284. b.config.Cmd = nil
  285. }
  286. if err := b.commit("", b.config.Cmd, fmt.Sprintf("ENTRYPOINT %v", entrypoint)); err != nil {
  287. return err
  288. }
  289. return nil
  290. }
  291. func (b *buildFile) CmdExpose(args string) error {
  292. portsTab := strings.Split(args, " ")
  293. if b.config.ExposedPorts == nil {
  294. b.config.ExposedPorts = make(nat.PortSet)
  295. }
  296. ports, _, err := nat.ParsePortSpecs(append(portsTab, b.config.PortSpecs...))
  297. if err != nil {
  298. return err
  299. }
  300. for port := range ports {
  301. if _, exists := b.config.ExposedPorts[port]; !exists {
  302. b.config.ExposedPorts[port] = struct{}{}
  303. }
  304. }
  305. b.config.PortSpecs = nil
  306. return b.commit("", b.config.Cmd, fmt.Sprintf("EXPOSE %v", ports))
  307. }
  308. func (b *buildFile) CmdUser(args string) error {
  309. b.config.User = args
  310. return b.commit("", b.config.Cmd, fmt.Sprintf("USER %v", args))
  311. }
  312. func (b *buildFile) CmdInsert(args string) error {
  313. return fmt.Errorf("INSERT has been deprecated. Please use ADD instead")
  314. }
  315. func (b *buildFile) CmdCopy(args string) error {
  316. return b.runContextCommand(args, false, false, "COPY")
  317. }
  318. func (b *buildFile) CmdWorkdir(workdir string) error {
  319. if workdir[0] == '/' {
  320. b.config.WorkingDir = workdir
  321. } else {
  322. if b.config.WorkingDir == "" {
  323. b.config.WorkingDir = "/"
  324. }
  325. b.config.WorkingDir = filepath.Join(b.config.WorkingDir, workdir)
  326. }
  327. return b.commit("", b.config.Cmd, fmt.Sprintf("WORKDIR %v", workdir))
  328. }
  329. func (b *buildFile) CmdVolume(args string) error {
  330. if args == "" {
  331. return fmt.Errorf("Volume cannot be empty")
  332. }
  333. var volume []string
  334. if err := json.Unmarshal([]byte(args), &volume); err != nil {
  335. volume = []string{args}
  336. }
  337. if b.config.Volumes == nil {
  338. b.config.Volumes = map[string]struct{}{}
  339. }
  340. for _, v := range volume {
  341. b.config.Volumes[v] = struct{}{}
  342. }
  343. if err := b.commit("", b.config.Cmd, fmt.Sprintf("VOLUME %s", args)); err != nil {
  344. return err
  345. }
  346. return nil
  347. }
  348. func (b *buildFile) checkPathForAddition(orig string) error {
  349. origPath := path.Join(b.contextPath, orig)
  350. if p, err := filepath.EvalSymlinks(origPath); err != nil {
  351. if os.IsNotExist(err) {
  352. return fmt.Errorf("%s: no such file or directory", orig)
  353. }
  354. return err
  355. } else {
  356. origPath = p
  357. }
  358. if !strings.HasPrefix(origPath, b.contextPath) {
  359. return fmt.Errorf("Forbidden path outside the build context: %s (%s)", orig, origPath)
  360. }
  361. _, err := os.Stat(origPath)
  362. if err != nil {
  363. if os.IsNotExist(err) {
  364. return fmt.Errorf("%s: no such file or directory", orig)
  365. }
  366. return err
  367. }
  368. return nil
  369. }
  370. func (b *buildFile) addContext(container *daemon.Container, orig, dest string, decompress bool) error {
  371. var (
  372. err error
  373. destExists = true
  374. origPath = path.Join(b.contextPath, orig)
  375. destPath = path.Join(container.RootfsPath(), dest)
  376. )
  377. if destPath != container.RootfsPath() {
  378. destPath, err = symlink.FollowSymlinkInScope(destPath, container.RootfsPath())
  379. if err != nil {
  380. return err
  381. }
  382. }
  383. // Preserve the trailing '/'
  384. if strings.HasSuffix(dest, "/") || dest == "." {
  385. destPath = destPath + "/"
  386. }
  387. destStat, err := os.Stat(destPath)
  388. if err != nil {
  389. if !os.IsNotExist(err) {
  390. return err
  391. }
  392. destExists = false
  393. }
  394. fi, err := os.Stat(origPath)
  395. if err != nil {
  396. if os.IsNotExist(err) {
  397. return fmt.Errorf("%s: no such file or directory", orig)
  398. }
  399. return err
  400. }
  401. if fi.IsDir() {
  402. return copyAsDirectory(origPath, destPath, destExists)
  403. }
  404. // If we are adding a remote file (or we've been told not to decompress), do not try to untar it
  405. if decompress {
  406. // First try to unpack the source as an archive
  407. // to support the untar feature we need to clean up the path a little bit
  408. // because tar is very forgiving. First we need to strip off the archive's
  409. // filename from the path but this is only added if it does not end in / .
  410. tarDest := destPath
  411. if strings.HasSuffix(tarDest, "/") {
  412. tarDest = filepath.Dir(destPath)
  413. }
  414. // try to successfully untar the orig
  415. if err := archive.UntarPath(origPath, tarDest); err == nil {
  416. return nil
  417. } else if err != io.EOF {
  418. utils.Debugf("Couldn't untar %s to %s: %s", origPath, tarDest, err)
  419. }
  420. }
  421. if err := os.MkdirAll(path.Dir(destPath), 0755); err != nil {
  422. return err
  423. }
  424. if err := archive.CopyWithTar(origPath, destPath); err != nil {
  425. return err
  426. }
  427. resPath := destPath
  428. if destExists && destStat.IsDir() {
  429. resPath = path.Join(destPath, path.Base(origPath))
  430. }
  431. return fixPermissions(resPath, 0, 0)
  432. }
  433. func (b *buildFile) runContextCommand(args string, allowRemote bool, allowDecompression bool, cmdName string) error {
  434. if b.context == nil {
  435. return fmt.Errorf("No context given. Impossible to use %s", cmdName)
  436. }
  437. tmp := strings.SplitN(args, " ", 2)
  438. if len(tmp) != 2 {
  439. return fmt.Errorf("Invalid %s format", cmdName)
  440. }
  441. orig, err := b.ReplaceEnvMatches(strings.Trim(tmp[0], " \t"))
  442. if err != nil {
  443. return err
  444. }
  445. dest, err := b.ReplaceEnvMatches(strings.Trim(tmp[1], " \t"))
  446. if err != nil {
  447. return err
  448. }
  449. cmd := b.config.Cmd
  450. b.config.Cmd = []string{"/bin/sh", "-c", fmt.Sprintf("#(nop) %s %s in %s", cmdName, orig, dest)}
  451. defer func(cmd []string) { b.config.Cmd = cmd }(cmd)
  452. b.config.Image = b.image
  453. var (
  454. origPath = orig
  455. destPath = dest
  456. remoteHash string
  457. isRemote bool
  458. decompress = true
  459. )
  460. isRemote = utils.IsURL(orig)
  461. if isRemote && !allowRemote {
  462. return fmt.Errorf("Source can't be an URL for %s", cmdName)
  463. } else if utils.IsURL(orig) {
  464. // Initiate the download
  465. resp, err := utils.Download(orig)
  466. if err != nil {
  467. return err
  468. }
  469. // Create a tmp dir
  470. tmpDirName, err := ioutil.TempDir(b.contextPath, "docker-remote")
  471. if err != nil {
  472. return err
  473. }
  474. // Create a tmp file within our tmp dir
  475. tmpFileName := path.Join(tmpDirName, "tmp")
  476. tmpFile, err := os.OpenFile(tmpFileName, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0600)
  477. if err != nil {
  478. return err
  479. }
  480. defer os.RemoveAll(tmpDirName)
  481. // Download and dump result to tmp file
  482. if _, err := io.Copy(tmpFile, resp.Body); err != nil {
  483. tmpFile.Close()
  484. return err
  485. }
  486. tmpFile.Close()
  487. // Remove the mtime of the newly created tmp file
  488. if err := system.UtimesNano(tmpFileName, make([]syscall.Timespec, 2)); err != nil {
  489. return err
  490. }
  491. origPath = path.Join(filepath.Base(tmpDirName), filepath.Base(tmpFileName))
  492. // Process the checksum
  493. r, err := archive.Tar(tmpFileName, archive.Uncompressed)
  494. if err != nil {
  495. return err
  496. }
  497. tarSum := &tarsum.TarSum{Reader: r, DisableCompression: true}
  498. if _, err := io.Copy(ioutil.Discard, tarSum); err != nil {
  499. return err
  500. }
  501. remoteHash = tarSum.Sum(nil)
  502. r.Close()
  503. // If the destination is a directory, figure out the filename.
  504. if strings.HasSuffix(dest, "/") {
  505. u, err := url.Parse(orig)
  506. if err != nil {
  507. return err
  508. }
  509. path := u.Path
  510. if strings.HasSuffix(path, "/") {
  511. path = path[:len(path)-1]
  512. }
  513. parts := strings.Split(path, "/")
  514. filename := parts[len(parts)-1]
  515. if filename == "" {
  516. return fmt.Errorf("cannot determine filename from url: %s", u)
  517. }
  518. destPath = dest + filename
  519. }
  520. }
  521. if err := b.checkPathForAddition(origPath); err != nil {
  522. return err
  523. }
  524. // Hash path and check the cache
  525. if b.utilizeCache {
  526. var (
  527. hash string
  528. sums = b.context.GetSums()
  529. )
  530. if remoteHash != "" {
  531. hash = remoteHash
  532. } else if fi, err := os.Stat(path.Join(b.contextPath, origPath)); err != nil {
  533. return err
  534. } else if fi.IsDir() {
  535. var subfiles []string
  536. for file, sum := range sums {
  537. absFile := path.Join(b.contextPath, file)
  538. absOrigPath := path.Join(b.contextPath, origPath)
  539. if strings.HasPrefix(absFile, absOrigPath) {
  540. subfiles = append(subfiles, sum)
  541. }
  542. }
  543. sort.Strings(subfiles)
  544. hasher := sha256.New()
  545. hasher.Write([]byte(strings.Join(subfiles, ",")))
  546. hash = "dir:" + hex.EncodeToString(hasher.Sum(nil))
  547. } else {
  548. if origPath[0] == '/' && len(origPath) > 1 {
  549. origPath = origPath[1:]
  550. }
  551. origPath = strings.TrimPrefix(origPath, "./")
  552. if h, ok := sums[origPath]; ok {
  553. hash = "file:" + h
  554. }
  555. }
  556. b.config.Cmd = []string{"/bin/sh", "-c", fmt.Sprintf("#(nop) %s %s in %s", cmdName, hash, dest)}
  557. hit, err := b.probeCache()
  558. if err != nil {
  559. return err
  560. }
  561. // If we do not have a hash, never use the cache
  562. if hit && hash != "" {
  563. return nil
  564. }
  565. }
  566. // Create the container
  567. container, _, err := b.daemon.Create(b.config, "")
  568. if err != nil {
  569. return err
  570. }
  571. b.tmpContainers[container.ID] = struct{}{}
  572. if err := container.Mount(); err != nil {
  573. return err
  574. }
  575. defer container.Unmount()
  576. if !allowDecompression || isRemote {
  577. decompress = false
  578. }
  579. if err := b.addContext(container, origPath, destPath, decompress); err != nil {
  580. return err
  581. }
  582. if err := b.commit(container.ID, cmd, fmt.Sprintf("%s %s in %s", cmdName, orig, dest)); err != nil {
  583. return err
  584. }
  585. return nil
  586. }
  587. func (b *buildFile) CmdAdd(args string) error {
  588. return b.runContextCommand(args, true, true, "ADD")
  589. }
  590. func (b *buildFile) create() (*daemon.Container, error) {
  591. if b.image == "" {
  592. return nil, fmt.Errorf("Please provide a source image with `from` prior to run")
  593. }
  594. b.config.Image = b.image
  595. // Create the container
  596. c, _, err := b.daemon.Create(b.config, "")
  597. if err != nil {
  598. return nil, err
  599. }
  600. b.tmpContainers[c.ID] = struct{}{}
  601. fmt.Fprintf(b.outStream, " ---> Running in %s\n", utils.TruncateID(c.ID))
  602. // override the entry point that may have been picked up from the base image
  603. c.Path = b.config.Cmd[0]
  604. c.Args = b.config.Cmd[1:]
  605. return c, nil
  606. }
  607. func (b *buildFile) run(c *daemon.Container) error {
  608. var errCh chan error
  609. if b.verbose {
  610. errCh = utils.Go(func() error {
  611. // FIXME: call the 'attach' job so that daemon.Attach can be made private
  612. //
  613. // FIXME (LK4D4): Also, maybe makes sense to call "logs" job, it is like attach
  614. // but without hijacking for stdin. Also, with attach there can be race
  615. // condition because of some output already was printed before it.
  616. return <-b.daemon.Attach(c, nil, nil, b.outStream, b.errStream)
  617. })
  618. }
  619. //start the container
  620. if err := c.Start(); err != nil {
  621. return err
  622. }
  623. if errCh != nil {
  624. if err := <-errCh; err != nil {
  625. return err
  626. }
  627. }
  628. // Wait for it to finish
  629. if ret, _ := c.State.WaitStop(-1 * time.Second); ret != 0 {
  630. err := &utils.JSONError{
  631. Message: fmt.Sprintf("The command %v returned a non-zero code: %d", b.config.Cmd, ret),
  632. Code: ret,
  633. }
  634. return err
  635. }
  636. return nil
  637. }
  638. // Commit the container <id> with the autorun command <autoCmd>
  639. func (b *buildFile) commit(id string, autoCmd []string, comment string) error {
  640. if b.image == "" {
  641. return fmt.Errorf("Please provide a source image with `from` prior to commit")
  642. }
  643. b.config.Image = b.image
  644. if id == "" {
  645. cmd := b.config.Cmd
  646. b.config.Cmd = []string{"/bin/sh", "-c", "#(nop) " + comment}
  647. defer func(cmd []string) { b.config.Cmd = cmd }(cmd)
  648. hit, err := b.probeCache()
  649. if err != nil {
  650. return err
  651. }
  652. if hit {
  653. return nil
  654. }
  655. container, warnings, err := b.daemon.Create(b.config, "")
  656. if err != nil {
  657. return err
  658. }
  659. for _, warning := range warnings {
  660. fmt.Fprintf(b.outStream, " ---> [Warning] %s\n", warning)
  661. }
  662. b.tmpContainers[container.ID] = struct{}{}
  663. fmt.Fprintf(b.outStream, " ---> Running in %s\n", utils.TruncateID(container.ID))
  664. id = container.ID
  665. if err := container.Mount(); err != nil {
  666. return err
  667. }
  668. defer container.Unmount()
  669. }
  670. container := b.daemon.Get(id)
  671. if container == nil {
  672. return fmt.Errorf("An error occured while creating the container")
  673. }
  674. // Note: Actually copy the struct
  675. autoConfig := *b.config
  676. autoConfig.Cmd = autoCmd
  677. // Commit the container
  678. image, err := b.daemon.Commit(container, "", "", "", b.maintainer, true, &autoConfig)
  679. if err != nil {
  680. return err
  681. }
  682. b.tmpImages[image.ID] = struct{}{}
  683. b.image = image.ID
  684. return nil
  685. }
  686. // Long lines can be split with a backslash
  687. var lineContinuation = regexp.MustCompile(`\\\s*\n`)
  688. func (b *buildFile) Build(context io.Reader) (string, error) {
  689. tmpdirPath, err := ioutil.TempDir("", "docker-build")
  690. if err != nil {
  691. return "", err
  692. }
  693. decompressedStream, err := archive.DecompressStream(context)
  694. if err != nil {
  695. return "", err
  696. }
  697. b.context = &tarsum.TarSum{Reader: decompressedStream, DisableCompression: true}
  698. if err := archive.Untar(b.context, tmpdirPath, nil); err != nil {
  699. return "", err
  700. }
  701. defer os.RemoveAll(tmpdirPath)
  702. b.contextPath = tmpdirPath
  703. filename := path.Join(tmpdirPath, "Dockerfile")
  704. if _, err := os.Stat(filename); os.IsNotExist(err) {
  705. return "", fmt.Errorf("Can't build a directory with no Dockerfile")
  706. }
  707. fileBytes, err := ioutil.ReadFile(filename)
  708. if err != nil {
  709. return "", err
  710. }
  711. if len(fileBytes) == 0 {
  712. return "", ErrDockerfileEmpty
  713. }
  714. var (
  715. dockerfile = lineContinuation.ReplaceAllString(stripComments(fileBytes), "")
  716. stepN = 0
  717. )
  718. for _, line := range strings.Split(dockerfile, "\n") {
  719. line = strings.Trim(strings.Replace(line, "\t", " ", -1), " \t\r\n")
  720. if len(line) == 0 {
  721. continue
  722. }
  723. if err := b.BuildStep(fmt.Sprintf("%d", stepN), line); err != nil {
  724. if b.forceRm {
  725. b.clearTmp(b.tmpContainers)
  726. }
  727. return "", err
  728. } else if b.rm {
  729. b.clearTmp(b.tmpContainers)
  730. }
  731. stepN += 1
  732. }
  733. if b.image != "" {
  734. fmt.Fprintf(b.outStream, "Successfully built %s\n", utils.TruncateID(b.image))
  735. return b.image, nil
  736. }
  737. return "", fmt.Errorf("No image was generated. This may be because the Dockerfile does not, like, do anything.\n")
  738. }
  739. // BuildStep parses a single build step from `instruction` and executes it in the current context.
  740. func (b *buildFile) BuildStep(name, expression string) error {
  741. fmt.Fprintf(b.outStream, "Step %s : %s\n", name, expression)
  742. tmp := strings.SplitN(expression, " ", 2)
  743. if len(tmp) != 2 {
  744. return fmt.Errorf("Invalid Dockerfile format")
  745. }
  746. instruction := strings.ToLower(strings.Trim(tmp[0], " "))
  747. arguments := strings.Trim(tmp[1], " ")
  748. method, exists := reflect.TypeOf(b).MethodByName("Cmd" + strings.ToUpper(instruction[:1]) + strings.ToLower(instruction[1:]))
  749. if !exists {
  750. fmt.Fprintf(b.errStream, "# Skipping unknown instruction %s\n", strings.ToUpper(instruction))
  751. return nil
  752. }
  753. ret := method.Func.Call([]reflect.Value{reflect.ValueOf(b), reflect.ValueOf(arguments)})[0].Interface()
  754. if ret != nil {
  755. return ret.(error)
  756. }
  757. fmt.Fprintf(b.outStream, " ---> %s\n", utils.TruncateID(b.image))
  758. return nil
  759. }
  760. func stripComments(raw []byte) string {
  761. var (
  762. out []string
  763. lines = strings.Split(string(raw), "\n")
  764. )
  765. for _, l := range lines {
  766. if len(l) == 0 || l[0] == '#' {
  767. continue
  768. }
  769. out = append(out, l)
  770. }
  771. return strings.Join(out, "\n")
  772. }
  773. func copyAsDirectory(source, destination string, destinationExists bool) error {
  774. if err := archive.CopyWithTar(source, destination); err != nil {
  775. return err
  776. }
  777. if destinationExists {
  778. files, err := ioutil.ReadDir(source)
  779. if err != nil {
  780. return err
  781. }
  782. for _, file := range files {
  783. if err := fixPermissions(filepath.Join(destination, file.Name()), 0, 0); err != nil {
  784. return err
  785. }
  786. }
  787. return nil
  788. }
  789. return fixPermissions(destination, 0, 0)
  790. }
  791. func fixPermissions(destination string, uid, gid int) error {
  792. return filepath.Walk(destination, func(path string, info os.FileInfo, err error) error {
  793. if err := os.Lchown(path, uid, gid); err != nil && !os.IsNotExist(err) {
  794. return err
  795. }
  796. return nil
  797. })
  798. }
  799. 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 {
  800. return &buildFile{
  801. daemon: d,
  802. eng: eng,
  803. config: &runconfig.Config{},
  804. outStream: outStream,
  805. errStream: errStream,
  806. tmpContainers: make(map[string]struct{}),
  807. tmpImages: make(map[string]struct{}),
  808. verbose: verbose,
  809. utilizeCache: utilizeCache,
  810. rm: rm,
  811. forceRm: forceRm,
  812. sf: sf,
  813. authConfig: auth,
  814. configFile: authConfigFile,
  815. outOld: outOld,
  816. }
  817. }