buildfile.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  1. package docker
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "github.com/dotcloud/docker/utils"
  6. "io"
  7. "io/ioutil"
  8. "net/url"
  9. "os"
  10. "path"
  11. "reflect"
  12. "regexp"
  13. "strings"
  14. )
  15. type BuildFile interface {
  16. Build(io.Reader) (string, error)
  17. CmdFrom(string) error
  18. CmdRun(string) error
  19. }
  20. type buildFile struct {
  21. runtime *Runtime
  22. srv *Server
  23. image string
  24. maintainer string
  25. config *Config
  26. context string
  27. verbose bool
  28. utilizeCache bool
  29. rm bool
  30. tmpContainers map[string]struct{}
  31. tmpImages map[string]struct{}
  32. out io.Writer
  33. }
  34. func (b *buildFile) clearTmp(containers map[string]struct{}) {
  35. for c := range containers {
  36. tmp := b.runtime.Get(c)
  37. b.runtime.Destroy(tmp)
  38. fmt.Fprintf(b.out, "Removing intermediate container %s\n", utils.TruncateID(c))
  39. }
  40. }
  41. func (b *buildFile) CmdFrom(name string) error {
  42. image, err := b.runtime.repositories.LookupImage(name)
  43. if err != nil {
  44. if b.runtime.graph.IsNotExist(err) {
  45. remote, tag := utils.ParseRepositoryTag(name)
  46. if err := b.srv.ImagePull(remote, tag, b.out, utils.NewStreamFormatter(false), nil, nil, true); err != nil {
  47. return err
  48. }
  49. image, err = b.runtime.repositories.LookupImage(name)
  50. if err != nil {
  51. return err
  52. }
  53. } else {
  54. return err
  55. }
  56. }
  57. b.image = image.ID
  58. b.config = &Config{}
  59. if b.config.Env == nil || len(b.config.Env) == 0 {
  60. b.config.Env = append(b.config.Env, "HOME=/", "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin")
  61. }
  62. return nil
  63. }
  64. func (b *buildFile) CmdMaintainer(name string) error {
  65. b.maintainer = name
  66. return b.commit("", b.config.Cmd, fmt.Sprintf("MAINTAINER %s", name))
  67. }
  68. func (b *buildFile) CmdRun(args string) error {
  69. if b.image == "" {
  70. return fmt.Errorf("Please provide a source image with `from` prior to run")
  71. }
  72. config, _, _, err := ParseRun([]string{b.image, "/bin/sh", "-c", args}, nil)
  73. if err != nil {
  74. return err
  75. }
  76. cmd := b.config.Cmd
  77. b.config.Cmd = nil
  78. MergeConfig(b.config, config)
  79. defer func(cmd []string) { b.config.Cmd = cmd }(cmd)
  80. utils.Debugf("Command to be executed: %v", b.config.Cmd)
  81. if b.utilizeCache {
  82. if cache, err := b.srv.ImageGetCached(b.image, b.config); err != nil {
  83. return err
  84. } else if cache != nil {
  85. fmt.Fprintf(b.out, " ---> Using cache\n")
  86. utils.Debugf("[BUILDER] Use cached version")
  87. b.image = cache.ID
  88. return nil
  89. } else {
  90. utils.Debugf("[BUILDER] Cache miss")
  91. }
  92. }
  93. cid, err := b.run()
  94. if err != nil {
  95. return err
  96. }
  97. if err := b.commit(cid, cmd, "run"); err != nil {
  98. return err
  99. }
  100. return nil
  101. }
  102. func (b *buildFile) FindEnvKey(key string) int {
  103. for k, envVar := range b.config.Env {
  104. envParts := strings.SplitN(envVar, "=", 2)
  105. if key == envParts[0] {
  106. return k
  107. }
  108. }
  109. return -1
  110. }
  111. func (b *buildFile) ReplaceEnvMatches(value string) (string, error) {
  112. exp, err := regexp.Compile("(\\\\\\\\+|[^\\\\]|\\b|\\A)\\$({?)([[:alnum:]_]+)(}?)")
  113. if err != nil {
  114. return value, err
  115. }
  116. matches := exp.FindAllString(value, -1)
  117. for _, match := range matches {
  118. match = match[strings.Index(match, "$"):]
  119. matchKey := strings.Trim(match, "${}")
  120. for _, envVar := range b.config.Env {
  121. envParts := strings.SplitN(envVar, "=", 2)
  122. envKey := envParts[0]
  123. envValue := envParts[1]
  124. if envKey == matchKey {
  125. value = strings.Replace(value, match, envValue, -1)
  126. break
  127. }
  128. }
  129. }
  130. return value, nil
  131. }
  132. func (b *buildFile) CmdEnv(args string) error {
  133. tmp := strings.SplitN(args, " ", 2)
  134. if len(tmp) != 2 {
  135. return fmt.Errorf("Invalid ENV format")
  136. }
  137. key := strings.Trim(tmp[0], " \t")
  138. value := strings.Trim(tmp[1], " \t")
  139. envKey := b.FindEnvKey(key)
  140. replacedValue, err := b.ReplaceEnvMatches(value)
  141. if err != nil {
  142. return err
  143. }
  144. replacedVar := fmt.Sprintf("%s=%s", key, replacedValue)
  145. if envKey >= 0 {
  146. b.config.Env[envKey] = replacedVar
  147. } else {
  148. b.config.Env = append(b.config.Env, replacedVar)
  149. }
  150. return b.commit("", b.config.Cmd, fmt.Sprintf("ENV %s", replacedVar))
  151. }
  152. func (b *buildFile) CmdCmd(args string) error {
  153. var cmd []string
  154. if err := json.Unmarshal([]byte(args), &cmd); err != nil {
  155. utils.Errorf("Error unmarshalling: %s, setting cmd to /bin/sh -c", err)
  156. cmd = []string{"/bin/sh", "-c", args}
  157. }
  158. if err := b.commit("", cmd, fmt.Sprintf("CMD %v", cmd)); err != nil {
  159. return err
  160. }
  161. b.config.Cmd = cmd
  162. return nil
  163. }
  164. func (b *buildFile) CmdExpose(args string) error {
  165. ports := strings.Split(args, " ")
  166. b.config.PortSpecs = append(ports, b.config.PortSpecs...)
  167. return b.commit("", b.config.Cmd, fmt.Sprintf("EXPOSE %v", ports))
  168. }
  169. func (b *buildFile) CmdUser(args string) error {
  170. b.config.User = args
  171. return b.commit("", b.config.Cmd, fmt.Sprintf("USER %v", args))
  172. }
  173. func (b *buildFile) CmdInsert(args string) error {
  174. return fmt.Errorf("INSERT has been deprecated. Please use ADD instead")
  175. }
  176. func (b *buildFile) CmdCopy(args string) error {
  177. return fmt.Errorf("COPY has been deprecated. Please use ADD instead")
  178. }
  179. func (b *buildFile) CmdEntrypoint(args string) error {
  180. if args == "" {
  181. return fmt.Errorf("Entrypoint cannot be empty")
  182. }
  183. var entrypoint []string
  184. if err := json.Unmarshal([]byte(args), &entrypoint); err != nil {
  185. b.config.Entrypoint = []string{"/bin/sh", "-c", args}
  186. } else {
  187. b.config.Entrypoint = entrypoint
  188. }
  189. if err := b.commit("", b.config.Cmd, fmt.Sprintf("ENTRYPOINT %s", args)); err != nil {
  190. return err
  191. }
  192. return nil
  193. }
  194. func (b *buildFile) CmdWorkdir(workdir string) error {
  195. b.config.WorkingDir = workdir
  196. return b.commit("", b.config.Cmd, fmt.Sprintf("WORKDIR %v", workdir))
  197. }
  198. func (b *buildFile) CmdVolume(args string) error {
  199. if args == "" {
  200. return fmt.Errorf("Volume cannot be empty")
  201. }
  202. var volume []string
  203. if err := json.Unmarshal([]byte(args), &volume); err != nil {
  204. volume = []string{args}
  205. }
  206. if b.config.Volumes == nil {
  207. b.config.Volumes = NewPathOpts()
  208. }
  209. for _, v := range volume {
  210. b.config.Volumes[v] = struct{}{}
  211. }
  212. if err := b.commit("", b.config.Cmd, fmt.Sprintf("VOLUME %s", args)); err != nil {
  213. return err
  214. }
  215. return nil
  216. }
  217. func (b *buildFile) addRemote(container *Container, orig, dest string) error {
  218. file, err := utils.Download(orig, ioutil.Discard)
  219. if err != nil {
  220. return err
  221. }
  222. defer file.Body.Close()
  223. // If the destination is a directory, figure out the filename.
  224. if strings.HasSuffix(dest, "/") {
  225. u, err := url.Parse(orig)
  226. if err != nil {
  227. return err
  228. }
  229. path := u.Path
  230. if strings.HasSuffix(path, "/") {
  231. path = path[:len(path)-1]
  232. }
  233. parts := strings.Split(path, "/")
  234. filename := parts[len(parts)-1]
  235. if filename == "" {
  236. return fmt.Errorf("cannot determine filename from url: %s", u)
  237. }
  238. dest = dest + filename
  239. }
  240. return container.Inject(file.Body, dest)
  241. }
  242. func (b *buildFile) addContext(container *Container, orig, dest string) error {
  243. origPath := path.Join(b.context, orig)
  244. destPath := path.Join(container.RootfsPath(), dest)
  245. // Preserve the trailing '/'
  246. if strings.HasSuffix(dest, "/") {
  247. destPath = destPath + "/"
  248. }
  249. if !strings.HasPrefix(origPath, b.context) {
  250. return fmt.Errorf("Forbidden path: %s", origPath)
  251. }
  252. fi, err := os.Stat(origPath)
  253. if err != nil {
  254. return fmt.Errorf("%s: no such file or directory", orig)
  255. }
  256. if fi.IsDir() {
  257. if err := CopyWithTar(origPath, destPath); err != nil {
  258. return err
  259. }
  260. // First try to unpack the source as an archive
  261. } else if err := UntarPath(origPath, destPath); err != nil {
  262. utils.Errorf("Couldn't untar %s to %s: %s", origPath, destPath, err)
  263. // If that fails, just copy it as a regular file
  264. if err := os.MkdirAll(path.Dir(destPath), 0755); err != nil {
  265. return err
  266. }
  267. if err := CopyWithTar(origPath, destPath); err != nil {
  268. return err
  269. }
  270. }
  271. return nil
  272. }
  273. func (b *buildFile) CmdAdd(args string) error {
  274. if b.context == "" {
  275. return fmt.Errorf("No context given. Impossible to use ADD")
  276. }
  277. tmp := strings.SplitN(args, " ", 2)
  278. if len(tmp) != 2 {
  279. return fmt.Errorf("Invalid ADD format")
  280. }
  281. orig, err := b.ReplaceEnvMatches(strings.Trim(tmp[0], " \t"))
  282. if err != nil {
  283. return err
  284. }
  285. dest, err := b.ReplaceEnvMatches(strings.Trim(tmp[1], " \t"))
  286. if err != nil {
  287. return err
  288. }
  289. cmd := b.config.Cmd
  290. b.config.Cmd = []string{"/bin/sh", "-c", fmt.Sprintf("#(nop) ADD %s in %s", orig, dest)}
  291. b.config.Image = b.image
  292. // Create the container and start it
  293. container, err := b.runtime.Create(b.config)
  294. if err != nil {
  295. return err
  296. }
  297. b.tmpContainers[container.ID] = struct{}{}
  298. if err := container.EnsureMounted(); err != nil {
  299. return err
  300. }
  301. defer container.Unmount()
  302. if utils.IsURL(orig) {
  303. if err := b.addRemote(container, orig, dest); err != nil {
  304. return err
  305. }
  306. } else {
  307. if err := b.addContext(container, orig, dest); err != nil {
  308. return err
  309. }
  310. }
  311. if err := b.commit(container.ID, cmd, fmt.Sprintf("ADD %s in %s", orig, dest)); err != nil {
  312. return err
  313. }
  314. b.config.Cmd = cmd
  315. return nil
  316. }
  317. func (b *buildFile) run() (string, error) {
  318. if b.image == "" {
  319. return "", fmt.Errorf("Please provide a source image with `from` prior to run")
  320. }
  321. b.config.Image = b.image
  322. // Create the container and start it
  323. c, err := b.runtime.Create(b.config)
  324. if err != nil {
  325. return "", err
  326. }
  327. b.tmpContainers[c.ID] = struct{}{}
  328. fmt.Fprintf(b.out, " ---> Running in %s\n", utils.TruncateID(c.ID))
  329. // override the entry point that may have been picked up from the base image
  330. c.Path = b.config.Cmd[0]
  331. c.Args = b.config.Cmd[1:]
  332. //start the container
  333. hostConfig := &HostConfig{}
  334. if err := c.Start(hostConfig); err != nil {
  335. return "", err
  336. }
  337. if b.verbose {
  338. err = <-c.Attach(nil, nil, b.out, b.out)
  339. if err != nil {
  340. return "", err
  341. }
  342. }
  343. // Wait for it to finish
  344. if ret := c.Wait(); ret != 0 {
  345. return "", fmt.Errorf("The command %v returned a non-zero code: %d", b.config.Cmd, ret)
  346. }
  347. return c.ID, nil
  348. }
  349. // Commit the container <id> with the autorun command <autoCmd>
  350. func (b *buildFile) commit(id string, autoCmd []string, comment string) error {
  351. if b.image == "" {
  352. return fmt.Errorf("Please provide a source image with `from` prior to commit")
  353. }
  354. b.config.Image = b.image
  355. if id == "" {
  356. cmd := b.config.Cmd
  357. b.config.Cmd = []string{"/bin/sh", "-c", "#(nop) " + comment}
  358. defer func(cmd []string) { b.config.Cmd = cmd }(cmd)
  359. if b.utilizeCache {
  360. if cache, err := b.srv.ImageGetCached(b.image, b.config); err != nil {
  361. return err
  362. } else if cache != nil {
  363. fmt.Fprintf(b.out, " ---> Using cache\n")
  364. utils.Debugf("[BUILDER] Use cached version")
  365. b.image = cache.ID
  366. return nil
  367. } else {
  368. utils.Debugf("[BUILDER] Cache miss")
  369. }
  370. }
  371. container, err := b.runtime.Create(b.config)
  372. if err != nil {
  373. return err
  374. }
  375. b.tmpContainers[container.ID] = struct{}{}
  376. fmt.Fprintf(b.out, " ---> Running in %s\n", utils.TruncateID(container.ID))
  377. id = container.ID
  378. if err := container.EnsureMounted(); err != nil {
  379. return err
  380. }
  381. defer container.Unmount()
  382. }
  383. container := b.runtime.Get(id)
  384. if container == nil {
  385. return fmt.Errorf("An error occured while creating the container")
  386. }
  387. // Note: Actually copy the struct
  388. autoConfig := *b.config
  389. autoConfig.Cmd = autoCmd
  390. // Commit the container
  391. image, err := b.runtime.Commit(container, "", "", "", b.maintainer, &autoConfig)
  392. if err != nil {
  393. return err
  394. }
  395. b.tmpImages[image.ID] = struct{}{}
  396. b.image = image.ID
  397. return nil
  398. }
  399. // Long lines can be split with a backslash
  400. var lineContinuation = regexp.MustCompile(`\s*\\\s*\n`)
  401. func (b *buildFile) Build(context io.Reader) (string, error) {
  402. // FIXME: @creack "name" is a terrible variable name
  403. name, err := ioutil.TempDir("", "docker-build")
  404. if err != nil {
  405. return "", err
  406. }
  407. if err := Untar(context, name); err != nil {
  408. return "", err
  409. }
  410. defer os.RemoveAll(name)
  411. b.context = name
  412. filename := path.Join(name, "Dockerfile")
  413. if _, err := os.Stat(filename); os.IsNotExist(err) {
  414. return "", fmt.Errorf("Can't build a directory with no Dockerfile")
  415. }
  416. fileBytes, err := ioutil.ReadFile(filename)
  417. if err != nil {
  418. return "", err
  419. }
  420. dockerfile := string(fileBytes)
  421. dockerfile = lineContinuation.ReplaceAllString(dockerfile, "")
  422. stepN := 0
  423. for _, line := range strings.Split(dockerfile, "\n") {
  424. line = strings.Trim(strings.Replace(line, "\t", " ", -1), " \t\r\n")
  425. // Skip comments and empty line
  426. if len(line) == 0 || line[0] == '#' {
  427. continue
  428. }
  429. tmp := strings.SplitN(line, " ", 2)
  430. if len(tmp) != 2 {
  431. return "", fmt.Errorf("Invalid Dockerfile format")
  432. }
  433. instruction := strings.ToLower(strings.Trim(tmp[0], " "))
  434. arguments := strings.Trim(tmp[1], " ")
  435. method, exists := reflect.TypeOf(b).MethodByName("Cmd" + strings.ToUpper(instruction[:1]) + strings.ToLower(instruction[1:]))
  436. if !exists {
  437. fmt.Fprintf(b.out, "# Skipping unknown instruction %s\n", strings.ToUpper(instruction))
  438. continue
  439. }
  440. stepN += 1
  441. fmt.Fprintf(b.out, "Step %d : %s %s\n", stepN, strings.ToUpper(instruction), arguments)
  442. ret := method.Func.Call([]reflect.Value{reflect.ValueOf(b), reflect.ValueOf(arguments)})[0].Interface()
  443. if ret != nil {
  444. return "", ret.(error)
  445. }
  446. fmt.Fprintf(b.out, " ---> %v\n", utils.TruncateID(b.image))
  447. }
  448. if b.image != "" {
  449. fmt.Fprintf(b.out, "Successfully built %s\n", utils.TruncateID(b.image))
  450. if b.rm {
  451. b.clearTmp(b.tmpContainers)
  452. }
  453. return b.image, nil
  454. }
  455. return "", fmt.Errorf("An error occurred during the build\n")
  456. }
  457. func NewBuildFile(srv *Server, out io.Writer, verbose, utilizeCache, rm bool) BuildFile {
  458. return &buildFile{
  459. runtime: srv.runtime,
  460. srv: srv,
  461. config: &Config{},
  462. out: out,
  463. tmpContainers: make(map[string]struct{}),
  464. tmpImages: make(map[string]struct{}),
  465. verbose: verbose,
  466. utilizeCache: utilizeCache,
  467. rm: rm,
  468. }
  469. }