builder.go 9.3 KB

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