server.go 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076
  1. package docker
  2. import (
  3. "errors"
  4. "fmt"
  5. "github.com/dotcloud/docker/auth"
  6. "github.com/dotcloud/docker/registry"
  7. "github.com/dotcloud/docker/utils"
  8. "io"
  9. "io/ioutil"
  10. "log"
  11. "net/http"
  12. "net/url"
  13. "os"
  14. "path"
  15. "runtime"
  16. "strings"
  17. "sync"
  18. )
  19. func (srv *Server) DockerVersion() APIVersion {
  20. return APIVersion{
  21. Version: VERSION,
  22. GitCommit: GITCOMMIT,
  23. GoVersion: runtime.Version(),
  24. }
  25. }
  26. func (srv *Server) ContainerKill(name string) error {
  27. if container := srv.runtime.Get(name); container != nil {
  28. if err := container.Kill(); err != nil {
  29. return fmt.Errorf("Error restarting container %s: %s", name, err.Error())
  30. }
  31. } else {
  32. return fmt.Errorf("No such container: %s", name)
  33. }
  34. return nil
  35. }
  36. func (srv *Server) ContainerExport(name string, out io.Writer) error {
  37. if container := srv.runtime.Get(name); container != nil {
  38. data, err := container.Export()
  39. if err != nil {
  40. return err
  41. }
  42. // Stream the entire contents of the container (basically a volatile snapshot)
  43. if _, err := io.Copy(out, data); err != nil {
  44. return err
  45. }
  46. return nil
  47. }
  48. return fmt.Errorf("No such container: %s", name)
  49. }
  50. func (srv *Server) ImagesSearch(term string) ([]APISearch, error) {
  51. r, err := registry.NewRegistry(srv.runtime.root, nil)
  52. if err != nil {
  53. return nil, err
  54. }
  55. results, err := r.SearchRepositories(term)
  56. if err != nil {
  57. return nil, err
  58. }
  59. var outs []APISearch
  60. for _, repo := range results.Results {
  61. var out APISearch
  62. out.Description = repo["description"]
  63. out.Name = repo["name"]
  64. outs = append(outs, out)
  65. }
  66. return outs, nil
  67. }
  68. func (srv *Server) ImageInsert(name, url, path string, out io.Writer, sf *utils.StreamFormatter) (string, error) {
  69. out = utils.NewWriteFlusher(out)
  70. img, err := srv.runtime.repositories.LookupImage(name)
  71. if err != nil {
  72. return "", err
  73. }
  74. file, err := utils.Download(url, out)
  75. if err != nil {
  76. return "", err
  77. }
  78. defer file.Body.Close()
  79. config, _, err := ParseRun([]string{img.ID, "echo", "insert", url, path}, srv.runtime.capabilities)
  80. if err != nil {
  81. return "", err
  82. }
  83. b := NewBuilder(srv.runtime)
  84. c, err := b.Create(config)
  85. if err != nil {
  86. return "", err
  87. }
  88. if err := c.Inject(utils.ProgressReader(file.Body, int(file.ContentLength), out, sf.FormatProgress("Downloading", "%v/%v (%v)"), sf), path); err != nil {
  89. return "", err
  90. }
  91. // FIXME: Handle custom repo, tag comment, author
  92. img, err = b.Commit(c, "", "", img.Comment, img.Author, nil)
  93. if err != nil {
  94. return "", err
  95. }
  96. out.Write(sf.FormatStatus(img.ID))
  97. return img.ShortID(), nil
  98. }
  99. func (srv *Server) ImagesViz(out io.Writer) error {
  100. images, _ := srv.runtime.graph.All()
  101. if images == nil {
  102. return nil
  103. }
  104. out.Write([]byte("digraph docker {\n"))
  105. var (
  106. parentImage *Image
  107. err error
  108. )
  109. for _, image := range images {
  110. parentImage, err = image.GetParent()
  111. if err != nil {
  112. return fmt.Errorf("Error while getting parent image: %v", err)
  113. }
  114. if parentImage != nil {
  115. out.Write([]byte(" \"" + parentImage.ShortID() + "\" -> \"" + image.ShortID() + "\"\n"))
  116. } else {
  117. out.Write([]byte(" base -> \"" + image.ShortID() + "\" [style=invis]\n"))
  118. }
  119. }
  120. reporefs := make(map[string][]string)
  121. for name, repository := range srv.runtime.repositories.Repositories {
  122. for tag, id := range repository {
  123. reporefs[utils.TruncateID(id)] = append(reporefs[utils.TruncateID(id)], fmt.Sprintf("%s:%s", name, tag))
  124. }
  125. }
  126. for id, repos := range reporefs {
  127. out.Write([]byte(" \"" + id + "\" [label=\"" + id + "\\n" + strings.Join(repos, "\\n") + "\",shape=box,fillcolor=\"paleturquoise\",style=\"filled,rounded\"];\n"))
  128. }
  129. out.Write([]byte(" base [style=invisible]\n}\n"))
  130. return nil
  131. }
  132. func (srv *Server) Images(all bool, filter string) ([]APIImages, error) {
  133. var (
  134. allImages map[string]*Image
  135. err error
  136. )
  137. if all {
  138. allImages, err = srv.runtime.graph.Map()
  139. } else {
  140. allImages, err = srv.runtime.graph.Heads()
  141. }
  142. if err != nil {
  143. return nil, err
  144. }
  145. outs := []APIImages{} //produce [] when empty instead of 'null'
  146. for name, repository := range srv.runtime.repositories.Repositories {
  147. if filter != "" && name != filter {
  148. continue
  149. }
  150. for tag, id := range repository {
  151. var out APIImages
  152. image, err := srv.runtime.graph.Get(id)
  153. if err != nil {
  154. log.Printf("Warning: couldn't load %s from %s/%s: %s", id, name, tag, err)
  155. continue
  156. }
  157. delete(allImages, id)
  158. out.Repository = name
  159. out.Tag = tag
  160. out.ID = image.ID
  161. out.Created = image.Created.Unix()
  162. out.Size = image.Size
  163. out.VirtualSize = image.getParentsSize(0) + image.Size
  164. outs = append(outs, out)
  165. }
  166. }
  167. // Display images which aren't part of a
  168. if filter == "" {
  169. for _, image := range allImages {
  170. var out APIImages
  171. out.ID = image.ID
  172. out.Created = image.Created.Unix()
  173. out.Size = image.Size
  174. out.VirtualSize = image.getParentsSize(0) + image.Size
  175. outs = append(outs, out)
  176. }
  177. }
  178. return outs, nil
  179. }
  180. func (srv *Server) DockerInfo() *APIInfo {
  181. images, _ := srv.runtime.graph.All()
  182. var imgcount int
  183. if images == nil {
  184. imgcount = 0
  185. } else {
  186. imgcount = len(images)
  187. }
  188. return &APIInfo{
  189. Containers: len(srv.runtime.List()),
  190. Images: imgcount,
  191. MemoryLimit: srv.runtime.capabilities.MemoryLimit,
  192. SwapLimit: srv.runtime.capabilities.SwapLimit,
  193. Debug: os.Getenv("DEBUG") != "",
  194. NFd: utils.GetTotalUsedFds(),
  195. NGoroutines: runtime.NumGoroutine(),
  196. }
  197. }
  198. func (srv *Server) ImageHistory(name string) ([]APIHistory, error) {
  199. image, err := srv.runtime.repositories.LookupImage(name)
  200. if err != nil {
  201. return nil, err
  202. }
  203. lookupMap := make(map[string][]string)
  204. for name, repository := range srv.runtime.repositories.Repositories {
  205. for tag, id := range repository {
  206. // If the ID already has a reverse lookup, do not update it unless for "latest"
  207. if _, exists := lookupMap[id]; !exists {
  208. lookupMap[id] = []string{}
  209. }
  210. lookupMap[id] = append(lookupMap[id], name+":"+tag)
  211. }
  212. }
  213. outs := []APIHistory{} //produce [] when empty instead of 'null'
  214. err = image.WalkHistory(func(img *Image) error {
  215. var out APIHistory
  216. out.ID = srv.runtime.repositories.ImageName(img.ShortID())
  217. out.Created = img.Created.Unix()
  218. out.CreatedBy = strings.Join(img.ContainerConfig.Cmd, " ")
  219. out.Tags = lookupMap[img.ID]
  220. outs = append(outs, out)
  221. return nil
  222. })
  223. return outs, nil
  224. }
  225. func (srv *Server) ContainerChanges(name string) ([]Change, error) {
  226. if container := srv.runtime.Get(name); container != nil {
  227. return container.Changes()
  228. }
  229. return nil, fmt.Errorf("No such container: %s", name)
  230. }
  231. func (srv *Server) Containers(all bool, n int, since, before string) []APIContainers {
  232. var foundBefore bool
  233. var displayed int
  234. retContainers := []APIContainers{}
  235. for _, container := range srv.runtime.List() {
  236. if !container.State.Running && !all && n == -1 && since == "" && before == "" {
  237. continue
  238. }
  239. if before != "" {
  240. if container.ShortID() == before {
  241. foundBefore = true
  242. continue
  243. }
  244. if !foundBefore {
  245. continue
  246. }
  247. }
  248. if displayed == n {
  249. break
  250. }
  251. if container.ShortID() == since {
  252. break
  253. }
  254. displayed++
  255. c := APIContainers{
  256. ID: container.ID,
  257. }
  258. c.Image = srv.runtime.repositories.ImageName(container.Image)
  259. c.Command = fmt.Sprintf("%s %s", container.Path, strings.Join(container.Args, " "))
  260. c.Created = container.Created.Unix()
  261. c.Status = container.State.String()
  262. c.Ports = container.NetworkSettings.PortMappingHuman()
  263. c.SizeRw, c.SizeRootFs = container.GetSize()
  264. retContainers = append(retContainers, c)
  265. }
  266. return retContainers
  267. }
  268. func (srv *Server) ContainerCommit(name, repo, tag, author, comment string, config *Config) (string, error) {
  269. container := srv.runtime.Get(name)
  270. if container == nil {
  271. return "", fmt.Errorf("No such container: %s", name)
  272. }
  273. img, err := NewBuilder(srv.runtime).Commit(container, repo, tag, comment, author, config)
  274. if err != nil {
  275. return "", err
  276. }
  277. return img.ShortID(), err
  278. }
  279. func (srv *Server) ContainerTag(name, repo, tag string, force bool) error {
  280. if err := srv.runtime.repositories.Set(repo, tag, name, force); err != nil {
  281. return err
  282. }
  283. return nil
  284. }
  285. func (srv *Server) pullImage(r *registry.Registry, out io.Writer, imgId, endpoint string, token []string, sf *utils.StreamFormatter) error {
  286. history, err := r.GetRemoteHistory(imgId, endpoint, token)
  287. if err != nil {
  288. return err
  289. }
  290. // FIXME: Try to stream the images?
  291. // FIXME: Launch the getRemoteImage() in goroutines
  292. for _, id := range history {
  293. if !srv.runtime.graph.Exists(id) {
  294. out.Write(sf.FormatStatus("Pulling %s metadata", id))
  295. imgJSON, imgSize, err := r.GetRemoteImageJSON(id, endpoint, token)
  296. if err != nil {
  297. // FIXME: Keep goging in case of error?
  298. return err
  299. }
  300. img, err := NewImgJSON(imgJSON)
  301. if err != nil {
  302. return fmt.Errorf("Failed to parse json: %s", err)
  303. }
  304. // Get the layer
  305. out.Write(sf.FormatStatus("Pulling %s fs layer", id))
  306. layer, err := r.GetRemoteImageLayer(img.ID, endpoint, token)
  307. if err != nil {
  308. return err
  309. }
  310. defer layer.Close()
  311. if err := srv.runtime.graph.Register(utils.ProgressReader(layer, imgSize, out, sf.FormatProgress("Downloading", "%v/%v (%v)"), sf), false, img); err != nil {
  312. return err
  313. }
  314. }
  315. }
  316. return nil
  317. }
  318. func (srv *Server) pullRepository(r *registry.Registry, out io.Writer, local, remote, askedTag string, sf *utils.StreamFormatter) error {
  319. out.Write(sf.FormatStatus("Pulling repository %s from %s", local, auth.IndexServerAddress()))
  320. repoData, err := r.GetRepositoryData(remote)
  321. if err != nil {
  322. return err
  323. }
  324. utils.Debugf("Updating checksums")
  325. // Reload the json file to make sure not to overwrite faster sums
  326. if err := srv.runtime.graph.UpdateChecksums(repoData.ImgList); err != nil {
  327. return err
  328. }
  329. utils.Debugf("Retrieving the tag list")
  330. tagsList, err := r.GetRemoteTags(repoData.Endpoints, remote, repoData.Tokens)
  331. if err != nil {
  332. return err
  333. }
  334. utils.Debugf("Registering tags")
  335. // If not specific tag have been asked, take all
  336. if askedTag == "" {
  337. for tag, id := range tagsList {
  338. repoData.ImgList[id].Tag = tag
  339. }
  340. } else {
  341. // Otherwise, check that the tag exists and use only that one
  342. id, exists := tagsList[askedTag]
  343. if !exists {
  344. return fmt.Errorf("Tag %s not found in repositoy %s", askedTag, local)
  345. }
  346. repoData.ImgList[id].Tag = askedTag
  347. }
  348. for _, img := range repoData.ImgList {
  349. if askedTag != "" && img.Tag != askedTag {
  350. utils.Debugf("(%s) does not match %s (id: %s), skipping", img.Tag, askedTag, img.ID)
  351. continue
  352. }
  353. out.Write(sf.FormatStatus("Pulling image %s (%s) from %s", img.ID, img.Tag, remote))
  354. success := false
  355. for _, ep := range repoData.Endpoints {
  356. if err := srv.pullImage(r, out, img.ID, "https://"+ep+"/v1", repoData.Tokens, sf); err != nil {
  357. out.Write(sf.FormatStatus("Error while retrieving image for tag: %s (%s); checking next endpoint", askedTag, err))
  358. continue
  359. }
  360. success = true
  361. break
  362. }
  363. if !success {
  364. return fmt.Errorf("Could not find repository on any of the indexed registries.")
  365. }
  366. }
  367. for tag, id := range tagsList {
  368. if askedTag != "" && tag != askedTag {
  369. continue
  370. }
  371. if err := srv.runtime.repositories.Set(local, tag, id, true); err != nil {
  372. return err
  373. }
  374. }
  375. if err := srv.runtime.repositories.Save(); err != nil {
  376. return err
  377. }
  378. return nil
  379. }
  380. func (srv *Server) poolAdd(kind, key string) error {
  381. srv.lock.Lock()
  382. defer srv.lock.Unlock()
  383. if _, exists := srv.pullingPool[key]; exists {
  384. return fmt.Errorf("%s %s is already in progress", key, kind)
  385. }
  386. switch kind {
  387. case "pull":
  388. srv.pullingPool[key] = struct{}{}
  389. break
  390. case "push":
  391. srv.pushingPool[key] = struct{}{}
  392. break
  393. default:
  394. return fmt.Errorf("Unkown pool type")
  395. }
  396. return nil
  397. }
  398. func (srv *Server) poolRemove(kind, key string) error {
  399. switch kind {
  400. case "pull":
  401. delete(srv.pullingPool, key)
  402. break
  403. case "push":
  404. delete(srv.pushingPool, key)
  405. break
  406. default:
  407. return fmt.Errorf("Unkown pool type")
  408. }
  409. return nil
  410. }
  411. func (srv *Server) ImagePull(name, tag, endpoint string, out io.Writer, sf *utils.StreamFormatter, authConfig *auth.AuthConfig) error {
  412. r, err := registry.NewRegistry(srv.runtime.root, authConfig)
  413. if err != nil {
  414. return err
  415. }
  416. if err := srv.poolAdd("pull", name+":"+tag); err != nil {
  417. return err
  418. }
  419. defer srv.poolRemove("pull", name+":"+tag)
  420. out = utils.NewWriteFlusher(out)
  421. if endpoint != "" {
  422. if err := srv.pullImage(r, out, name, endpoint, nil, sf); err != nil {
  423. return err
  424. }
  425. return nil
  426. }
  427. remote := name
  428. parts := strings.Split(name, "/")
  429. if len(parts) > 2 {
  430. remote = fmt.Sprintf("src/%s", url.QueryEscape(strings.Join(parts, "/")))
  431. }
  432. if err := srv.pullRepository(r, out, name, remote, tag, sf); err != nil {
  433. return err
  434. }
  435. return nil
  436. }
  437. // Retrieve the checksum of an image
  438. // Priority:
  439. // - Check on the stored checksums
  440. // - Check if the archive exists, if it does not, ask the registry
  441. // - If the archive does exists, process the checksum from it
  442. // - If the archive does not exists and not found on registry, process checksum from layer
  443. func (srv *Server) getChecksum(imageId string) (string, error) {
  444. // FIXME: Use in-memory map instead of reading the file each time
  445. if sums, err := srv.runtime.graph.getStoredChecksums(); err != nil {
  446. return "", err
  447. } else if checksum, exists := sums[imageId]; exists {
  448. return checksum, nil
  449. }
  450. img, err := srv.runtime.graph.Get(imageId)
  451. if err != nil {
  452. return "", err
  453. }
  454. if _, err := os.Stat(layerArchivePath(srv.runtime.graph.imageRoot(imageId))); err != nil {
  455. if os.IsNotExist(err) {
  456. // TODO: Ask the registry for the checksum
  457. // As the archive is not there, it is supposed to come from a pull.
  458. } else {
  459. return "", err
  460. }
  461. }
  462. checksum, err := img.Checksum()
  463. if err != nil {
  464. return "", err
  465. }
  466. return checksum, nil
  467. }
  468. // Retrieve the all the images to be uploaded in the correct order
  469. // Note: we can't use a map as it is not ordered
  470. func (srv *Server) getImageList(localRepo map[string]string) ([]*registry.ImgData, error) {
  471. var imgList []*registry.ImgData
  472. imageSet := make(map[string]struct{})
  473. for tag, id := range localRepo {
  474. img, err := srv.runtime.graph.Get(id)
  475. if err != nil {
  476. return nil, err
  477. }
  478. img.WalkHistory(func(img *Image) error {
  479. if _, exists := imageSet[img.ID]; exists {
  480. return nil
  481. }
  482. imageSet[img.ID] = struct{}{}
  483. checksum, err := srv.getChecksum(img.ID)
  484. if err != nil {
  485. return err
  486. }
  487. imgList = append([]*registry.ImgData{{
  488. ID: img.ID,
  489. Checksum: checksum,
  490. Tag: tag,
  491. }}, imgList...)
  492. return nil
  493. })
  494. }
  495. return imgList, nil
  496. }
  497. func (srv *Server) pushRepository(r *registry.Registry, out io.Writer, name string, localRepo map[string]string, sf *utils.StreamFormatter) error {
  498. out = utils.NewWriteFlusher(out)
  499. out.Write(sf.FormatStatus("Processing checksums"))
  500. imgList, err := srv.getImageList(localRepo)
  501. if err != nil {
  502. return err
  503. }
  504. out.Write(sf.FormatStatus("Sending image list"))
  505. srvName := name
  506. parts := strings.Split(name, "/")
  507. if len(parts) > 2 {
  508. srvName = fmt.Sprintf("src/%s", url.QueryEscape(strings.Join(parts, "/")))
  509. }
  510. repoData, err := r.PushImageJSONIndex(srvName, imgList, false, nil)
  511. if err != nil {
  512. return err
  513. }
  514. for _, ep := range repoData.Endpoints {
  515. out.Write(sf.FormatStatus("Pushing repository %s to %s (%d tags)", name, ep, len(localRepo)))
  516. // For each image within the repo, push them
  517. for _, elem := range imgList {
  518. if _, exists := repoData.ImgList[elem.ID]; exists {
  519. out.Write(sf.FormatStatus("Image %s already on registry, skipping", name))
  520. continue
  521. }
  522. if err := srv.pushImage(r, out, name, elem.ID, ep, repoData.Tokens, sf); err != nil {
  523. // FIXME: Continue on error?
  524. return err
  525. }
  526. out.Write(sf.FormatStatus("Pushing tags for rev [%s] on {%s}", elem.ID, ep+"/repositories/"+srvName+"/tags/"+elem.Tag))
  527. if err := r.PushRegistryTag(srvName, elem.ID, elem.Tag, ep, repoData.Tokens); err != nil {
  528. return err
  529. }
  530. }
  531. }
  532. if _, err := r.PushImageJSONIndex(srvName, imgList, true, repoData.Endpoints); err != nil {
  533. return err
  534. }
  535. return nil
  536. }
  537. func (srv *Server) pushImage(r *registry.Registry, out io.Writer, remote, imgId, ep string, token []string, sf *utils.StreamFormatter) error {
  538. out = utils.NewWriteFlusher(out)
  539. jsonRaw, err := ioutil.ReadFile(path.Join(srv.runtime.graph.Root, imgId, "json"))
  540. if err != nil {
  541. return fmt.Errorf("Error while retreiving the path for {%s}: %s", imgId, err)
  542. }
  543. out.Write(sf.FormatStatus("Pushing %s", imgId))
  544. // Make sure we have the image's checksum
  545. checksum, err := srv.getChecksum(imgId)
  546. if err != nil {
  547. return err
  548. }
  549. imgData := &registry.ImgData{
  550. ID: imgId,
  551. Checksum: checksum,
  552. }
  553. // Send the json
  554. if err := r.PushImageJSONRegistry(imgData, jsonRaw, ep, token); err != nil {
  555. if err == registry.ErrAlreadyExists {
  556. out.Write(sf.FormatStatus("Image %s already uploaded ; skipping", imgData.ID))
  557. return nil
  558. }
  559. return err
  560. }
  561. // Retrieve the tarball to be sent
  562. var layerData *TempArchive
  563. // If the archive exists, use it
  564. file, err := os.Open(layerArchivePath(srv.runtime.graph.imageRoot(imgId)))
  565. if err != nil {
  566. if os.IsNotExist(err) {
  567. // If the archive does not exist, create one from the layer
  568. layerData, err = srv.runtime.graph.TempLayerArchive(imgId, Xz, out)
  569. if err != nil {
  570. return fmt.Errorf("Failed to generate layer archive: %s", err)
  571. }
  572. } else {
  573. return err
  574. }
  575. } else {
  576. defer file.Close()
  577. st, err := file.Stat()
  578. if err != nil {
  579. return err
  580. }
  581. layerData = &TempArchive{
  582. File: file,
  583. Size: st.Size(),
  584. }
  585. }
  586. // Send the layer
  587. if err := r.PushImageLayerRegistry(imgData.ID, utils.ProgressReader(layerData, int(layerData.Size), out, sf.FormatProgress("Pushing", "%v/%v (%v)"), sf), ep, token); err != nil {
  588. return err
  589. }
  590. return nil
  591. }
  592. // FIXME: Allow to interupt current push when new push of same image is done.
  593. func (srv *Server) ImagePush(name, endpoint string, out io.Writer, sf *utils.StreamFormatter, authConfig *auth.AuthConfig) error {
  594. if err := srv.poolAdd("push", name); err != nil {
  595. return err
  596. }
  597. defer srv.poolRemove("push", name)
  598. out = utils.NewWriteFlusher(out)
  599. img, err := srv.runtime.graph.Get(name)
  600. r, err2 := registry.NewRegistry(srv.runtime.root, authConfig)
  601. if err2 != nil {
  602. return err2
  603. }
  604. if err != nil {
  605. out.Write(sf.FormatStatus("The push refers to a repository [%s] (len: %d)", name, len(srv.runtime.repositories.Repositories[name])))
  606. // If it fails, try to get the repository
  607. if localRepo, exists := srv.runtime.repositories.Repositories[name]; exists {
  608. if err := srv.pushRepository(r, out, name, localRepo, sf); err != nil {
  609. return err
  610. }
  611. return nil
  612. }
  613. return err
  614. }
  615. out.Write(sf.FormatStatus("The push refers to an image: [%s]", name))
  616. if err := srv.pushImage(r, out, name, img.ID, endpoint, nil, sf); err != nil {
  617. return err
  618. }
  619. return nil
  620. }
  621. func (srv *Server) ImageImport(src, repo, tag string, in io.Reader, out io.Writer, sf *utils.StreamFormatter) error {
  622. var archive io.Reader
  623. var resp *http.Response
  624. if src == "-" {
  625. archive = in
  626. } else {
  627. u, err := url.Parse(src)
  628. if err != nil {
  629. return err
  630. }
  631. if u.Scheme == "" {
  632. u.Scheme = "http"
  633. u.Host = src
  634. u.Path = ""
  635. }
  636. out.Write(sf.FormatStatus("Downloading from %s", u))
  637. // Download with curl (pretty progress bar)
  638. // If curl is not available, fallback to http.Get()
  639. resp, err = utils.Download(u.String(), out)
  640. if err != nil {
  641. return err
  642. }
  643. archive = utils.ProgressReader(resp.Body, int(resp.ContentLength), out, sf.FormatProgress("Importing", "%v/%v (%v)"), sf)
  644. }
  645. img, err := srv.runtime.graph.Create(archive, nil, "Imported from "+src, "", nil)
  646. if err != nil {
  647. return err
  648. }
  649. // Optionally register the image at REPO/TAG
  650. if repo != "" {
  651. if err := srv.runtime.repositories.Set(repo, tag, img.ID, true); err != nil {
  652. return err
  653. }
  654. }
  655. out.Write(sf.FormatStatus(img.ShortID()))
  656. return nil
  657. }
  658. func (srv *Server) ContainerCreate(config *Config) (string, error) {
  659. if config.Memory != 0 && config.Memory < 524288 {
  660. return "", fmt.Errorf("Memory limit must be given in bytes (minimum 524288 bytes)")
  661. }
  662. if config.Memory > 0 && !srv.runtime.capabilities.MemoryLimit {
  663. config.Memory = 0
  664. }
  665. if config.Memory > 0 && !srv.runtime.capabilities.SwapLimit {
  666. config.MemorySwap = -1
  667. }
  668. b := NewBuilder(srv.runtime)
  669. container, err := b.Create(config)
  670. if err != nil {
  671. if srv.runtime.graph.IsNotExist(err) {
  672. return "", fmt.Errorf("No such image: %s", config.Image)
  673. }
  674. return "", err
  675. }
  676. return container.ShortID(), nil
  677. }
  678. func (srv *Server) ContainerRestart(name string, t int) error {
  679. if container := srv.runtime.Get(name); container != nil {
  680. if err := container.Restart(t); err != nil {
  681. return fmt.Errorf("Error restarting container %s: %s", name, err.Error())
  682. }
  683. } else {
  684. return fmt.Errorf("No such container: %s", name)
  685. }
  686. return nil
  687. }
  688. func (srv *Server) ContainerDestroy(name string, removeVolume bool) error {
  689. if container := srv.runtime.Get(name); container != nil {
  690. if container.State.Running {
  691. return fmt.Errorf("Impossible to remove a running container, please stop it first")
  692. }
  693. volumes := make(map[string]struct{})
  694. // Store all the deleted containers volumes
  695. for _, volumeId := range container.Volumes {
  696. volumes[volumeId] = struct{}{}
  697. }
  698. if err := srv.runtime.Destroy(container); err != nil {
  699. return fmt.Errorf("Error destroying container %s: %s", name, err.Error())
  700. }
  701. if removeVolume {
  702. // Retrieve all volumes from all remaining containers
  703. usedVolumes := make(map[string]*Container)
  704. for _, container := range srv.runtime.List() {
  705. for _, containerVolumeId := range container.Volumes {
  706. usedVolumes[containerVolumeId] = container
  707. }
  708. }
  709. for volumeId := range volumes {
  710. // If the requested volu
  711. if c, exists := usedVolumes[volumeId]; exists {
  712. log.Printf("The volume %s is used by the container %s. Impossible to remove it. Skipping.\n", volumeId, c.ID)
  713. continue
  714. }
  715. if err := srv.runtime.volumes.Delete(volumeId); err != nil {
  716. return err
  717. }
  718. }
  719. }
  720. } else {
  721. return fmt.Errorf("No such container: %s", name)
  722. }
  723. return nil
  724. }
  725. var ErrImageReferenced = errors.New("Image referenced by a repository")
  726. func (srv *Server) deleteImageAndChildren(id string, imgs *[]APIRmi) error {
  727. // If the image is referenced by a repo, do not delete
  728. if len(srv.runtime.repositories.ByID()[id]) != 0 {
  729. return ErrImageReferenced
  730. }
  731. // If the image is not referenced but has children, go recursive
  732. referenced := false
  733. byParents, err := srv.runtime.graph.ByParent()
  734. if err != nil {
  735. return err
  736. }
  737. for _, img := range byParents[id] {
  738. if err := srv.deleteImageAndChildren(img.ID, imgs); err != nil {
  739. if err != ErrImageReferenced {
  740. return err
  741. }
  742. referenced = true
  743. }
  744. }
  745. if referenced {
  746. return ErrImageReferenced
  747. }
  748. // If the image is not referenced and has no children, remove it
  749. byParents, err = srv.runtime.graph.ByParent()
  750. if err != nil {
  751. return err
  752. }
  753. if len(byParents[id]) == 0 {
  754. if err := srv.runtime.repositories.DeleteAll(id); err != nil {
  755. return err
  756. }
  757. err := srv.runtime.graph.Delete(id)
  758. if err != nil {
  759. return err
  760. }
  761. *imgs = append(*imgs, APIRmi{Deleted: utils.TruncateID(id)})
  762. return nil
  763. }
  764. return nil
  765. }
  766. func (srv *Server) deleteImageParents(img *Image, imgs *[]APIRmi) error {
  767. if img.Parent != "" {
  768. parent, err := srv.runtime.graph.Get(img.Parent)
  769. if err != nil {
  770. return err
  771. }
  772. // Remove all children images
  773. if err := srv.deleteImageAndChildren(img.Parent, imgs); err != nil {
  774. return err
  775. }
  776. return srv.deleteImageParents(parent, imgs)
  777. }
  778. return nil
  779. }
  780. func (srv *Server) deleteImage(img *Image, repoName, tag string) (*[]APIRmi, error) {
  781. //Untag the current image
  782. var imgs []APIRmi
  783. tagDeleted, err := srv.runtime.repositories.Delete(repoName, tag)
  784. if err != nil {
  785. return nil, err
  786. }
  787. if tagDeleted {
  788. imgs = append(imgs, APIRmi{Untagged: img.ShortID()})
  789. }
  790. if len(srv.runtime.repositories.ByID()[img.ID]) == 0 {
  791. if err := srv.deleteImageAndChildren(img.ID, &imgs); err != nil {
  792. if err != ErrImageReferenced {
  793. return &imgs, err
  794. }
  795. } else if err := srv.deleteImageParents(img, &imgs); err != nil {
  796. if err != ErrImageReferenced {
  797. return &imgs, err
  798. }
  799. }
  800. }
  801. return &imgs, nil
  802. }
  803. func (srv *Server) ImageDelete(name string, autoPrune bool) (*[]APIRmi, error) {
  804. img, err := srv.runtime.repositories.LookupImage(name)
  805. if err != nil {
  806. return nil, fmt.Errorf("No such image: %s", name)
  807. }
  808. if !autoPrune {
  809. if err := srv.runtime.graph.Delete(img.ID); err != nil {
  810. return nil, fmt.Errorf("Error deleting image %s: %s", name, err.Error())
  811. }
  812. return nil, nil
  813. }
  814. var tag string
  815. if strings.Contains(name, ":") {
  816. nameParts := strings.Split(name, ":")
  817. name = nameParts[0]
  818. tag = nameParts[1]
  819. }
  820. return srv.deleteImage(img, name, tag)
  821. }
  822. func (srv *Server) ImageGetCached(imgId string, config *Config) (*Image, error) {
  823. // Retrieve all images
  824. images, err := srv.runtime.graph.All()
  825. if err != nil {
  826. return nil, err
  827. }
  828. // Store the tree in a map of map (map[parentId][childId])
  829. imageMap := make(map[string]map[string]struct{})
  830. for _, img := range images {
  831. if _, exists := imageMap[img.Parent]; !exists {
  832. imageMap[img.Parent] = make(map[string]struct{})
  833. }
  834. imageMap[img.Parent][img.ID] = struct{}{}
  835. }
  836. // Loop on the children of the given image and check the config
  837. for elem := range imageMap[imgId] {
  838. img, err := srv.runtime.graph.Get(elem)
  839. if err != nil {
  840. return nil, err
  841. }
  842. if CompareConfig(&img.ContainerConfig, config) {
  843. return img, nil
  844. }
  845. }
  846. return nil, nil
  847. }
  848. func (srv *Server) ContainerStart(name string) error {
  849. if container := srv.runtime.Get(name); container != nil {
  850. if err := container.Start(); err != nil {
  851. return fmt.Errorf("Error starting container %s: %s", name, err.Error())
  852. }
  853. } else {
  854. return fmt.Errorf("No such container: %s", name)
  855. }
  856. return nil
  857. }
  858. func (srv *Server) ContainerStop(name string, t int) error {
  859. if container := srv.runtime.Get(name); container != nil {
  860. if err := container.Stop(t); err != nil {
  861. return fmt.Errorf("Error stopping container %s: %s", name, err.Error())
  862. }
  863. } else {
  864. return fmt.Errorf("No such container: %s", name)
  865. }
  866. return nil
  867. }
  868. func (srv *Server) ContainerWait(name string) (int, error) {
  869. if container := srv.runtime.Get(name); container != nil {
  870. return container.Wait(), nil
  871. }
  872. return 0, fmt.Errorf("No such container: %s", name)
  873. }
  874. func (srv *Server) ContainerResize(name string, h, w int) error {
  875. if container := srv.runtime.Get(name); container != nil {
  876. return container.Resize(h, w)
  877. }
  878. return fmt.Errorf("No such container: %s", name)
  879. }
  880. func (srv *Server) ContainerAttach(name string, logs, stream, stdin, stdout, stderr bool, in io.ReadCloser, out io.Writer) error {
  881. container := srv.runtime.Get(name)
  882. if container == nil {
  883. return fmt.Errorf("No such container: %s", name)
  884. }
  885. //logs
  886. if logs {
  887. if stdout {
  888. cLog, err := container.ReadLog("stdout")
  889. if err != nil {
  890. utils.Debugf("Error reading logs (stdout): %s", err)
  891. } else if _, err := io.Copy(out, cLog); err != nil {
  892. utils.Debugf("Error streaming logs (stdout): %s", err)
  893. }
  894. }
  895. if stderr {
  896. cLog, err := container.ReadLog("stderr")
  897. if err != nil {
  898. utils.Debugf("Error reading logs (stderr): %s", err)
  899. } else if _, err := io.Copy(out, cLog); err != nil {
  900. utils.Debugf("Error streaming logs (stderr): %s", err)
  901. }
  902. }
  903. }
  904. //stream
  905. if stream {
  906. if container.State.Ghost {
  907. return fmt.Errorf("Impossible to attach to a ghost container")
  908. }
  909. var (
  910. cStdin io.ReadCloser
  911. cStdout, cStderr io.Writer
  912. cStdinCloser io.Closer
  913. )
  914. if stdin {
  915. r, w := io.Pipe()
  916. go func() {
  917. defer w.Close()
  918. defer utils.Debugf("Closing buffered stdin pipe")
  919. io.Copy(w, in)
  920. }()
  921. cStdin = r
  922. cStdinCloser = in
  923. }
  924. if stdout {
  925. cStdout = out
  926. }
  927. if stderr {
  928. cStderr = out
  929. }
  930. <-container.Attach(cStdin, cStdinCloser, cStdout, cStderr)
  931. // If we are in stdinonce mode, wait for the process to end
  932. // otherwise, simply return
  933. if container.Config.StdinOnce && !container.Config.Tty {
  934. container.Wait()
  935. }
  936. }
  937. return nil
  938. }
  939. func (srv *Server) ContainerInspect(name string) (*Container, error) {
  940. if container := srv.runtime.Get(name); container != nil {
  941. return container, nil
  942. }
  943. return nil, fmt.Errorf("No such container: %s", name)
  944. }
  945. func (srv *Server) ImageInspect(name string) (*Image, error) {
  946. if image, err := srv.runtime.repositories.LookupImage(name); err == nil && image != nil {
  947. return image, nil
  948. }
  949. return nil, fmt.Errorf("No such image: %s", name)
  950. }
  951. func NewServer(autoRestart, enableCors bool, dns ListOpts) (*Server, error) {
  952. if runtime.GOARCH != "amd64" {
  953. log.Fatalf("The docker runtime currently only supports amd64 (not %s). This will change in the future. Aborting.", runtime.GOARCH)
  954. }
  955. runtime, err := NewRuntime(autoRestart, dns)
  956. if err != nil {
  957. return nil, err
  958. }
  959. srv := &Server{
  960. runtime: runtime,
  961. enableCors: enableCors,
  962. lock: &sync.Mutex{},
  963. pullingPool: make(map[string]struct{}),
  964. pushingPool: make(map[string]struct{}),
  965. }
  966. runtime.srv = srv
  967. return srv, nil
  968. }
  969. type Server struct {
  970. runtime *Runtime
  971. enableCors bool
  972. lock *sync.Mutex
  973. pullingPool map[string]struct{}
  974. pushingPool map[string]struct{}
  975. }