server.go 37 KB

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