server.go 34 KB

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