server.go 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131
  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, size 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. if size {
  264. c.SizeRw, c.SizeRootFs = container.GetSize()
  265. }
  266. retContainers = append(retContainers, c)
  267. }
  268. return retContainers
  269. }
  270. func (srv *Server) ContainerCommit(name, repo, tag, author, comment string, config *Config) (string, error) {
  271. container := srv.runtime.Get(name)
  272. if container == nil {
  273. return "", fmt.Errorf("No such container: %s", name)
  274. }
  275. img, err := NewBuilder(srv.runtime).Commit(container, repo, tag, comment, author, config)
  276. if err != nil {
  277. return "", err
  278. }
  279. return img.ShortID(), err
  280. }
  281. func (srv *Server) ContainerTag(name, repo, tag string, force bool) error {
  282. if err := srv.runtime.repositories.Set(repo, tag, name, force); err != nil {
  283. return err
  284. }
  285. return nil
  286. }
  287. func (srv *Server) pullImage(r *registry.Registry, out io.Writer, imgId, endpoint string, token []string, sf *utils.StreamFormatter) error {
  288. history, err := r.GetRemoteHistory(imgId, endpoint, token)
  289. if err != nil {
  290. return err
  291. }
  292. // FIXME: Try to stream the images?
  293. // FIXME: Launch the getRemoteImage() in goroutines
  294. for _, id := range history {
  295. if !srv.runtime.graph.Exists(id) {
  296. out.Write(sf.FormatStatus("Pulling %s metadata", id))
  297. imgJSON, imgSize, err := r.GetRemoteImageJSON(id, endpoint, token)
  298. if err != nil {
  299. // FIXME: Keep goging in case of error?
  300. return err
  301. }
  302. img, err := NewImgJSON(imgJSON)
  303. if err != nil {
  304. return fmt.Errorf("Failed to parse json: %s", err)
  305. }
  306. // Get the layer
  307. out.Write(sf.FormatStatus("Pulling %s fs layer", id))
  308. layer, err := r.GetRemoteImageLayer(img.ID, endpoint, token)
  309. if err != nil {
  310. return err
  311. }
  312. defer layer.Close()
  313. if err := srv.runtime.graph.Register(utils.ProgressReader(layer, imgSize, out, sf.FormatProgress("Downloading", "%v/%v (%v)"), sf), false, img); err != nil {
  314. return err
  315. }
  316. }
  317. }
  318. return nil
  319. }
  320. func (srv *Server) pullRepository(r *registry.Registry, out io.Writer, local, remote, askedTag, registryEp string, sf *utils.StreamFormatter) error {
  321. out.Write(sf.FormatStatus("Pulling repository %s from %s", local, auth.IndexServerAddress()))
  322. var repoData *registry.RepositoryData
  323. var err error
  324. if registryEp == "" {
  325. repoData, err = r.GetRepositoryData(remote)
  326. if err != nil {
  327. return err
  328. }
  329. utils.Debugf("Updating checksums")
  330. // Reload the json file to make sure not to overwrite faster sums
  331. if err := srv.runtime.graph.UpdateChecksums(repoData.ImgList); err != nil {
  332. return err
  333. }
  334. } else {
  335. repoData = &registry.RepositoryData{
  336. Tokens: []string{},
  337. ImgList: make(map[string]*registry.ImgData),
  338. Endpoints: []string{registryEp},
  339. }
  340. }
  341. utils.Debugf("Retrieving the tag list")
  342. tagsList, err := r.GetRemoteTags(repoData.Endpoints, remote, repoData.Tokens)
  343. if err != nil {
  344. utils.Debugf("%v", err)
  345. return err
  346. }
  347. if registryEp != "" {
  348. for tag, id := range tagsList {
  349. repoData.ImgList[id] = &registry.ImgData{
  350. ID: id,
  351. Tag: tag,
  352. Checksum: "",
  353. }
  354. }
  355. }
  356. utils.Debugf("Registering tags")
  357. // If no tag has been specified, pull them all
  358. if askedTag == "" {
  359. for tag, id := range tagsList {
  360. repoData.ImgList[id].Tag = tag
  361. }
  362. } else {
  363. // Otherwise, check that the tag exists and use only that one
  364. id, exists := tagsList[askedTag]
  365. if !exists {
  366. return fmt.Errorf("Tag %s not found in repositoy %s", askedTag, local)
  367. }
  368. repoData.ImgList[id].Tag = askedTag
  369. }
  370. for _, img := range repoData.ImgList {
  371. if askedTag != "" && img.Tag != askedTag {
  372. utils.Debugf("(%s) does not match %s (id: %s), skipping", img.Tag, askedTag, img.ID)
  373. continue
  374. }
  375. out.Write(sf.FormatStatus("Pulling image %s (%s) from %s", img.ID, img.Tag, remote))
  376. success := false
  377. for _, ep := range repoData.Endpoints {
  378. if !(strings.HasPrefix(ep, "http://") || strings.HasPrefix(ep, "https://")) {
  379. ep = fmt.Sprintf("%s://%s", registry.UrlScheme(), ep)
  380. }
  381. if err := srv.pullImage(r, out, img.ID, ep+"/v1", repoData.Tokens, sf); err != nil {
  382. out.Write(sf.FormatStatus("Error while retrieving image for tag: %s (%s); checking next endpoint", askedTag, err))
  383. continue
  384. }
  385. success = true
  386. break
  387. }
  388. if !success {
  389. return fmt.Errorf("Could not find repository on any of the indexed registries.")
  390. }
  391. }
  392. for tag, id := range tagsList {
  393. if askedTag != "" && tag != askedTag {
  394. continue
  395. }
  396. if err := srv.runtime.repositories.Set(local, tag, id, true); err != nil {
  397. return err
  398. }
  399. }
  400. if err := srv.runtime.repositories.Save(); err != nil {
  401. return err
  402. }
  403. return nil
  404. }
  405. func (srv *Server) poolAdd(kind, key string) error {
  406. srv.lock.Lock()
  407. defer srv.lock.Unlock()
  408. if _, exists := srv.pullingPool[key]; exists {
  409. return fmt.Errorf("%s %s is already in progress", key, kind)
  410. }
  411. switch kind {
  412. case "pull":
  413. srv.pullingPool[key] = struct{}{}
  414. break
  415. case "push":
  416. srv.pushingPool[key] = struct{}{}
  417. break
  418. default:
  419. return fmt.Errorf("Unkown pool type")
  420. }
  421. return nil
  422. }
  423. func (srv *Server) poolRemove(kind, key string) error {
  424. switch kind {
  425. case "pull":
  426. delete(srv.pullingPool, key)
  427. break
  428. case "push":
  429. delete(srv.pushingPool, key)
  430. break
  431. default:
  432. return fmt.Errorf("Unkown pool type")
  433. }
  434. return nil
  435. }
  436. func (srv *Server) ImagePull(name, tag, endpoint string, out io.Writer, sf *utils.StreamFormatter, authConfig *auth.AuthConfig) error {
  437. r, err := registry.NewRegistry(srv.runtime.root, authConfig)
  438. if err != nil {
  439. return err
  440. }
  441. if err := srv.poolAdd("pull", name+":"+tag); err != nil {
  442. return err
  443. }
  444. defer srv.poolRemove("pull", name+":"+tag)
  445. remote := name
  446. parts := strings.Split(name, "/")
  447. if len(parts) > 2 {
  448. remote = fmt.Sprintf("src/%s", url.QueryEscape(strings.Join(parts, "/")))
  449. }
  450. out = utils.NewWriteFlusher(out)
  451. err = srv.pullRepository(r, out, name, remote, tag, endpoint, sf)
  452. if err != nil && endpoint != "" {
  453. if err := srv.pullImage(r, out, name, endpoint, nil, sf); err != nil {
  454. return err
  455. }
  456. return nil
  457. }
  458. return nil
  459. }
  460. // Retrieve the checksum of an image
  461. // Priority:
  462. // - Check on the stored checksums
  463. // - Check if the archive exists, if it does not, ask the registry
  464. // - If the archive does exists, process the checksum from it
  465. // - If the archive does not exists and not found on registry, process checksum from layer
  466. func (srv *Server) getChecksum(imageId string) (string, error) {
  467. // FIXME: Use in-memory map instead of reading the file each time
  468. if sums, err := srv.runtime.graph.getStoredChecksums(); err != nil {
  469. return "", err
  470. } else if checksum, exists := sums[imageId]; exists {
  471. return checksum, nil
  472. }
  473. img, err := srv.runtime.graph.Get(imageId)
  474. if err != nil {
  475. return "", err
  476. }
  477. if _, err := os.Stat(layerArchivePath(srv.runtime.graph.imageRoot(imageId))); err != nil {
  478. if os.IsNotExist(err) {
  479. // TODO: Ask the registry for the checksum
  480. // As the archive is not there, it is supposed to come from a pull.
  481. } else {
  482. return "", err
  483. }
  484. }
  485. checksum, err := img.Checksum()
  486. if err != nil {
  487. return "", err
  488. }
  489. return checksum, nil
  490. }
  491. // Retrieve the all the images to be uploaded in the correct order
  492. // Note: we can't use a map as it is not ordered
  493. func (srv *Server) getImageList(localRepo map[string]string) ([]*registry.ImgData, error) {
  494. var imgList []*registry.ImgData
  495. imageSet := make(map[string]struct{})
  496. for tag, id := range localRepo {
  497. img, err := srv.runtime.graph.Get(id)
  498. if err != nil {
  499. return nil, err
  500. }
  501. img.WalkHistory(func(img *Image) error {
  502. if _, exists := imageSet[img.ID]; exists {
  503. return nil
  504. }
  505. imageSet[img.ID] = struct{}{}
  506. checksum, err := srv.getChecksum(img.ID)
  507. if err != nil {
  508. return err
  509. }
  510. imgList = append([]*registry.ImgData{{
  511. ID: img.ID,
  512. Checksum: checksum,
  513. Tag: tag,
  514. }}, imgList...)
  515. return nil
  516. })
  517. }
  518. return imgList, nil
  519. }
  520. func (srv *Server) pushRepository(r *registry.Registry, out io.Writer, name, registryEp string, localRepo map[string]string, sf *utils.StreamFormatter) error {
  521. out = utils.NewWriteFlusher(out)
  522. out.Write(sf.FormatStatus("Processing checksums"))
  523. imgList, err := srv.getImageList(localRepo)
  524. if err != nil {
  525. return err
  526. }
  527. out.Write(sf.FormatStatus("Sending image list"))
  528. srvName := name
  529. parts := strings.Split(name, "/")
  530. if len(parts) > 2 {
  531. srvName = fmt.Sprintf("src/%s", url.QueryEscape(strings.Join(parts, "/")))
  532. }
  533. var repoData *registry.RepositoryData
  534. if registryEp == "" {
  535. repoData, err = r.PushImageJSONIndex(name, imgList, false, nil)
  536. if err != nil {
  537. return err
  538. }
  539. } else {
  540. repoData = &registry.RepositoryData{
  541. ImgList: make(map[string]*registry.ImgData),
  542. Tokens: []string{},
  543. Endpoints: []string{registryEp},
  544. }
  545. tagsList, err := r.GetRemoteTags(repoData.Endpoints, name, repoData.Tokens)
  546. if err != nil && err.Error() != "Repository not found" {
  547. return err
  548. } else if err == nil {
  549. for tag, id := range tagsList {
  550. repoData.ImgList[id] = &registry.ImgData{
  551. ID: id,
  552. Tag: tag,
  553. Checksum: "",
  554. }
  555. }
  556. }
  557. }
  558. for _, ep := range repoData.Endpoints {
  559. if !(strings.HasPrefix(ep, "http://") || strings.HasPrefix(ep, "https://")) {
  560. ep = "https://" + ep
  561. }
  562. out.Write(sf.FormatStatus("Pushing repository %s to %s (%d tags)", name, ep, len(localRepo)))
  563. // For each image within the repo, push them
  564. for _, elem := range imgList {
  565. if _, exists := repoData.ImgList[elem.ID]; exists {
  566. out.Write(sf.FormatStatus("Image %s already on registry, skipping", name))
  567. continue
  568. } else if registryEp != "" && r.LookupRemoteImage(elem.ID, registryEp, repoData.Tokens) {
  569. fmt.Fprintf(out, "Image %s already on registry, skipping\n", name)
  570. continue
  571. }
  572. if err := srv.pushImage(r, out, name, elem.ID, ep, repoData.Tokens, sf); err != nil {
  573. // FIXME: Continue on error?
  574. return err
  575. }
  576. out.Write(sf.FormatStatus("Pushing tags for rev [%s] on {%s}", elem.ID, ep+"/repositories/"+srvName+"/tags/"+elem.Tag))
  577. if err := r.PushRegistryTag(srvName, elem.ID, elem.Tag, ep, repoData.Tokens); err != nil {
  578. return err
  579. }
  580. }
  581. }
  582. if registryEp == "" {
  583. if _, err := r.PushImageJSONIndex(name, imgList, true, repoData.Endpoints); err != nil {
  584. return err
  585. }
  586. }
  587. return nil
  588. }
  589. func (srv *Server) pushImage(r *registry.Registry, out io.Writer, remote, imgId, ep string, token []string, sf *utils.StreamFormatter) error {
  590. out = utils.NewWriteFlusher(out)
  591. jsonRaw, err := ioutil.ReadFile(path.Join(srv.runtime.graph.Root, imgId, "json"))
  592. if err != nil {
  593. return fmt.Errorf("Error while retreiving the path for {%s}: %s", imgId, err)
  594. }
  595. out.Write(sf.FormatStatus("Pushing %s", imgId))
  596. // Make sure we have the image's checksum
  597. checksum, err := srv.getChecksum(imgId)
  598. if err != nil {
  599. return err
  600. }
  601. imgData := &registry.ImgData{
  602. ID: imgId,
  603. Checksum: checksum,
  604. }
  605. // Send the json
  606. if err := r.PushImageJSONRegistry(imgData, jsonRaw, ep, token); err != nil {
  607. if err == registry.ErrAlreadyExists {
  608. out.Write(sf.FormatStatus("Image %s already uploaded ; skipping", imgData.ID))
  609. return nil
  610. }
  611. return err
  612. }
  613. // Retrieve the tarball to be sent
  614. var layerData *TempArchive
  615. // If the archive exists, use it
  616. file, err := os.Open(layerArchivePath(srv.runtime.graph.imageRoot(imgId)))
  617. if err != nil {
  618. if os.IsNotExist(err) {
  619. // If the archive does not exist, create one from the layer
  620. layerData, err = srv.runtime.graph.TempLayerArchive(imgId, Xz, out)
  621. if err != nil {
  622. return fmt.Errorf("Failed to generate layer archive: %s", err)
  623. }
  624. } else {
  625. return err
  626. }
  627. } else {
  628. defer file.Close()
  629. st, err := file.Stat()
  630. if err != nil {
  631. return err
  632. }
  633. layerData = &TempArchive{
  634. File: file,
  635. Size: st.Size(),
  636. }
  637. }
  638. // Send the layer
  639. if err := r.PushImageLayerRegistry(imgData.ID, utils.ProgressReader(layerData, int(layerData.Size), out, sf.FormatProgress("Pushing", "%v/%v (%v)"), sf), ep, token); err != nil {
  640. return err
  641. }
  642. return nil
  643. }
  644. // FIXME: Allow to interupt current push when new push of same image is done.
  645. func (srv *Server) ImagePush(name, endpoint string, out io.Writer, sf *utils.StreamFormatter, authConfig *auth.AuthConfig) error {
  646. if err := srv.poolAdd("push", name); err != nil {
  647. return err
  648. }
  649. defer srv.poolRemove("push", name)
  650. out = utils.NewWriteFlusher(out)
  651. img, err := srv.runtime.graph.Get(name)
  652. r, err2 := registry.NewRegistry(srv.runtime.root, authConfig)
  653. if err2 != nil {
  654. return err2
  655. }
  656. if err != nil {
  657. out.Write(sf.FormatStatus("The push refers to a repository [%s] (len: %d)", name, len(srv.runtime.repositories.Repositories[name])))
  658. // If it fails, try to get the repository
  659. if localRepo, exists := srv.runtime.repositories.Repositories[name]; exists {
  660. if err := srv.pushRepository(r, out, name, endpoint, localRepo, sf); err != nil {
  661. return err
  662. }
  663. return nil
  664. }
  665. return err
  666. }
  667. out.Write(sf.FormatStatus("The push refers to an image: [%s]", name))
  668. if err := srv.pushImage(r, out, name, img.ID, endpoint, nil, sf); err != nil {
  669. return err
  670. }
  671. return nil
  672. }
  673. func (srv *Server) ImageImport(src, repo, tag string, in io.Reader, out io.Writer, sf *utils.StreamFormatter) error {
  674. var archive io.Reader
  675. var resp *http.Response
  676. if src == "-" {
  677. archive = in
  678. } else {
  679. u, err := url.Parse(src)
  680. if err != nil {
  681. return err
  682. }
  683. if u.Scheme == "" {
  684. u.Scheme = "http"
  685. u.Host = src
  686. u.Path = ""
  687. }
  688. out.Write(sf.FormatStatus("Downloading from %s", u))
  689. // Download with curl (pretty progress bar)
  690. // If curl is not available, fallback to http.Get()
  691. resp, err = utils.Download(u.String(), out)
  692. if err != nil {
  693. return err
  694. }
  695. archive = utils.ProgressReader(resp.Body, int(resp.ContentLength), out, sf.FormatProgress("Importing", "%v/%v (%v)"), sf)
  696. }
  697. img, err := srv.runtime.graph.Create(archive, nil, "Imported from "+src, "", nil)
  698. if err != nil {
  699. return err
  700. }
  701. // Optionally register the image at REPO/TAG
  702. if repo != "" {
  703. if err := srv.runtime.repositories.Set(repo, tag, img.ID, true); err != nil {
  704. return err
  705. }
  706. }
  707. out.Write(sf.FormatStatus(img.ShortID()))
  708. return nil
  709. }
  710. func (srv *Server) ContainerCreate(config *Config) (string, error) {
  711. if config.Memory != 0 && config.Memory < 524288 {
  712. return "", fmt.Errorf("Memory limit must be given in bytes (minimum 524288 bytes)")
  713. }
  714. if config.Memory > 0 && !srv.runtime.capabilities.MemoryLimit {
  715. config.Memory = 0
  716. }
  717. if config.Memory > 0 && !srv.runtime.capabilities.SwapLimit {
  718. config.MemorySwap = -1
  719. }
  720. b := NewBuilder(srv.runtime)
  721. container, err := b.Create(config)
  722. if err != nil {
  723. if srv.runtime.graph.IsNotExist(err) {
  724. return "", fmt.Errorf("No such image: %s", config.Image)
  725. }
  726. return "", err
  727. }
  728. return container.ShortID(), nil
  729. }
  730. func (srv *Server) ContainerRestart(name string, t int) error {
  731. if container := srv.runtime.Get(name); container != nil {
  732. if err := container.Restart(t); err != nil {
  733. return fmt.Errorf("Error restarting container %s: %s", name, err.Error())
  734. }
  735. } else {
  736. return fmt.Errorf("No such container: %s", name)
  737. }
  738. return nil
  739. }
  740. func (srv *Server) ContainerDestroy(name string, removeVolume bool) error {
  741. if container := srv.runtime.Get(name); container != nil {
  742. if container.State.Running {
  743. return fmt.Errorf("Impossible to remove a running container, please stop it first")
  744. }
  745. volumes := make(map[string]struct{})
  746. // Store all the deleted containers volumes
  747. for _, volumeId := range container.Volumes {
  748. volumes[volumeId] = struct{}{}
  749. }
  750. if err := srv.runtime.Destroy(container); err != nil {
  751. return fmt.Errorf("Error destroying container %s: %s", name, err.Error())
  752. }
  753. if removeVolume {
  754. // Retrieve all volumes from all remaining containers
  755. usedVolumes := make(map[string]*Container)
  756. for _, container := range srv.runtime.List() {
  757. for _, containerVolumeId := range container.Volumes {
  758. usedVolumes[containerVolumeId] = container
  759. }
  760. }
  761. for volumeId := range volumes {
  762. // If the requested volu
  763. if c, exists := usedVolumes[volumeId]; exists {
  764. log.Printf("The volume %s is used by the container %s. Impossible to remove it. Skipping.\n", volumeId, c.ID)
  765. continue
  766. }
  767. if err := srv.runtime.volumes.Delete(volumeId); err != nil {
  768. return err
  769. }
  770. }
  771. }
  772. } else {
  773. return fmt.Errorf("No such container: %s", name)
  774. }
  775. return nil
  776. }
  777. var ErrImageReferenced = errors.New("Image referenced by a repository")
  778. func (srv *Server) deleteImageAndChildren(id string, imgs *[]APIRmi) error {
  779. // If the image is referenced by a repo, do not delete
  780. if len(srv.runtime.repositories.ByID()[id]) != 0 {
  781. return ErrImageReferenced
  782. }
  783. // If the image is not referenced but has children, go recursive
  784. referenced := false
  785. byParents, err := srv.runtime.graph.ByParent()
  786. if err != nil {
  787. return err
  788. }
  789. for _, img := range byParents[id] {
  790. if err := srv.deleteImageAndChildren(img.ID, imgs); err != nil {
  791. if err != ErrImageReferenced {
  792. return err
  793. }
  794. referenced = true
  795. }
  796. }
  797. if referenced {
  798. return ErrImageReferenced
  799. }
  800. // If the image is not referenced and has no children, remove it
  801. byParents, err = srv.runtime.graph.ByParent()
  802. if err != nil {
  803. return err
  804. }
  805. if len(byParents[id]) == 0 {
  806. if err := srv.runtime.repositories.DeleteAll(id); err != nil {
  807. return err
  808. }
  809. err := srv.runtime.graph.Delete(id)
  810. if err != nil {
  811. return err
  812. }
  813. *imgs = append(*imgs, APIRmi{Deleted: utils.TruncateID(id)})
  814. return nil
  815. }
  816. return nil
  817. }
  818. func (srv *Server) deleteImageParents(img *Image, imgs *[]APIRmi) error {
  819. if img.Parent != "" {
  820. parent, err := srv.runtime.graph.Get(img.Parent)
  821. if err != nil {
  822. return err
  823. }
  824. // Remove all children images
  825. if err := srv.deleteImageAndChildren(img.Parent, imgs); err != nil {
  826. return err
  827. }
  828. return srv.deleteImageParents(parent, imgs)
  829. }
  830. return nil
  831. }
  832. func (srv *Server) deleteImage(img *Image, repoName, tag string) (*[]APIRmi, error) {
  833. //Untag the current image
  834. var imgs []APIRmi
  835. tagDeleted, err := srv.runtime.repositories.Delete(repoName, tag)
  836. if err != nil {
  837. return nil, err
  838. }
  839. if tagDeleted {
  840. imgs = append(imgs, APIRmi{Untagged: img.ShortID()})
  841. }
  842. if len(srv.runtime.repositories.ByID()[img.ID]) == 0 {
  843. if err := srv.deleteImageAndChildren(img.ID, &imgs); err != nil {
  844. if err != ErrImageReferenced {
  845. return &imgs, err
  846. }
  847. } else if err := srv.deleteImageParents(img, &imgs); err != nil {
  848. if err != ErrImageReferenced {
  849. return &imgs, err
  850. }
  851. }
  852. }
  853. return &imgs, nil
  854. }
  855. func (srv *Server) ImageDelete(name string, autoPrune bool) (*[]APIRmi, error) {
  856. img, err := srv.runtime.repositories.LookupImage(name)
  857. if err != nil {
  858. return nil, fmt.Errorf("No such image: %s", name)
  859. }
  860. if !autoPrune {
  861. if err := srv.runtime.graph.Delete(img.ID); err != nil {
  862. return nil, fmt.Errorf("Error deleting image %s: %s", name, err.Error())
  863. }
  864. return nil, nil
  865. }
  866. var tag string
  867. if strings.Contains(name, ":") {
  868. nameParts := strings.Split(name, ":")
  869. name = nameParts[0]
  870. tag = nameParts[1]
  871. }
  872. return srv.deleteImage(img, name, tag)
  873. }
  874. func (srv *Server) ImageGetCached(imgId string, config *Config) (*Image, error) {
  875. // Retrieve all images
  876. images, err := srv.runtime.graph.All()
  877. if err != nil {
  878. return nil, err
  879. }
  880. // Store the tree in a map of map (map[parentId][childId])
  881. imageMap := make(map[string]map[string]struct{})
  882. for _, img := range images {
  883. if _, exists := imageMap[img.Parent]; !exists {
  884. imageMap[img.Parent] = make(map[string]struct{})
  885. }
  886. imageMap[img.Parent][img.ID] = struct{}{}
  887. }
  888. // Loop on the children of the given image and check the config
  889. for elem := range imageMap[imgId] {
  890. img, err := srv.runtime.graph.Get(elem)
  891. if err != nil {
  892. return nil, err
  893. }
  894. if CompareConfig(&img.ContainerConfig, config) {
  895. return img, nil
  896. }
  897. }
  898. return nil, nil
  899. }
  900. func (srv *Server) ContainerStart(name string, hostConfig *HostConfig) error {
  901. if container := srv.runtime.Get(name); container != nil {
  902. if err := container.Start(hostConfig); err != nil {
  903. return fmt.Errorf("Error starting container %s: %s", name, err.Error())
  904. }
  905. } else {
  906. return fmt.Errorf("No such container: %s", name)
  907. }
  908. return nil
  909. }
  910. func (srv *Server) ContainerStop(name string, t int) error {
  911. if container := srv.runtime.Get(name); container != nil {
  912. if err := container.Stop(t); err != nil {
  913. return fmt.Errorf("Error stopping container %s: %s", name, err.Error())
  914. }
  915. } else {
  916. return fmt.Errorf("No such container: %s", name)
  917. }
  918. return nil
  919. }
  920. func (srv *Server) ContainerWait(name string) (int, error) {
  921. if container := srv.runtime.Get(name); container != nil {
  922. return container.Wait(), nil
  923. }
  924. return 0, fmt.Errorf("No such container: %s", name)
  925. }
  926. func (srv *Server) ContainerResize(name string, h, w int) error {
  927. if container := srv.runtime.Get(name); container != nil {
  928. return container.Resize(h, w)
  929. }
  930. return fmt.Errorf("No such container: %s", name)
  931. }
  932. func (srv *Server) ContainerAttach(name string, logs, stream, stdin, stdout, stderr bool, in io.ReadCloser, out io.Writer) error {
  933. container := srv.runtime.Get(name)
  934. if container == nil {
  935. return fmt.Errorf("No such container: %s", name)
  936. }
  937. //logs
  938. if logs {
  939. if stdout {
  940. cLog, err := container.ReadLog("stdout")
  941. if err != nil {
  942. utils.Debugf("Error reading logs (stdout): %s", err)
  943. } else if _, err := io.Copy(out, cLog); err != nil {
  944. utils.Debugf("Error streaming logs (stdout): %s", err)
  945. }
  946. }
  947. if stderr {
  948. cLog, err := container.ReadLog("stderr")
  949. if err != nil {
  950. utils.Debugf("Error reading logs (stderr): %s", err)
  951. } else if _, err := io.Copy(out, cLog); err != nil {
  952. utils.Debugf("Error streaming logs (stderr): %s", err)
  953. }
  954. }
  955. }
  956. //stream
  957. if stream {
  958. if container.State.Ghost {
  959. return fmt.Errorf("Impossible to attach to a ghost container")
  960. }
  961. var (
  962. cStdin io.ReadCloser
  963. cStdout, cStderr io.Writer
  964. cStdinCloser io.Closer
  965. )
  966. if stdin {
  967. r, w := io.Pipe()
  968. go func() {
  969. defer w.Close()
  970. defer utils.Debugf("Closing buffered stdin pipe")
  971. io.Copy(w, in)
  972. }()
  973. cStdin = r
  974. cStdinCloser = in
  975. }
  976. if stdout {
  977. cStdout = out
  978. }
  979. if stderr {
  980. cStderr = out
  981. }
  982. <-container.Attach(cStdin, cStdinCloser, cStdout, cStderr)
  983. // If we are in stdinonce mode, wait for the process to end
  984. // otherwise, simply return
  985. if container.Config.StdinOnce && !container.Config.Tty {
  986. container.Wait()
  987. }
  988. }
  989. return nil
  990. }
  991. func (srv *Server) ContainerInspect(name string) (*Container, error) {
  992. if container := srv.runtime.Get(name); container != nil {
  993. return container, nil
  994. }
  995. return nil, fmt.Errorf("No such container: %s", name)
  996. }
  997. func (srv *Server) ImageInspect(name string) (*Image, error) {
  998. if image, err := srv.runtime.repositories.LookupImage(name); err == nil && image != nil {
  999. return image, nil
  1000. }
  1001. return nil, fmt.Errorf("No such image: %s", name)
  1002. }
  1003. func NewServer(flGraphPath string, autoRestart, enableCors bool, dns ListOpts) (*Server, error) {
  1004. if runtime.GOARCH != "amd64" {
  1005. log.Fatalf("The docker runtime currently only supports amd64 (not %s). This will change in the future. Aborting.", runtime.GOARCH)
  1006. }
  1007. runtime, err := NewRuntime(flGraphPath, autoRestart, dns)
  1008. if err != nil {
  1009. return nil, err
  1010. }
  1011. srv := &Server{
  1012. runtime: runtime,
  1013. enableCors: enableCors,
  1014. lock: &sync.Mutex{},
  1015. pullingPool: make(map[string]struct{}),
  1016. pushingPool: make(map[string]struct{}),
  1017. }
  1018. runtime.srv = srv
  1019. return srv, nil
  1020. }
  1021. type Server struct {
  1022. runtime *Runtime
  1023. enableCors bool
  1024. lock *sync.Mutex
  1025. pullingPool map[string]struct{}
  1026. pushingPool map[string]struct{}
  1027. }