server.go 43 KB

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