server.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839
  1. package docker
  2. import (
  3. "fmt"
  4. "github.com/dotcloud/docker/auth"
  5. "github.com/dotcloud/docker/registry"
  6. "github.com/dotcloud/docker/utils"
  7. "io"
  8. "io/ioutil"
  9. "log"
  10. "net/http"
  11. "net/url"
  12. "os"
  13. "path"
  14. "runtime"
  15. "strings"
  16. )
  17. func (srv *Server) DockerVersion() ApiVersion {
  18. return ApiVersion{VERSION, GIT_COMMIT, srv.runtime.capabilities.MemoryLimit, srv.runtime.capabilities.SwapLimit}
  19. }
  20. func (srv *Server) ContainerKill(name string) error {
  21. if container := srv.runtime.Get(name); container != nil {
  22. if err := container.Kill(); err != nil {
  23. return fmt.Errorf("Error restarting container %s: %s", name, err.Error())
  24. }
  25. } else {
  26. return fmt.Errorf("No such container: %s", name)
  27. }
  28. return nil
  29. }
  30. func (srv *Server) ContainerExport(name string, out io.Writer) error {
  31. if container := srv.runtime.Get(name); container != nil {
  32. data, err := container.Export()
  33. if err != nil {
  34. return err
  35. }
  36. // Stream the entire contents of the container (basically a volatile snapshot)
  37. if _, err := io.Copy(out, data); err != nil {
  38. return err
  39. }
  40. return nil
  41. }
  42. return fmt.Errorf("No such container: %s", name)
  43. }
  44. func (srv *Server) ImagesSearch(term string) ([]ApiSearch, error) {
  45. results, err := srv.registry.SearchRepositories(term)
  46. if err != nil {
  47. return nil, err
  48. }
  49. var outs []ApiSearch
  50. for _, repo := range results.Results {
  51. var out ApiSearch
  52. out.Description = repo["description"]
  53. if len(out.Description) > 45 {
  54. out.Description = utils.Trunc(out.Description, 42) + "..."
  55. }
  56. out.Name = repo["name"]
  57. outs = append(outs, out)
  58. }
  59. return outs, nil
  60. }
  61. func (srv *Server) ImageInsert(name, url, path string, out io.Writer) error {
  62. img, err := srv.runtime.repositories.LookupImage(name)
  63. if err != nil {
  64. return err
  65. }
  66. file, err := utils.Download(url, out)
  67. if err != nil {
  68. return err
  69. }
  70. defer file.Body.Close()
  71. config, _, err := ParseRun([]string{img.Id, "echo", "insert", url, path}, srv.runtime.capabilities)
  72. if err != nil {
  73. return err
  74. }
  75. b := NewBuilder(srv.runtime)
  76. c, err := b.Create(config)
  77. if err != nil {
  78. return err
  79. }
  80. if err := c.Inject(utils.ProgressReader(file.Body, int(file.ContentLength), out, "Downloading %v/%v (%v)"), path); err != nil {
  81. return err
  82. }
  83. // FIXME: Handle custom repo, tag comment, author
  84. img, err = b.Commit(c, "", "", img.Comment, img.Author, nil)
  85. if err != nil {
  86. return err
  87. }
  88. utils.FprintfFlush(out, "%s\n", img.Id)
  89. return nil
  90. }
  91. func (srv *Server) ImagesViz(out io.Writer) error {
  92. images, _ := srv.runtime.graph.All()
  93. if images == nil {
  94. return nil
  95. }
  96. out.Write([]byte("digraph docker {\n"))
  97. var (
  98. parentImage *Image
  99. err error
  100. )
  101. for _, image := range images {
  102. parentImage, err = image.GetParent()
  103. if err != nil {
  104. return fmt.Errorf("Error while getting parent image: %v", err)
  105. }
  106. if parentImage != nil {
  107. out.Write([]byte(" \"" + parentImage.ShortId() + "\" -> \"" + image.ShortId() + "\"\n"))
  108. } else {
  109. out.Write([]byte(" base -> \"" + image.ShortId() + "\" [style=invis]\n"))
  110. }
  111. }
  112. reporefs := make(map[string][]string)
  113. for name, repository := range srv.runtime.repositories.Repositories {
  114. for tag, id := range repository {
  115. reporefs[utils.TruncateId(id)] = append(reporefs[utils.TruncateId(id)], fmt.Sprintf("%s:%s", name, tag))
  116. }
  117. }
  118. for id, repos := range reporefs {
  119. out.Write([]byte(" \"" + id + "\" [label=\"" + id + "\\n" + strings.Join(repos, "\\n") + "\",shape=box,fillcolor=\"paleturquoise\",style=\"filled,rounded\"];\n"))
  120. }
  121. out.Write([]byte(" base [style=invisible]\n}\n"))
  122. return nil
  123. }
  124. func (srv *Server) Images(all bool, filter string) ([]ApiImages, error) {
  125. var allImages map[string]*Image
  126. var err error
  127. if all {
  128. allImages, err = srv.runtime.graph.Map()
  129. } else {
  130. allImages, err = srv.runtime.graph.Heads()
  131. }
  132. if err != nil {
  133. return nil, err
  134. }
  135. var outs []ApiImages = []ApiImages{} //produce [] when empty instead of 'null'
  136. for name, repository := range srv.runtime.repositories.Repositories {
  137. if filter != "" && name != filter {
  138. continue
  139. }
  140. for tag, id := range repository {
  141. var out ApiImages
  142. image, err := srv.runtime.graph.Get(id)
  143. if err != nil {
  144. log.Printf("Warning: couldn't load %s from %s/%s: %s", id, name, tag, err)
  145. continue
  146. }
  147. delete(allImages, id)
  148. out.Repository = name
  149. out.Tag = tag
  150. out.Id = image.Id
  151. out.Created = image.Created.Unix()
  152. outs = append(outs, out)
  153. }
  154. }
  155. // Display images which aren't part of a
  156. if filter == "" {
  157. for _, image := range allImages {
  158. var out ApiImages
  159. out.Id = image.Id
  160. out.Created = image.Created.Unix()
  161. outs = append(outs, out)
  162. }
  163. }
  164. return outs, nil
  165. }
  166. func (srv *Server) DockerInfo() ApiInfo {
  167. images, _ := srv.runtime.graph.All()
  168. var imgcount int
  169. if images == nil {
  170. imgcount = 0
  171. } else {
  172. imgcount = len(images)
  173. }
  174. var out ApiInfo
  175. out.Containers = len(srv.runtime.List())
  176. out.Version = VERSION
  177. out.Images = imgcount
  178. out.GoVersion = runtime.Version()
  179. if os.Getenv("DEBUG") != "" {
  180. out.Debug = true
  181. out.NFd = utils.GetTotalUsedFds()
  182. out.NGoroutines = runtime.NumGoroutine()
  183. }
  184. return out
  185. }
  186. func (srv *Server) ImageHistory(name string) ([]ApiHistory, error) {
  187. image, err := srv.runtime.repositories.LookupImage(name)
  188. if err != nil {
  189. return nil, err
  190. }
  191. var outs []ApiHistory = []ApiHistory{} //produce [] when empty instead of 'null'
  192. err = image.WalkHistory(func(img *Image) error {
  193. var out ApiHistory
  194. out.Id = srv.runtime.repositories.ImageName(img.ShortId())
  195. out.Created = img.Created.Unix()
  196. out.CreatedBy = strings.Join(img.ContainerConfig.Cmd, " ")
  197. outs = append(outs, out)
  198. return nil
  199. })
  200. return outs, nil
  201. }
  202. func (srv *Server) ContainerChanges(name string) ([]Change, error) {
  203. if container := srv.runtime.Get(name); container != nil {
  204. return container.Changes()
  205. }
  206. return nil, fmt.Errorf("No such container: %s", name)
  207. }
  208. func (srv *Server) Containers(all bool, n int, since, before string) []ApiContainers {
  209. var foundBefore bool
  210. var displayed int
  211. retContainers := []ApiContainers{}
  212. for _, container := range srv.runtime.List() {
  213. if !container.State.Running && !all && n == -1 && since == "" && before == "" {
  214. continue
  215. }
  216. if before != "" {
  217. if container.ShortId() == before {
  218. foundBefore = true
  219. continue
  220. }
  221. if !foundBefore {
  222. continue
  223. }
  224. }
  225. if displayed == n {
  226. break
  227. }
  228. if container.ShortId() == since {
  229. break
  230. }
  231. displayed++
  232. c := ApiContainers{
  233. Id: container.Id,
  234. }
  235. c.Image = srv.runtime.repositories.ImageName(container.Image)
  236. c.Command = fmt.Sprintf("%s %s", container.Path, strings.Join(container.Args, " "))
  237. c.Created = container.Created.Unix()
  238. c.Status = container.State.String()
  239. c.Ports = container.NetworkSettings.PortMappingHuman()
  240. retContainers = append(retContainers, c)
  241. }
  242. return retContainers
  243. }
  244. func (srv *Server) ContainerCommit(name, repo, tag, author, comment string, config *Config) (string, error) {
  245. container := srv.runtime.Get(name)
  246. if container == nil {
  247. return "", fmt.Errorf("No such container: %s", name)
  248. }
  249. img, err := NewBuilder(srv.runtime).Commit(container, repo, tag, comment, author, config)
  250. if err != nil {
  251. return "", err
  252. }
  253. return img.ShortId(), err
  254. }
  255. func (srv *Server) ContainerTag(name, repo, tag string, force bool) error {
  256. if err := srv.runtime.repositories.Set(repo, tag, name, force); err != nil {
  257. return err
  258. }
  259. return nil
  260. }
  261. func (srv *Server) pullImage(out io.Writer, imgId, registry string, token []string) error {
  262. history, err := srv.registry.GetRemoteHistory(imgId, registry, token)
  263. if err != nil {
  264. return err
  265. }
  266. // FIXME: Try to stream the images?
  267. // FIXME: Launch the getRemoteImage() in goroutines
  268. for _, id := range history {
  269. if !srv.runtime.graph.Exists(id) {
  270. utils.FprintfFlush(out, "Pulling %s metadata\r\n", id)
  271. imgJson, err := srv.registry.GetRemoteImageJson(id, registry, token)
  272. if err != nil {
  273. // FIXME: Keep goging in case of error?
  274. return err
  275. }
  276. img, err := NewImgJson(imgJson)
  277. if err != nil {
  278. return fmt.Errorf("Failed to parse json: %s", err)
  279. }
  280. // Get the layer
  281. utils.FprintfFlush(out, "Pulling %s fs layer\r\n", img.Id)
  282. layer, contentLength, err := srv.registry.GetRemoteImageLayer(img.Id, registry, token)
  283. if err != nil {
  284. return err
  285. }
  286. if err := srv.runtime.graph.Register(utils.ProgressReader(layer, contentLength, out, "Downloading %v/%v (%v)"), false, img); err != nil {
  287. return err
  288. }
  289. }
  290. }
  291. return nil
  292. }
  293. func (srv *Server) pullRepository(out io.Writer, remote, askedTag string) error {
  294. utils.FprintfFlush(out, "Pulling repository %s from %s\r\n", remote, auth.IndexServerAddress())
  295. repoData, err := srv.registry.GetRepositoryData(remote)
  296. if err != nil {
  297. return err
  298. }
  299. utils.Debugf("Updating checksums")
  300. // Reload the json file to make sure not to overwrite faster sums
  301. if err := srv.runtime.graph.UpdateChecksums(repoData.ImgList); err != nil {
  302. return err
  303. }
  304. utils.Debugf("Retrieving the tag list")
  305. tagsList, err := srv.registry.GetRemoteTags(repoData.Endpoints, remote, repoData.Tokens)
  306. if err != nil {
  307. return err
  308. }
  309. for tag, id := range tagsList {
  310. repoData.ImgList[id].Tag = tag
  311. }
  312. for _, img := range repoData.ImgList {
  313. // If we asked for a specific tag, skip all tags expect the wanted one
  314. if askedTag != "" && askedTag != img.Tag {
  315. continue
  316. }
  317. utils.FprintfFlush(out, "Pulling image %s (%s) from %s\n", img.Id, img.Tag, remote)
  318. success := false
  319. for _, ep := range repoData.Endpoints {
  320. if err := srv.pullImage(out, img.Id, "https://"+ep+"/v1", repoData.Tokens); err != nil {
  321. utils.FprintfFlush(out, "Error while retrieving image for tag: %s (%s); checking next endpoint\n", askedTag, err)
  322. continue
  323. }
  324. if err := srv.runtime.repositories.Set(remote, img.Tag, img.Id, true); err != nil {
  325. return err
  326. }
  327. success = true
  328. delete(tagsList, img.Tag)
  329. break
  330. }
  331. if !success {
  332. return fmt.Errorf("Could not find repository on any of the indexed registries.")
  333. }
  334. }
  335. for tag, id := range tagsList {
  336. if err := srv.runtime.repositories.Set(remote, tag, id, true); err != nil {
  337. return err
  338. }
  339. }
  340. if err := srv.runtime.repositories.Save(); err != nil {
  341. return err
  342. }
  343. return nil
  344. }
  345. func (srv *Server) ImagePull(name, tag, registry string, out io.Writer) error {
  346. if registry != "" {
  347. if err := srv.pullImage(out, name, registry, nil); err != nil {
  348. return err
  349. }
  350. return nil
  351. }
  352. if err := srv.pullRepository(out, name, tag); err != nil {
  353. return err
  354. }
  355. return nil
  356. }
  357. // Retrieve the checksum of an image
  358. // Priority:
  359. // - Check on the stored checksums
  360. // - Check if the archive exists, if it does not, ask the registry
  361. // - If the archive does exists, process the checksum from it
  362. // - If the archive does not exists and not found on registry, process checksum from layer
  363. func (srv *Server) getChecksum(imageId string) (string, error) {
  364. // FIXME: Use in-memory map instead of reading the file each time
  365. if sums, err := srv.runtime.graph.getStoredChecksums(); err != nil {
  366. return "", err
  367. } else if checksum, exists := sums[imageId]; exists {
  368. return checksum, nil
  369. }
  370. img, err := srv.runtime.graph.Get(imageId)
  371. if err != nil {
  372. return "", err
  373. }
  374. if _, err := os.Stat(layerArchivePath(srv.runtime.graph.imageRoot(imageId))); err != nil {
  375. if os.IsNotExist(err) {
  376. // TODO: Ask the registry for the checksum
  377. // As the archive is not there, it is supposed to come from a pull.
  378. } else {
  379. return "", err
  380. }
  381. }
  382. checksum, err := img.Checksum()
  383. if err != nil {
  384. return "", err
  385. }
  386. return checksum, nil
  387. }
  388. // Retrieve the all the images to be uploaded in the correct order
  389. // Note: we can't use a map as it is not ordered
  390. func (srv *Server) getImageList(localRepo map[string]string) ([]*registry.ImgData, error) {
  391. var imgList []*registry.ImgData
  392. imageSet := make(map[string]struct{})
  393. for tag, id := range localRepo {
  394. img, err := srv.runtime.graph.Get(id)
  395. if err != nil {
  396. return nil, err
  397. }
  398. img.WalkHistory(func(img *Image) error {
  399. if _, exists := imageSet[img.Id]; exists {
  400. return nil
  401. }
  402. imageSet[img.Id] = struct{}{}
  403. checksum, err := srv.getChecksum(img.Id)
  404. if err != nil {
  405. return err
  406. }
  407. imgList = append([]*registry.ImgData{{
  408. Id: img.Id,
  409. Checksum: checksum,
  410. Tag: tag,
  411. }}, imgList...)
  412. return nil
  413. })
  414. }
  415. return imgList, nil
  416. }
  417. func (srv *Server) pushRepository(out io.Writer, name string, localRepo map[string]string) error {
  418. utils.FprintfFlush(out, "Processing checksums\n")
  419. imgList, err := srv.getImageList(localRepo)
  420. if err != nil {
  421. return err
  422. }
  423. utils.FprintfFlush(out, "Sending image list\n")
  424. repoData, err := srv.registry.PushImageJsonIndex(name, imgList, false)
  425. if err != nil {
  426. return err
  427. }
  428. // FIXME: Send only needed images
  429. for _, ep := range repoData.Endpoints {
  430. utils.FprintfFlush(out, "Pushing repository %s to %s (%d tags)\r\n", name, ep, len(localRepo))
  431. // For each image within the repo, push them
  432. for _, elem := range imgList {
  433. if _, exists := repoData.ImgList[elem.Id]; exists {
  434. utils.FprintfFlush(out, "Image %s already on registry, skipping\n", name)
  435. continue
  436. }
  437. if err := srv.pushImage(out, name, elem.Id, ep, repoData.Tokens); err != nil {
  438. // FIXME: Continue on error?
  439. return err
  440. }
  441. utils.FprintfFlush(out, "Pushing tags for rev [%s] on {%s}\n", elem.Id, ep+"/users/"+name+"/"+elem.Tag)
  442. if err := srv.registry.PushRegistryTag(name, elem.Id, elem.Tag, ep, repoData.Tokens); err != nil {
  443. return err
  444. }
  445. }
  446. }
  447. if _, err := srv.registry.PushImageJsonIndex(name, imgList, true); err != nil {
  448. return err
  449. }
  450. return nil
  451. }
  452. func (srv *Server) pushImage(out io.Writer, remote, imgId, ep string, token []string) error {
  453. jsonRaw, err := ioutil.ReadFile(path.Join(srv.runtime.graph.Root, imgId, "json"))
  454. if err != nil {
  455. return fmt.Errorf("Error while retreiving the path for {%s}: %s", imgId, err)
  456. }
  457. utils.FprintfFlush(out, "Pushing %s\r\n", imgId)
  458. // Make sure we have the image's checksum
  459. checksum, err := srv.getChecksum(imgId)
  460. if err != nil {
  461. return err
  462. }
  463. imgData := &registry.ImgData{
  464. Id: imgId,
  465. Checksum: checksum,
  466. }
  467. // Send the json
  468. if err := srv.registry.PushImageJsonRegistry(imgData, jsonRaw, ep, token); err != nil {
  469. if err == registry.ErrAlreadyExists {
  470. utils.FprintfFlush(out, "Image %s already uploaded ; skipping\n", imgData.Id)
  471. return nil
  472. }
  473. return err
  474. }
  475. // Retrieve the tarball to be sent
  476. var layerData *TempArchive
  477. // If the archive exists, use it
  478. file, err := os.Open(layerArchivePath(srv.runtime.graph.imageRoot(imgId)))
  479. if err != nil {
  480. if os.IsNotExist(err) {
  481. // If the archive does not exist, create one from the layer
  482. layerData, err = srv.runtime.graph.TempLayerArchive(imgId, Xz, out)
  483. if err != nil {
  484. return fmt.Errorf("Failed to generate layer archive: %s", err)
  485. }
  486. } else {
  487. return err
  488. }
  489. } else {
  490. defer file.Close()
  491. st, err := file.Stat()
  492. if err != nil {
  493. return err
  494. }
  495. layerData = &TempArchive{
  496. File: file,
  497. Size: st.Size(),
  498. }
  499. }
  500. // Send the layer
  501. if err := srv.registry.PushImageLayerRegistry(imgData.Id, utils.ProgressReader(layerData, int(layerData.Size), out, ""), ep, token); err != nil {
  502. return err
  503. }
  504. return nil
  505. }
  506. func (srv *Server) ImagePush(name, registry string, out io.Writer) error {
  507. img, err := srv.runtime.graph.Get(name)
  508. if err != nil {
  509. utils.FprintfFlush(out, "The push refers to a repository [%s] (len: %d)\n", name, len(srv.runtime.repositories.Repositories[name]))
  510. // If it fails, try to get the repository
  511. if localRepo, exists := srv.runtime.repositories.Repositories[name]; exists {
  512. if err := srv.pushRepository(out, name, localRepo); err != nil {
  513. return err
  514. }
  515. return nil
  516. }
  517. return err
  518. }
  519. utils.FprintfFlush(out, "The push refers to an image: [%s]\n", name)
  520. if err := srv.pushImage(out, name, img.Id, registry, nil); err != nil {
  521. return err
  522. }
  523. return nil
  524. }
  525. func (srv *Server) ImageImport(src, repo, tag string, in io.Reader, out io.Writer) error {
  526. var archive io.Reader
  527. var resp *http.Response
  528. if src == "-" {
  529. archive = in
  530. } else {
  531. u, err := url.Parse(src)
  532. if err != nil {
  533. utils.FprintfFlush(out, "Error: %s\n", err)
  534. }
  535. if u.Scheme == "" {
  536. u.Scheme = "http"
  537. u.Host = src
  538. u.Path = ""
  539. }
  540. utils.FprintfFlush(out, "Downloading from %s\n", u)
  541. // Download with curl (pretty progress bar)
  542. // If curl is not available, fallback to http.Get()
  543. resp, err = utils.Download(u.String(), out)
  544. if err != nil {
  545. return err
  546. }
  547. archive = utils.ProgressReader(resp.Body, int(resp.ContentLength), out, "Importing %v/%v (%v)")
  548. }
  549. img, err := srv.runtime.graph.Create(archive, nil, "Imported from "+src, "", nil)
  550. if err != nil {
  551. return err
  552. }
  553. // Optionally register the image at REPO/TAG
  554. if repo != "" {
  555. if err := srv.runtime.repositories.Set(repo, tag, img.Id, true); err != nil {
  556. return err
  557. }
  558. }
  559. utils.FprintfFlush(out, "%s\n", img.ShortId())
  560. return nil
  561. }
  562. func (srv *Server) ContainerCreate(config *Config) (string, error) {
  563. if config.Memory > 0 && !srv.runtime.capabilities.MemoryLimit {
  564. config.Memory = 0
  565. }
  566. if config.Memory > 0 && !srv.runtime.capabilities.SwapLimit {
  567. config.MemorySwap = -1
  568. }
  569. b := NewBuilder(srv.runtime)
  570. container, err := b.Create(config)
  571. if err != nil {
  572. if srv.runtime.graph.IsNotExist(err) {
  573. return "", fmt.Errorf("No such image: %s", config.Image)
  574. }
  575. return "", err
  576. }
  577. return container.ShortId(), nil
  578. }
  579. func (srv *Server) ImageCreateFromFile(dockerfile io.Reader, out io.Writer) error {
  580. img, err := NewBuilder(srv.runtime).Build(dockerfile, out)
  581. if err != nil {
  582. return err
  583. }
  584. fmt.Fprintf(out, "%s\n", img.ShortId())
  585. return nil
  586. }
  587. func (srv *Server) ContainerRestart(name string, t int) error {
  588. if container := srv.runtime.Get(name); container != nil {
  589. if err := container.Restart(t); err != nil {
  590. return fmt.Errorf("Error restarting container %s: %s", name, err.Error())
  591. }
  592. } else {
  593. return fmt.Errorf("No such container: %s", name)
  594. }
  595. return nil
  596. }
  597. func (srv *Server) ContainerDestroy(name string, removeVolume bool) error {
  598. if container := srv.runtime.Get(name); container != nil {
  599. volumes := make(map[string]struct{})
  600. // Store all the deleted containers volumes
  601. for _, volumeId := range container.Volumes {
  602. volumes[volumeId] = struct{}{}
  603. }
  604. if err := srv.runtime.Destroy(container); err != nil {
  605. return fmt.Errorf("Error destroying container %s: %s", name, err.Error())
  606. }
  607. if removeVolume {
  608. // Retrieve all volumes from all remaining containers
  609. usedVolumes := make(map[string]*Container)
  610. for _, container := range srv.runtime.List() {
  611. for _, containerVolumeId := range container.Volumes {
  612. usedVolumes[containerVolumeId] = container
  613. }
  614. }
  615. for volumeId := range volumes {
  616. // If the requested volu
  617. if c, exists := usedVolumes[volumeId]; exists {
  618. log.Printf("The volume %s is used by the container %s. Impossible to remove it. Skipping.\n", volumeId, c.Id)
  619. continue
  620. }
  621. if err := srv.runtime.volumes.Delete(volumeId); err != nil {
  622. return err
  623. }
  624. }
  625. }
  626. } else {
  627. return fmt.Errorf("No such container: %s", name)
  628. }
  629. return nil
  630. }
  631. func (srv *Server) ImageDelete(name string) error {
  632. img, err := srv.runtime.repositories.LookupImage(name)
  633. if err != nil {
  634. return fmt.Errorf("No such image: %s", name)
  635. } else {
  636. if err := srv.runtime.graph.Delete(img.Id); err != nil {
  637. return fmt.Errorf("Error deleting image %s: %s", name, err.Error())
  638. }
  639. }
  640. return nil
  641. }
  642. func (srv *Server) ContainerStart(name string) error {
  643. if container := srv.runtime.Get(name); container != nil {
  644. if err := container.Start(); err != nil {
  645. return fmt.Errorf("Error starting container %s: %s", name, err.Error())
  646. }
  647. } else {
  648. return fmt.Errorf("No such container: %s", name)
  649. }
  650. return nil
  651. }
  652. func (srv *Server) ContainerStop(name string, t int) error {
  653. if container := srv.runtime.Get(name); container != nil {
  654. if err := container.Stop(t); err != nil {
  655. return fmt.Errorf("Error stopping container %s: %s", name, err.Error())
  656. }
  657. } else {
  658. return fmt.Errorf("No such container: %s", name)
  659. }
  660. return nil
  661. }
  662. func (srv *Server) ContainerWait(name string) (int, error) {
  663. if container := srv.runtime.Get(name); container != nil {
  664. return container.Wait(), nil
  665. }
  666. return 0, fmt.Errorf("No such container: %s", name)
  667. }
  668. func (srv *Server) ContainerAttach(name string, logs, stream, stdin, stdout, stderr bool, in io.ReadCloser, out io.Writer) error {
  669. container := srv.runtime.Get(name)
  670. if container == nil {
  671. return fmt.Errorf("No such container: %s", name)
  672. }
  673. //logs
  674. if logs {
  675. if stdout {
  676. cLog, err := container.ReadLog("stdout")
  677. if err != nil {
  678. utils.Debugf(err.Error())
  679. } else if _, err := io.Copy(out, cLog); err != nil {
  680. utils.Debugf(err.Error())
  681. }
  682. }
  683. if stderr {
  684. cLog, err := container.ReadLog("stderr")
  685. if err != nil {
  686. utils.Debugf(err.Error())
  687. } else if _, err := io.Copy(out, cLog); err != nil {
  688. utils.Debugf(err.Error())
  689. }
  690. }
  691. }
  692. //stream
  693. if stream {
  694. if container.State.Ghost {
  695. return fmt.Errorf("Impossible to attach to a ghost container")
  696. }
  697. var (
  698. cStdin io.ReadCloser
  699. cStdout, cStderr io.Writer
  700. cStdinCloser io.Closer
  701. )
  702. if stdin {
  703. r, w := io.Pipe()
  704. go func() {
  705. defer w.Close()
  706. defer utils.Debugf("Closing buffered stdin pipe")
  707. io.Copy(w, in)
  708. }()
  709. cStdin = r
  710. cStdinCloser = in
  711. }
  712. if stdout {
  713. cStdout = out
  714. }
  715. if stderr {
  716. cStderr = out
  717. }
  718. <-container.Attach(cStdin, cStdinCloser, cStdout, cStderr)
  719. // If we are in stdinonce mode, wait for the process to end
  720. // otherwise, simply return
  721. if container.Config.StdinOnce && !container.Config.Tty {
  722. container.Wait()
  723. }
  724. }
  725. return nil
  726. }
  727. func (srv *Server) ContainerInspect(name string) (*Container, error) {
  728. if container := srv.runtime.Get(name); container != nil {
  729. return container, nil
  730. }
  731. return nil, fmt.Errorf("No such container: %s", name)
  732. }
  733. func (srv *Server) ImageInspect(name string) (*Image, error) {
  734. if image, err := srv.runtime.repositories.LookupImage(name); err == nil && image != nil {
  735. return image, nil
  736. }
  737. return nil, fmt.Errorf("No such image: %s", name)
  738. }
  739. func NewServer(autoRestart bool) (*Server, error) {
  740. if runtime.GOARCH != "amd64" {
  741. log.Fatalf("The docker runtime currently only supports amd64 (not %s). This will change in the future. Aborting.", runtime.GOARCH)
  742. }
  743. runtime, err := NewRuntime(autoRestart)
  744. if err != nil {
  745. return nil, err
  746. }
  747. srv := &Server{
  748. runtime: runtime,
  749. registry: registry.NewRegistry(runtime.root),
  750. }
  751. runtime.srv = srv
  752. return srv, nil
  753. }
  754. type Server struct {
  755. runtime *Runtime
  756. registry *registry.Registry
  757. }