builder_client.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. package docker
  2. import (
  3. "bufio"
  4. "encoding/json"
  5. "fmt"
  6. "github.com/dotcloud/docker/utils"
  7. "io"
  8. "net/url"
  9. "os"
  10. "reflect"
  11. "strings"
  12. )
  13. type BuilderClient interface {
  14. Build(io.Reader) (string, error)
  15. CmdFrom(string) error
  16. CmdRun(string) error
  17. }
  18. type builderClient struct {
  19. cli *DockerCli
  20. image string
  21. maintainer string
  22. config *Config
  23. tmpContainers map[string]struct{}
  24. tmpImages map[string]struct{}
  25. needCommit bool
  26. }
  27. func (b *builderClient) clearTmp(containers, images map[string]struct{}) {
  28. for i := range images {
  29. if _, _, err := b.cli.call("DELETE", "/images/"+i, nil); err != nil {
  30. utils.Debugf("%s", err)
  31. }
  32. utils.Debugf("Removing image %s", i)
  33. }
  34. }
  35. func (b *builderClient) CmdFrom(name string) error {
  36. obj, statusCode, err := b.cli.call("GET", "/images/"+name+"/json", nil)
  37. if statusCode == 404 {
  38. remote := name
  39. var tag string
  40. if strings.Contains(remote, ":") {
  41. remoteParts := strings.Split(remote, ":")
  42. tag = remoteParts[1]
  43. remote = remoteParts[0]
  44. }
  45. var out io.Writer
  46. if os.Getenv("DEBUG") != "" {
  47. out = os.Stdout
  48. } else {
  49. out = &utils.NopWriter{}
  50. }
  51. if err := b.cli.stream("POST", "/images/create?fromImage="+remote+"&tag="+tag, nil, out); err != nil {
  52. return err
  53. }
  54. obj, _, err = b.cli.call("GET", "/images/"+name+"/json", nil)
  55. if err != nil {
  56. return err
  57. }
  58. }
  59. if err != nil {
  60. return err
  61. }
  62. img := &ApiId{}
  63. if err := json.Unmarshal(obj, img); err != nil {
  64. return err
  65. }
  66. b.image = img.Id
  67. utils.Debugf("Using image %s", b.image)
  68. return nil
  69. }
  70. func (b *builderClient) CmdMaintainer(name string) error {
  71. b.needCommit = true
  72. b.maintainer = name
  73. return nil
  74. }
  75. func (b *builderClient) CmdRun(args string) error {
  76. if b.image == "" {
  77. return fmt.Errorf("Please provide a source image with `from` prior to run")
  78. }
  79. config, _, err := ParseRun([]string{b.image, "/bin/sh", "-c", args}, nil)
  80. if err != nil {
  81. return err
  82. }
  83. cmd, env := b.config.Cmd, b.config.Env
  84. b.config.Cmd = nil
  85. MergeConfig(b.config, config)
  86. body, statusCode, err := b.cli.call("POST", "/images/getCache", &ApiImageConfig{Id: b.image, Config: b.config})
  87. if err != nil {
  88. if statusCode != 404 {
  89. return err
  90. }
  91. }
  92. if statusCode != 404 {
  93. apiId := &ApiId{}
  94. if err := json.Unmarshal(body, apiId); err != nil {
  95. return err
  96. }
  97. utils.Debugf("Use cached version")
  98. b.image = apiId.Id
  99. return nil
  100. }
  101. cid, err := b.run()
  102. if err != nil {
  103. return err
  104. }
  105. b.config.Cmd, b.config.Env = cmd, env
  106. return b.commit(cid)
  107. }
  108. func (b *builderClient) CmdEnv(args string) error {
  109. b.needCommit = true
  110. tmp := strings.SplitN(args, " ", 2)
  111. if len(tmp) != 2 {
  112. return fmt.Errorf("Invalid ENV format")
  113. }
  114. key := strings.Trim(tmp[0], " ")
  115. value := strings.Trim(tmp[1], " ")
  116. for i, elem := range b.config.Env {
  117. if strings.HasPrefix(elem, key+"=") {
  118. b.config.Env[i] = key + "=" + value
  119. return nil
  120. }
  121. }
  122. b.config.Env = append(b.config.Env, key+"="+value)
  123. return nil
  124. }
  125. func (b *builderClient) CmdCmd(args string) error {
  126. b.needCommit = true
  127. var cmd []string
  128. if err := json.Unmarshal([]byte(args), &cmd); err != nil {
  129. utils.Debugf("Error unmarshalling: %s, using /bin/sh -c", err)
  130. b.config.Cmd = []string{"/bin/sh", "-c", args}
  131. } else {
  132. b.config.Cmd = cmd
  133. }
  134. return nil
  135. }
  136. func (b *builderClient) CmdExpose(args string) error {
  137. ports := strings.Split(args, " ")
  138. b.config.PortSpecs = append(ports, b.config.PortSpecs...)
  139. return nil
  140. }
  141. func (b *builderClient) CmdInsert(args string) error {
  142. // FIXME: Reimplement this once the remove_hijack branch gets merged.
  143. // We need to retrieve the resulting Id
  144. return fmt.Errorf("INSERT not implemented")
  145. }
  146. func (b *builderClient) run() (string, error) {
  147. if b.image == "" {
  148. return "", fmt.Errorf("Please provide a source image with `from` prior to run")
  149. }
  150. b.config.Image = b.image
  151. body, _, err := b.cli.call("POST", "/containers/create", b.config)
  152. if err != nil {
  153. return "", err
  154. }
  155. apiRun := &ApiRun{}
  156. if err := json.Unmarshal(body, apiRun); err != nil {
  157. return "", err
  158. }
  159. for _, warning := range apiRun.Warnings {
  160. fmt.Fprintln(os.Stderr, "WARNING: ", warning)
  161. }
  162. //start the container
  163. _, _, err = b.cli.call("POST", "/containers/"+apiRun.Id+"/start", nil)
  164. if err != nil {
  165. return "", err
  166. }
  167. b.tmpContainers[apiRun.Id] = struct{}{}
  168. // Wait for it to finish
  169. body, _, err = b.cli.call("POST", "/containers/"+apiRun.Id+"/wait", nil)
  170. if err != nil {
  171. return "", err
  172. }
  173. apiWait := &ApiWait{}
  174. if err := json.Unmarshal(body, apiWait); err != nil {
  175. return "", err
  176. }
  177. if apiWait.StatusCode != 0 {
  178. return "", fmt.Errorf("The command %v returned a non-zero code: %d", b.config.Cmd, apiWait.StatusCode)
  179. }
  180. return apiRun.Id, nil
  181. }
  182. func (b *builderClient) commit(id string) error {
  183. if b.image == "" {
  184. return fmt.Errorf("Please provide a source image with `from` prior to run")
  185. }
  186. b.config.Image = b.image
  187. if id == "" {
  188. cmd := b.config.Cmd
  189. b.config.Cmd = []string{"true"}
  190. if cid, err := b.run(); err != nil {
  191. return err
  192. } else {
  193. id = cid
  194. }
  195. b.config.Cmd = cmd
  196. }
  197. // Commit the container
  198. v := url.Values{}
  199. v.Set("container", id)
  200. v.Set("author", b.maintainer)
  201. body, _, err := b.cli.call("POST", "/commit?"+v.Encode(), b.config)
  202. if err != nil {
  203. return err
  204. }
  205. apiId := &ApiId{}
  206. if err := json.Unmarshal(body, apiId); err != nil {
  207. return err
  208. }
  209. b.tmpImages[apiId.Id] = struct{}{}
  210. b.image = apiId.Id
  211. b.needCommit = false
  212. return nil
  213. }
  214. func (b *builderClient) Build(dockerfile io.Reader) (string, error) {
  215. defer b.clearTmp(b.tmpContainers, b.tmpImages)
  216. file := bufio.NewReader(dockerfile)
  217. for {
  218. line, err := file.ReadString('\n')
  219. if err != nil {
  220. if err == io.EOF {
  221. break
  222. }
  223. return "", err
  224. }
  225. line = strings.Replace(strings.TrimSpace(line), " ", " ", 1)
  226. // Skip comments and empty line
  227. if len(line) == 0 || line[0] == '#' {
  228. continue
  229. }
  230. tmp := strings.SplitN(line, " ", 2)
  231. if len(tmp) != 2 {
  232. return "", fmt.Errorf("Invalid Dockerfile format")
  233. }
  234. instruction := strings.ToLower(strings.Trim(tmp[0], " "))
  235. arguments := strings.Trim(tmp[1], " ")
  236. fmt.Printf("%s %s (%s)\n", strings.ToUpper(instruction), arguments, b.image)
  237. method, exists := reflect.TypeOf(b).MethodByName("Cmd" + strings.ToUpper(instruction[:1]) + strings.ToLower(instruction[1:]))
  238. if !exists {
  239. fmt.Printf("Skipping unknown instruction %s\n", strings.ToUpper(instruction))
  240. }
  241. ret := method.Func.Call([]reflect.Value{reflect.ValueOf(b), reflect.ValueOf(arguments)})[0].Interface()
  242. if ret != nil {
  243. return "", ret.(error)
  244. }
  245. fmt.Printf("===> %v\n", b.image)
  246. }
  247. if b.needCommit {
  248. if err := b.commit(""); err != nil {
  249. return "", err
  250. }
  251. }
  252. if b.image != "" {
  253. // The build is successful, keep the temporary containers and images
  254. for i := range b.tmpImages {
  255. delete(b.tmpImages, i)
  256. }
  257. for i := range b.tmpContainers {
  258. delete(b.tmpContainers, i)
  259. }
  260. fmt.Printf("Build finished. image id: %s\n", b.image)
  261. return b.image, nil
  262. }
  263. return "", fmt.Errorf("An error occured during the build\n")
  264. }
  265. func NewBuilderClient(addr string, port int) BuilderClient {
  266. return &builderClient{
  267. cli: NewDockerCli(addr, port),
  268. config: &Config{},
  269. tmpContainers: make(map[string]struct{}),
  270. tmpImages: make(map[string]struct{}),
  271. }
  272. }