builder.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  1. package docker
  2. import (
  3. "bufio"
  4. "encoding/json"
  5. "fmt"
  6. "io"
  7. "os"
  8. "path"
  9. "strings"
  10. "time"
  11. )
  12. type Builder struct {
  13. runtime *Runtime
  14. repositories *TagStore
  15. graph *Graph
  16. }
  17. func NewBuilder(runtime *Runtime) *Builder {
  18. return &Builder{
  19. runtime: runtime,
  20. graph: runtime.graph,
  21. repositories: runtime.repositories,
  22. }
  23. }
  24. func (builder *Builder) mergeConfig(userConf, imageConf *Config) {
  25. if userConf.Hostname != "" {
  26. userConf.Hostname = imageConf.Hostname
  27. }
  28. if userConf.User != "" {
  29. userConf.User = imageConf.User
  30. }
  31. if userConf.Memory == 0 {
  32. userConf.Memory = imageConf.Memory
  33. }
  34. if userConf.MemorySwap == 0 {
  35. userConf.MemorySwap = imageConf.MemorySwap
  36. }
  37. if userConf.PortSpecs == nil || len(userConf.PortSpecs) == 0 {
  38. userConf.PortSpecs = imageConf.PortSpecs
  39. }
  40. if !userConf.Tty {
  41. userConf.Tty = userConf.Tty
  42. }
  43. if !userConf.OpenStdin {
  44. userConf.OpenStdin = imageConf.OpenStdin
  45. }
  46. if !userConf.StdinOnce {
  47. userConf.StdinOnce = imageConf.StdinOnce
  48. }
  49. if userConf.Env == nil || len(userConf.Env) == 0 {
  50. userConf.Env = imageConf.Env
  51. }
  52. if userConf.Cmd == nil || len(userConf.Cmd) == 0 {
  53. userConf.Cmd = imageConf.Cmd
  54. }
  55. if userConf.Dns == nil || len(userConf.Dns) == 0 {
  56. userConf.Dns = imageConf.Dns
  57. }
  58. }
  59. func (builder *Builder) Create(config *Config) (*Container, error) {
  60. // Lookup image
  61. img, err := builder.repositories.LookupImage(config.Image)
  62. if err != nil {
  63. return nil, err
  64. }
  65. if img.Config != nil {
  66. builder.mergeConfig(config, img.Config)
  67. }
  68. if config.Cmd == nil || len(config.Cmd) == 0 {
  69. return nil, fmt.Errorf("No command specified")
  70. }
  71. // Generate id
  72. id := GenerateId()
  73. // Generate default hostname
  74. // FIXME: the lxc template no longer needs to set a default hostname
  75. if config.Hostname == "" {
  76. config.Hostname = id[:12]
  77. }
  78. container := &Container{
  79. // FIXME: we should generate the ID here instead of receiving it as an argument
  80. Id: id,
  81. Created: time.Now(),
  82. Path: config.Cmd[0],
  83. Args: config.Cmd[1:], //FIXME: de-duplicate from config
  84. Config: config,
  85. Image: img.Id, // Always use the resolved image id
  86. NetworkSettings: &NetworkSettings{},
  87. // FIXME: do we need to store this in the container?
  88. SysInitPath: sysInitPath,
  89. }
  90. container.root = builder.runtime.containerRoot(container.Id)
  91. // Step 1: create the container directory.
  92. // This doubles as a barrier to avoid race conditions.
  93. if err := os.Mkdir(container.root, 0700); err != nil {
  94. return nil, err
  95. }
  96. // If custom dns exists, then create a resolv.conf for the container
  97. if len(config.Dns) > 0 {
  98. container.ResolvConfPath = path.Join(container.root, "resolv.conf")
  99. f, err := os.Create(container.ResolvConfPath)
  100. if err != nil {
  101. return nil, err
  102. }
  103. defer f.Close()
  104. for _, dns := range config.Dns {
  105. if _, err := f.Write([]byte("nameserver " + dns + "\n")); err != nil {
  106. return nil, err
  107. }
  108. }
  109. } else {
  110. container.ResolvConfPath = "/etc/resolv.conf"
  111. }
  112. // Step 2: save the container json
  113. if err := container.ToDisk(); err != nil {
  114. return nil, err
  115. }
  116. // Step 3: register the container
  117. if err := builder.runtime.Register(container); err != nil {
  118. return nil, err
  119. }
  120. return container, nil
  121. }
  122. // Commit creates a new filesystem image from the current state of a container.
  123. // The image can optionally be tagged into a repository
  124. func (builder *Builder) Commit(container *Container, repository, tag, comment, author string, config *Config) (*Image, error) {
  125. // FIXME: freeze the container before copying it to avoid data corruption?
  126. // FIXME: this shouldn't be in commands.
  127. rwTar, err := container.ExportRw()
  128. if err != nil {
  129. return nil, err
  130. }
  131. // Create a new image from the container's base layers + a new layer from container changes
  132. img, err := builder.graph.Create(rwTar, container, comment, author, config)
  133. if err != nil {
  134. return nil, err
  135. }
  136. // Register the image if needed
  137. if repository != "" {
  138. if err := builder.repositories.Set(repository, tag, img.Id, true); err != nil {
  139. return img, err
  140. }
  141. }
  142. return img, nil
  143. }
  144. func (builder *Builder) clearTmp(containers, images map[string]struct{}) {
  145. for c := range containers {
  146. tmp := builder.runtime.Get(c)
  147. builder.runtime.Destroy(tmp)
  148. Debugf("Removing container %s", c)
  149. }
  150. for i := range images {
  151. builder.runtime.graph.Delete(i)
  152. Debugf("Removing image %s", i)
  153. }
  154. }
  155. func (builder *Builder) getCachedImage(image *Image, config *Config) (*Image, error) {
  156. // Retrieve all images
  157. images, err := builder.graph.All()
  158. if err != nil {
  159. return nil, err
  160. }
  161. // Store the tree in a map of map (map[parentId][childId])
  162. imageMap := make(map[string]map[string]struct{})
  163. for _, img := range images {
  164. if _, exists := imageMap[img.Parent]; !exists {
  165. imageMap[img.Parent] = make(map[string]struct{})
  166. }
  167. imageMap[img.Parent][img.Id] = struct{}{}
  168. }
  169. // Loop on the children of the given image and check the config
  170. for elem := range imageMap[image.Id] {
  171. img, err := builder.graph.Get(elem)
  172. if err != nil {
  173. return nil, err
  174. }
  175. if CompareConfig(&img.ContainerConfig, config) {
  176. return img, nil
  177. }
  178. }
  179. return nil, nil
  180. }
  181. func (builder *Builder) Build(dockerfile io.Reader, stdout io.Writer) (*Image, error) {
  182. var (
  183. image, base *Image
  184. config *Config
  185. maintainer string
  186. env map[string]string = make(map[string]string)
  187. tmpContainers map[string]struct{} = make(map[string]struct{})
  188. tmpImages map[string]struct{} = make(map[string]struct{})
  189. )
  190. defer builder.clearTmp(tmpContainers, tmpImages)
  191. file := bufio.NewReader(dockerfile)
  192. for {
  193. line, err := file.ReadString('\n')
  194. if err != nil {
  195. if err == io.EOF {
  196. break
  197. }
  198. return nil, err
  199. }
  200. line = strings.Replace(strings.TrimSpace(line), " ", " ", 1)
  201. // Skip comments and empty line
  202. if len(line) == 0 || line[0] == '#' {
  203. continue
  204. }
  205. tmp := strings.SplitN(line, " ", 2)
  206. if len(tmp) != 2 {
  207. return nil, fmt.Errorf("Invalid Dockerfile format")
  208. }
  209. instruction := strings.Trim(tmp[0], " ")
  210. arguments := strings.Trim(tmp[1], " ")
  211. switch strings.ToLower(instruction) {
  212. case "from":
  213. fmt.Fprintf(stdout, "FROM %s\n", arguments)
  214. image, err = builder.runtime.repositories.LookupImage(arguments)
  215. if err != nil {
  216. if builder.runtime.graph.IsNotExist(err) {
  217. var tag, remote string
  218. if strings.Contains(arguments, ":") {
  219. remoteParts := strings.Split(arguments, ":")
  220. tag = remoteParts[1]
  221. remote = remoteParts[0]
  222. } else {
  223. remote = arguments
  224. }
  225. if err := builder.runtime.graph.PullRepository(stdout, remote, tag, builder.runtime.repositories, builder.runtime.authConfig); err != nil {
  226. return nil, err
  227. }
  228. image, err = builder.runtime.repositories.LookupImage(arguments)
  229. if err != nil {
  230. return nil, err
  231. }
  232. } else {
  233. return nil, err
  234. }
  235. }
  236. config = &Config{}
  237. break
  238. case "maintainer":
  239. fmt.Fprintf(stdout, "MAINTAINER %s\n", arguments)
  240. maintainer = arguments
  241. break
  242. case "run":
  243. fmt.Fprintf(stdout, "RUN %s\n", arguments)
  244. if image == nil {
  245. return nil, fmt.Errorf("Please provide a source image with `from` prior to run")
  246. }
  247. config, _, err := ParseRun([]string{image.Id, "/bin/sh", "-c", arguments}, builder.runtime.capabilities)
  248. if err != nil {
  249. return nil, err
  250. }
  251. for key, value := range env {
  252. config.Env = append(config.Env, fmt.Sprintf("%s=%s", key, value))
  253. }
  254. if cache, err := builder.getCachedImage(image, config); err != nil {
  255. return nil, err
  256. } else if cache != nil {
  257. image = cache
  258. fmt.Fprintf(stdout, "===> %s\n", image.ShortId())
  259. break
  260. }
  261. Debugf("Env -----> %v ------ %v\n", config.Env, env)
  262. // Create the container and start it
  263. c, err := builder.Create(config)
  264. if err != nil {
  265. return nil, err
  266. }
  267. if os.Getenv("DEBUG") != "" {
  268. out, _ := c.StdoutPipe()
  269. err2, _ := c.StderrPipe()
  270. go io.Copy(os.Stdout, out)
  271. go io.Copy(os.Stdout, err2)
  272. }
  273. if err := c.Start(); err != nil {
  274. return nil, err
  275. }
  276. tmpContainers[c.Id] = struct{}{}
  277. // Wait for it to finish
  278. if result := c.Wait(); result != 0 {
  279. return nil, fmt.Errorf("!!! '%s' return non-zero exit code '%d'. Aborting.", arguments, result)
  280. }
  281. // Commit the container
  282. base, err = builder.Commit(c, "", "", "", maintainer, nil)
  283. if err != nil {
  284. return nil, err
  285. }
  286. tmpImages[base.Id] = struct{}{}
  287. fmt.Fprintf(stdout, "===> %s\n", base.ShortId())
  288. // use the base as the new image
  289. image = base
  290. break
  291. case "env":
  292. tmp := strings.SplitN(arguments, " ", 2)
  293. if len(tmp) != 2 {
  294. return nil, fmt.Errorf("Invalid ENV format")
  295. }
  296. key := strings.Trim(tmp[0], " ")
  297. value := strings.Trim(tmp[1], " ")
  298. fmt.Fprintf(stdout, "ENV %s %s\n", key, value)
  299. env[key] = value
  300. if image != nil {
  301. fmt.Fprintf(stdout, "===> %s\n", image.ShortId())
  302. } else {
  303. fmt.Fprintf(stdout, "===> <nil>\n")
  304. }
  305. break
  306. case "cmd":
  307. fmt.Fprintf(stdout, "CMD %s\n", arguments)
  308. // Create the container and start it
  309. c, err := builder.Create(&Config{Image: image.Id, Cmd: []string{"", ""}})
  310. if err != nil {
  311. return nil, err
  312. }
  313. if err := c.Start(); err != nil {
  314. return nil, err
  315. }
  316. tmpContainers[c.Id] = struct{}{}
  317. cmd := []string{}
  318. if err := json.Unmarshal([]byte(arguments), &cmd); err != nil {
  319. return nil, err
  320. }
  321. config.Cmd = cmd
  322. // Commit the container
  323. base, err = builder.Commit(c, "", "", "", maintainer, config)
  324. if err != nil {
  325. return nil, err
  326. }
  327. tmpImages[base.Id] = struct{}{}
  328. fmt.Fprintf(stdout, "===> %s\n", base.ShortId())
  329. image = base
  330. break
  331. case "expose":
  332. ports := strings.Split(arguments, " ")
  333. fmt.Fprintf(stdout, "EXPOSE %v\n", ports)
  334. if image == nil {
  335. return nil, fmt.Errorf("Please provide a source image with `from` prior to copy")
  336. }
  337. // Create the container and start it
  338. c, err := builder.Create(&Config{Image: image.Id, Cmd: []string{"", ""}})
  339. if err != nil {
  340. return nil, err
  341. }
  342. if err := c.Start(); err != nil {
  343. return nil, err
  344. }
  345. tmpContainers[c.Id] = struct{}{}
  346. config.PortSpecs = append(ports, config.PortSpecs...)
  347. // Commit the container
  348. base, err = builder.Commit(c, "", "", "", maintainer, config)
  349. if err != nil {
  350. return nil, err
  351. }
  352. tmpImages[base.Id] = struct{}{}
  353. fmt.Fprintf(stdout, "===> %s\n", base.ShortId())
  354. image = base
  355. break
  356. case "insert":
  357. if image == nil {
  358. return nil, fmt.Errorf("Please provide a source image with `from` prior to copy")
  359. }
  360. tmp = strings.SplitN(arguments, " ", 2)
  361. if len(tmp) != 2 {
  362. return nil, fmt.Errorf("Invalid INSERT format")
  363. }
  364. sourceUrl := strings.Trim(tmp[0], " ")
  365. destPath := strings.Trim(tmp[1], " ")
  366. fmt.Fprintf(stdout, "COPY %s to %s in %s\n", sourceUrl, destPath, base.ShortId())
  367. file, err := Download(sourceUrl, stdout)
  368. if err != nil {
  369. return nil, err
  370. }
  371. defer file.Body.Close()
  372. config, _, err := ParseRun([]string{base.Id, "echo", "insert", sourceUrl, destPath}, builder.runtime.capabilities)
  373. if err != nil {
  374. return nil, err
  375. }
  376. c, err := builder.Create(config)
  377. if err != nil {
  378. return nil, err
  379. }
  380. if err := c.Start(); err != nil {
  381. return nil, err
  382. }
  383. // Wait for echo to finish
  384. if result := c.Wait(); result != 0 {
  385. return nil, fmt.Errorf("!!! '%s' return non-zero exit code '%d'. Aborting.", arguments, result)
  386. }
  387. if err := c.Inject(file.Body, destPath); err != nil {
  388. return nil, err
  389. }
  390. base, err = builder.Commit(c, "", "", "", maintainer, nil)
  391. if err != nil {
  392. return nil, err
  393. }
  394. fmt.Fprintf(stdout, "===> %s\n", base.ShortId())
  395. image = base
  396. break
  397. default:
  398. fmt.Fprintf(stdout, "Skipping unknown instruction %s\n", strings.ToUpper(instruction))
  399. }
  400. }
  401. if image != nil {
  402. // The build is successful, keep the temporary containers and images
  403. for i := range tmpImages {
  404. delete(tmpImages, i)
  405. }
  406. for i := range tmpContainers {
  407. delete(tmpContainers, i)
  408. }
  409. fmt.Fprintf(stdout, "Build finished. image id: %s\n", image.ShortId())
  410. return image, nil
  411. }
  412. return nil, fmt.Errorf("An error occured during the build\n")
  413. }