builder.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  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 {
  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. tmpContainers map[string]struct{} = make(map[string]struct{})
  187. tmpImages map[string]struct{} = make(map[string]struct{})
  188. )
  189. defer builder.clearTmp(tmpContainers, tmpImages)
  190. file := bufio.NewReader(dockerfile)
  191. for {
  192. line, err := file.ReadString('\n')
  193. if err != nil {
  194. if err == io.EOF {
  195. break
  196. }
  197. return nil, err
  198. }
  199. line = strings.Replace(strings.TrimSpace(line), " ", " ", 1)
  200. // Skip comments and empty line
  201. if len(line) == 0 || line[0] == '#' {
  202. continue
  203. }
  204. tmp := strings.SplitN(line, " ", 2)
  205. if len(tmp) != 2 {
  206. return nil, fmt.Errorf("Invalid Dockerfile format")
  207. }
  208. instruction := strings.Trim(tmp[0], " ")
  209. arguments := strings.Trim(tmp[1], " ")
  210. switch strings.ToLower(instruction) {
  211. case "from":
  212. fmt.Fprintf(stdout, "FROM %s\n", arguments)
  213. image, err = builder.runtime.repositories.LookupImage(arguments)
  214. if err != nil {
  215. if builder.runtime.graph.IsNotExist(err) {
  216. var tag, remote string
  217. if strings.Contains(arguments, ":") {
  218. remoteParts := strings.Split(arguments, ":")
  219. tag = remoteParts[1]
  220. remote = remoteParts[0]
  221. } else {
  222. remote = arguments
  223. }
  224. if err := builder.runtime.graph.PullRepository(stdout, remote, tag, builder.runtime.repositories, builder.runtime.authConfig); err != nil {
  225. return nil, err
  226. }
  227. image, err = builder.runtime.repositories.LookupImage(arguments)
  228. if err != nil {
  229. return nil, err
  230. }
  231. } else {
  232. return nil, err
  233. }
  234. }
  235. config = &Config{}
  236. break
  237. case "mainainer":
  238. fmt.Fprintf(stdout, "MAINTAINER %s\n", arguments)
  239. maintainer = arguments
  240. break
  241. case "run":
  242. fmt.Fprintf(stdout, "RUN %s\n", arguments)
  243. if image == nil {
  244. return nil, fmt.Errorf("Please provide a source image with `from` prior to run")
  245. }
  246. config, err := ParseRun([]string{image.Id, "/bin/sh", "-c", arguments}, nil, builder.runtime.capabilities)
  247. if err != nil {
  248. return nil, err
  249. }
  250. if cache, err := builder.getCachedImage(image, config); err != nil {
  251. return nil, err
  252. } else if cache != nil {
  253. image = cache
  254. fmt.Fprintf(stdout, "===> %s\n", image.ShortId())
  255. break
  256. }
  257. config, err := ParseRun([]string{image.Id, "/bin/sh", "-c", tmp[1]}, nil, builder.runtime.capabilities)
  258. if err != nil {
  259. return err
  260. }
  261. // Create the container and start it
  262. c, err := builder.Create(config)
  263. if err != nil {
  264. return nil, err
  265. }
  266. if err := c.Start(); err != nil {
  267. return nil, err
  268. }
  269. if err := c.Start(); err != nil {
  270. return err
  271. }
  272. tmpContainers[c.Id] = struct{}{}
  273. // Wait for it to finish
  274. if result := c.Wait(); result != 0 {
  275. return nil, fmt.Errorf("!!! '%s' return non-zero exit code '%d'. Aborting.", arguments, result)
  276. }
  277. // Commit the container
  278. base, err = builder.Commit(c, "", "", "", maintainer, nil)
  279. if err != nil {
  280. return nil, err
  281. }
  282. tmpImages[base.Id] = struct{}{}
  283. fmt.Fprintf(stdout, "===> %s\n", base.ShortId())
  284. // use the base as the new image
  285. image = base
  286. break
  287. case "cmd":
  288. fmt.Fprintf(stdout, "CMD %s\n", arguments)
  289. // Create the container and start it
  290. c, err := builder.Create(&Config{Image: image.Id, Cmd: []string{"", ""}})
  291. if err != nil {
  292. return nil, err
  293. }
  294. if err := c.Start(); err != nil {
  295. return nil, err
  296. }
  297. tmpContainers[c.Id] = struct{}{}
  298. cmd := []string{}
  299. if err := json.Unmarshal([]byte(arguments), &cmd); err != nil {
  300. return nil, err
  301. }
  302. config.Cmd = cmd
  303. // Commit the container
  304. base, err = builder.Commit(c, "", "", "", maintainer, config)
  305. if err != nil {
  306. return nil, err
  307. }
  308. tmpImages[base.Id] = struct{}{}
  309. fmt.Fprintf(stdout, "===> %s\n", base.ShortId())
  310. image = base
  311. break
  312. case "expose":
  313. ports := strings.Split(arguments, " ")
  314. fmt.Fprintf(stdout, "EXPOSE %v\n", ports)
  315. if image == nil {
  316. return nil, fmt.Errorf("Please provide a source image with `from` prior to copy")
  317. }
  318. // Create the container and start it
  319. c, err := builder.Create(&Config{Image: image.Id, Cmd: []string{"", ""}})
  320. if err != nil {
  321. return nil, err
  322. }
  323. if err := c.Start(); err != nil {
  324. return nil, err
  325. }
  326. tmpContainers[c.Id] = struct{}{}
  327. config.PortSpecs = append(ports, config.PortSpecs...)
  328. // Commit the container
  329. base, err = builder.Commit(c, "", "", "", maintainer, config)
  330. if err != nil {
  331. return nil, err
  332. }
  333. tmpImages[base.Id] = struct{}{}
  334. fmt.Fprintf(stdout, "===> %s\n", base.ShortId())
  335. image = base
  336. break
  337. case "insert":
  338. if image == nil {
  339. return nil, fmt.Errorf("Please provide a source image with `from` prior to copy")
  340. }
  341. tmp = strings.SplitN(arguments, " ", 2)
  342. if len(tmp) != 2 {
  343. return nil, fmt.Errorf("Invalid INSERT format")
  344. }
  345. sourceUrl := strings.Trim(tmp[0], " ")
  346. destPath := strings.Trim(tmp[1], " ")
  347. fmt.Fprintf(stdout, "COPY %s to %s in %s\n", sourceUrl, destPath, base.ShortId())
  348. file, err := Download(sourceUrl, stdout)
  349. if err != nil {
  350. return nil, err
  351. }
  352. defer file.Body.Close()
  353. config, err := ParseRun([]string{base.Id, "echo", "insert", sourceUrl, destPath}, nil, builder.runtime.capabilities)
  354. if err != nil {
  355. return nil, err
  356. }
  357. c, err := builder.Create(config)
  358. if err != nil {
  359. return nil, err
  360. }
  361. if err := c.Start(); err != nil {
  362. return nil, err
  363. }
  364. // Wait for echo to finish
  365. if result := c.Wait(); result != 0 {
  366. return nil, fmt.Errorf("!!! '%s' return non-zero exit code '%d'. Aborting.", arguments, result)
  367. }
  368. if err := c.Inject(file.Body, destPath); err != nil {
  369. return nil, err
  370. }
  371. base, err = builder.Commit(c, "", "", "", maintainer, nil)
  372. if err != nil {
  373. return nil, err
  374. }
  375. fmt.Fprintf(stdout, "===> %s\n", base.ShortId())
  376. image = base
  377. break
  378. default:
  379. fmt.Fprintf(stdout, "Skipping unknown instruction %s\n", strings.ToUpper(instruction))
  380. }
  381. }
  382. if image != nil {
  383. // The build is successful, keep the temporary containers and images
  384. for i := range tmpImages {
  385. delete(tmpImages, i)
  386. }
  387. for i := range tmpContainers {
  388. delete(tmpContainers, i)
  389. }
  390. fmt.Fprintf(stdout, "Build finished. image id: %s\n", image.ShortId())
  391. return image, nil
  392. }
  393. return nil, fmt.Errorf("An error occured during the build\n")
  394. }