server.go 39 KB

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