commands.go 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064
  1. package docker
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "fmt"
  6. "github.com/dotcloud/docker/auth"
  7. "github.com/dotcloud/docker/rcli"
  8. "io"
  9. "log"
  10. "net/http"
  11. "net/url"
  12. "path/filepath"
  13. "runtime"
  14. "strconv"
  15. "strings"
  16. "text/tabwriter"
  17. "time"
  18. "unicode"
  19. )
  20. const VERSION = "0.2.2"
  21. var (
  22. GIT_COMMIT string
  23. )
  24. func (srv *Server) Name() string {
  25. return "docker"
  26. }
  27. // FIXME: Stop violating DRY by repeating usage here and in Subcmd declarations
  28. func (srv *Server) Help() string {
  29. help := "Usage: docker COMMAND [arg...]\n\nA self-sufficient runtime for linux containers.\n\nCommands:\n"
  30. for _, cmd := range [][]string{
  31. {"attach", "Attach to a running container"},
  32. {"commit", "Create a new image from a container's changes"},
  33. {"diff", "Inspect changes on a container's filesystem"},
  34. {"export", "Stream the contents of a container as a tar archive"},
  35. {"history", "Show the history of an image"},
  36. {"images", "List images"},
  37. {"import", "Create a new filesystem image from the contents of a tarball"},
  38. {"info", "Display system-wide information"},
  39. {"inspect", "Return low-level information on a container"},
  40. {"kill", "Kill a running container"},
  41. {"login", "Register or Login to the docker registry server"},
  42. {"logs", "Fetch the logs of a container"},
  43. {"port", "Lookup the public-facing port which is NAT-ed to PRIVATE_PORT"},
  44. {"ps", "List containers"},
  45. {"pull", "Pull an image or a repository from the docker registry server"},
  46. {"push", "Push an image or a repository to the docker registry server"},
  47. {"restart", "Restart a running container"},
  48. {"rm", "Remove a container"},
  49. {"rmi", "Remove an image"},
  50. {"run", "Run a command in a new container"},
  51. {"start", "Start a stopped container"},
  52. {"stop", "Stop a running container"},
  53. {"tag", "Tag an image into a repository"},
  54. {"version", "Show the docker version information"},
  55. {"wait", "Block until a container stops, then print its exit code"},
  56. } {
  57. help += fmt.Sprintf(" %-10.10s%s\n", cmd[0], cmd[1])
  58. }
  59. return help
  60. }
  61. // 'docker login': login / register a user to registry service.
  62. func (srv *Server) CmdLogin(stdin io.ReadCloser, stdout rcli.DockerConn, args ...string) error {
  63. // Read a line on raw terminal with support for simple backspace
  64. // sequences and echo.
  65. //
  66. // This function is necessary because the login command must be done in a
  67. // raw terminal for two reasons:
  68. // - we have to read a password (without echoing it);
  69. // - the rcli "protocol" only supports cannonical and raw modes and you
  70. // can't tune it once the command as been started.
  71. var readStringOnRawTerminal = func(stdin io.Reader, stdout io.Writer, echo bool) string {
  72. char := make([]byte, 1)
  73. buffer := make([]byte, 64)
  74. var i = 0
  75. for i < len(buffer) {
  76. n, err := stdin.Read(char)
  77. if n > 0 {
  78. if char[0] == '\r' || char[0] == '\n' {
  79. stdout.Write([]byte{'\r', '\n'})
  80. break
  81. } else if char[0] == 127 || char[0] == '\b' {
  82. if i > 0 {
  83. if echo {
  84. stdout.Write([]byte{'\b', ' ', '\b'})
  85. }
  86. i--
  87. }
  88. } else if !unicode.IsSpace(rune(char[0])) &&
  89. !unicode.IsControl(rune(char[0])) {
  90. if echo {
  91. stdout.Write(char)
  92. }
  93. buffer[i] = char[0]
  94. i++
  95. }
  96. }
  97. if err != nil {
  98. if err != io.EOF {
  99. fmt.Fprintf(stdout, "Read error: %v\r\n", err)
  100. }
  101. break
  102. }
  103. }
  104. return string(buffer[:i])
  105. }
  106. var readAndEchoString = func(stdin io.Reader, stdout io.Writer) string {
  107. return readStringOnRawTerminal(stdin, stdout, true)
  108. }
  109. var readString = func(stdin io.Reader, stdout io.Writer) string {
  110. return readStringOnRawTerminal(stdin, stdout, false)
  111. }
  112. stdout.SetOptionRawTerminal()
  113. cmd := rcli.Subcmd(stdout, "login", "", "Register or Login to the docker registry server")
  114. if err := cmd.Parse(args); err != nil {
  115. return nil
  116. }
  117. var username string
  118. var password string
  119. var email string
  120. fmt.Fprint(stdout, "Username (", srv.runtime.authConfig.Username, "): ")
  121. username = readAndEchoString(stdin, stdout)
  122. if username == "" {
  123. username = srv.runtime.authConfig.Username
  124. }
  125. if username != srv.runtime.authConfig.Username {
  126. fmt.Fprint(stdout, "Password: ")
  127. password = readString(stdin, stdout)
  128. if password == "" {
  129. return fmt.Errorf("Error : Password Required")
  130. }
  131. fmt.Fprint(stdout, "Email (", srv.runtime.authConfig.Email, "): ")
  132. email = readAndEchoString(stdin, stdout)
  133. if email == "" {
  134. email = srv.runtime.authConfig.Email
  135. }
  136. } else {
  137. password = srv.runtime.authConfig.Password
  138. email = srv.runtime.authConfig.Email
  139. }
  140. newAuthConfig := auth.NewAuthConfig(username, password, email, srv.runtime.root)
  141. status, err := auth.Login(newAuthConfig)
  142. if err != nil {
  143. fmt.Fprintf(stdout, "Error: %s\r\n", err)
  144. } else {
  145. srv.runtime.authConfig = newAuthConfig
  146. }
  147. if status != "" {
  148. fmt.Fprint(stdout, status)
  149. }
  150. return nil
  151. }
  152. // 'docker wait': block until a container stops
  153. func (srv *Server) CmdWait(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  154. cmd := rcli.Subcmd(stdout, "wait", "CONTAINER [CONTAINER...]", "Block until a container stops, then print its exit code.")
  155. if err := cmd.Parse(args); err != nil {
  156. return nil
  157. }
  158. if cmd.NArg() < 1 {
  159. cmd.Usage()
  160. return nil
  161. }
  162. for _, name := range cmd.Args() {
  163. if container := srv.runtime.Get(name); container != nil {
  164. fmt.Fprintln(stdout, container.Wait())
  165. } else {
  166. return fmt.Errorf("No such container: %s", name)
  167. }
  168. }
  169. return nil
  170. }
  171. // 'docker version': show version information
  172. func (srv *Server) CmdVersion(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  173. fmt.Fprintf(stdout, "Version: %s\n", VERSION)
  174. fmt.Fprintf(stdout, "Git Commit: %s\n", GIT_COMMIT)
  175. fmt.Fprintf(stdout, "Kernel: %s\n", srv.runtime.kernelVersion)
  176. if !srv.runtime.capabilities.MemoryLimit {
  177. fmt.Fprintf(stdout, "WARNING: No memory limit support\n")
  178. }
  179. if !srv.runtime.capabilities.SwapLimit {
  180. fmt.Fprintf(stdout, "WARNING: No swap limit support\n")
  181. }
  182. return nil
  183. }
  184. // 'docker info': display system-wide information.
  185. func (srv *Server) CmdInfo(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  186. images, _ := srv.runtime.graph.All()
  187. var imgcount int
  188. if images == nil {
  189. imgcount = 0
  190. } else {
  191. imgcount = len(images)
  192. }
  193. cmd := rcli.Subcmd(stdout, "info", "", "Display system-wide information.")
  194. if err := cmd.Parse(args); err != nil {
  195. return nil
  196. }
  197. if cmd.NArg() > 0 {
  198. cmd.Usage()
  199. return nil
  200. }
  201. fmt.Fprintf(stdout, "containers: %d\nversion: %s\nimages: %d\n",
  202. len(srv.runtime.List()),
  203. VERSION,
  204. imgcount)
  205. if !rcli.DEBUG_FLAG {
  206. return nil
  207. }
  208. fmt.Fprintln(stdout, "debug mode enabled")
  209. fmt.Fprintf(stdout, "fds: %d\ngoroutines: %d\n", getTotalUsedFds(), runtime.NumGoroutine())
  210. return nil
  211. }
  212. func (srv *Server) CmdStop(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  213. cmd := rcli.Subcmd(stdout, "stop", "[OPTIONS] CONTAINER [CONTAINER...]", "Stop a running container")
  214. nSeconds := cmd.Int("t", 10, "wait t seconds before killing the container")
  215. if err := cmd.Parse(args); err != nil {
  216. return nil
  217. }
  218. if cmd.NArg() < 1 {
  219. cmd.Usage()
  220. return nil
  221. }
  222. for _, name := range cmd.Args() {
  223. if container := srv.runtime.Get(name); container != nil {
  224. if err := container.Stop(*nSeconds); err != nil {
  225. return err
  226. }
  227. fmt.Fprintln(stdout, container.ShortId())
  228. } else {
  229. return fmt.Errorf("No such container: %s", name)
  230. }
  231. }
  232. return nil
  233. }
  234. func (srv *Server) CmdRestart(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  235. cmd := rcli.Subcmd(stdout, "restart", "CONTAINER [CONTAINER...]", "Restart a running container")
  236. nSeconds := cmd.Int("t", 10, "wait t seconds before killing the container")
  237. if err := cmd.Parse(args); err != nil {
  238. return nil
  239. }
  240. if cmd.NArg() < 1 {
  241. cmd.Usage()
  242. return nil
  243. }
  244. for _, name := range cmd.Args() {
  245. if container := srv.runtime.Get(name); container != nil {
  246. if err := container.Restart(*nSeconds); err != nil {
  247. return err
  248. }
  249. fmt.Fprintln(stdout, container.ShortId())
  250. } else {
  251. return fmt.Errorf("No such container: %s", name)
  252. }
  253. }
  254. return nil
  255. }
  256. func (srv *Server) CmdStart(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  257. cmd := rcli.Subcmd(stdout, "start", "CONTAINER [CONTAINER...]", "Start a stopped container")
  258. if err := cmd.Parse(args); err != nil {
  259. return nil
  260. }
  261. if cmd.NArg() < 1 {
  262. cmd.Usage()
  263. return nil
  264. }
  265. for _, name := range cmd.Args() {
  266. if container := srv.runtime.Get(name); container != nil {
  267. if err := container.Start(); err != nil {
  268. return err
  269. }
  270. fmt.Fprintln(stdout, container.ShortId())
  271. } else {
  272. return fmt.Errorf("No such container: %s", name)
  273. }
  274. }
  275. return nil
  276. }
  277. func (srv *Server) CmdInspect(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  278. cmd := rcli.Subcmd(stdout, "inspect", "CONTAINER", "Return low-level information on a container")
  279. if err := cmd.Parse(args); err != nil {
  280. return nil
  281. }
  282. if cmd.NArg() < 1 {
  283. cmd.Usage()
  284. return nil
  285. }
  286. name := cmd.Arg(0)
  287. var obj interface{}
  288. if container := srv.runtime.Get(name); container != nil {
  289. obj = container
  290. } else if image, err := srv.runtime.repositories.LookupImage(name); err == nil && image != nil {
  291. obj = image
  292. } else {
  293. // No output means the object does not exist
  294. // (easier to script since stdout and stderr are not differentiated atm)
  295. return nil
  296. }
  297. data, err := json.Marshal(obj)
  298. if err != nil {
  299. return err
  300. }
  301. indented := new(bytes.Buffer)
  302. if err = json.Indent(indented, data, "", " "); err != nil {
  303. return err
  304. }
  305. if _, err := io.Copy(stdout, indented); err != nil {
  306. return err
  307. }
  308. stdout.Write([]byte{'\n'})
  309. return nil
  310. }
  311. func (srv *Server) CmdPort(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  312. cmd := rcli.Subcmd(stdout, "port", "CONTAINER PRIVATE_PORT", "Lookup the public-facing port which is NAT-ed to PRIVATE_PORT")
  313. if err := cmd.Parse(args); err != nil {
  314. return nil
  315. }
  316. if cmd.NArg() != 2 {
  317. cmd.Usage()
  318. return nil
  319. }
  320. name := cmd.Arg(0)
  321. privatePort := cmd.Arg(1)
  322. if container := srv.runtime.Get(name); container == nil {
  323. return fmt.Errorf("No such container: %s", name)
  324. } else {
  325. if frontend, exists := container.NetworkSettings.PortMapping[privatePort]; !exists {
  326. return fmt.Errorf("No private port '%s' allocated on %s", privatePort, name)
  327. } else {
  328. fmt.Fprintln(stdout, frontend)
  329. }
  330. }
  331. return nil
  332. }
  333. // 'docker rmi IMAGE' removes all images with the name IMAGE
  334. func (srv *Server) CmdRmi(stdin io.ReadCloser, stdout io.Writer, args ...string) (err error) {
  335. cmd := rcli.Subcmd(stdout, "rmimage", "IMAGE [IMAGE...]", "Remove an image")
  336. if err := cmd.Parse(args); err != nil {
  337. return nil
  338. }
  339. if cmd.NArg() < 1 {
  340. cmd.Usage()
  341. return nil
  342. }
  343. for _, name := range cmd.Args() {
  344. img, err := srv.runtime.repositories.LookupImage(name)
  345. if err != nil {
  346. return err
  347. }
  348. if err := srv.runtime.graph.Delete(img.Id); err != nil {
  349. return err
  350. }
  351. }
  352. return nil
  353. }
  354. func (srv *Server) CmdHistory(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  355. cmd := rcli.Subcmd(stdout, "history", "IMAGE", "Show the history of an image")
  356. if err := cmd.Parse(args); err != nil {
  357. return nil
  358. }
  359. if cmd.NArg() != 1 {
  360. cmd.Usage()
  361. return nil
  362. }
  363. image, err := srv.runtime.repositories.LookupImage(cmd.Arg(0))
  364. if err != nil {
  365. return err
  366. }
  367. w := tabwriter.NewWriter(stdout, 20, 1, 3, ' ', 0)
  368. defer w.Flush()
  369. fmt.Fprintln(w, "ID\tCREATED\tCREATED BY")
  370. return image.WalkHistory(func(img *Image) error {
  371. fmt.Fprintf(w, "%s\t%s\t%s\n",
  372. srv.runtime.repositories.ImageName(img.ShortId()),
  373. HumanDuration(time.Now().Sub(img.Created))+" ago",
  374. strings.Join(img.ContainerConfig.Cmd, " "),
  375. )
  376. return nil
  377. })
  378. }
  379. func (srv *Server) CmdRm(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  380. cmd := rcli.Subcmd(stdout, "rm", "[OPTIONS] CONTAINER [CONTAINER...]", "Remove a container")
  381. v := cmd.Bool("v", false, "Remove the volumes associated to the container")
  382. if err := cmd.Parse(args); err != nil {
  383. return nil
  384. }
  385. if cmd.NArg() < 1 {
  386. cmd.Usage()
  387. return nil
  388. }
  389. volumes := make(map[string]struct{})
  390. for _, name := range cmd.Args() {
  391. container := srv.runtime.Get(name)
  392. if container == nil {
  393. return fmt.Errorf("No such container: %s", name)
  394. }
  395. // Store all the deleted containers volumes
  396. for _, volumeId := range container.Volumes {
  397. volumes[volumeId] = struct{}{}
  398. }
  399. if err := srv.runtime.Destroy(container); err != nil {
  400. fmt.Fprintln(stdout, "Error destroying container "+name+": "+err.Error())
  401. }
  402. }
  403. if *v {
  404. // Retrieve all volumes from all remaining containers
  405. usedVolumes := make(map[string]*Container)
  406. for _, container := range srv.runtime.List() {
  407. for _, containerVolumeId := range container.Volumes {
  408. usedVolumes[containerVolumeId] = container
  409. }
  410. }
  411. for volumeId := range volumes {
  412. // If the requested volu
  413. if c, exists := usedVolumes[volumeId]; exists {
  414. fmt.Fprintf(stdout, "The volume %s is used by the container %s. Impossible to remove it. Skipping.\n", volumeId, c.Id)
  415. continue
  416. }
  417. if err := srv.runtime.volumes.Delete(volumeId); err != nil {
  418. return err
  419. }
  420. }
  421. }
  422. return nil
  423. }
  424. // 'docker kill NAME' kills a running container
  425. func (srv *Server) CmdKill(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  426. cmd := rcli.Subcmd(stdout, "kill", "CONTAINER [CONTAINER...]", "Kill a running container")
  427. if err := cmd.Parse(args); err != nil {
  428. return nil
  429. }
  430. if cmd.NArg() < 1 {
  431. cmd.Usage()
  432. return nil
  433. }
  434. for _, name := range cmd.Args() {
  435. container := srv.runtime.Get(name)
  436. if container == nil {
  437. return fmt.Errorf("No such container: %s", name)
  438. }
  439. if err := container.Kill(); err != nil {
  440. fmt.Fprintln(stdout, "Error killing container "+name+": "+err.Error())
  441. }
  442. }
  443. return nil
  444. }
  445. func (srv *Server) CmdImport(stdin io.ReadCloser, stdout rcli.DockerConn, args ...string) error {
  446. stdout.Flush()
  447. cmd := rcli.Subcmd(stdout, "import", "URL|- [REPOSITORY [TAG]]", "Create a new filesystem image from the contents of a tarball")
  448. var archive io.Reader
  449. var resp *http.Response
  450. if err := cmd.Parse(args); err != nil {
  451. return nil
  452. }
  453. if cmd.NArg() < 1 {
  454. cmd.Usage()
  455. return nil
  456. }
  457. src := cmd.Arg(0)
  458. if src == "-" {
  459. archive = stdin
  460. } else {
  461. u, err := url.Parse(src)
  462. if err != nil {
  463. return err
  464. }
  465. if u.Scheme == "" {
  466. u.Scheme = "http"
  467. u.Host = src
  468. u.Path = ""
  469. }
  470. fmt.Fprintln(stdout, "Downloading from", u)
  471. // Download with curl (pretty progress bar)
  472. // If curl is not available, fallback to http.Get()
  473. resp, err = Download(u.String(), stdout)
  474. if err != nil {
  475. return err
  476. }
  477. archive = ProgressReader(resp.Body, int(resp.ContentLength), stdout, "Importing %v/%v (%v)")
  478. }
  479. img, err := srv.runtime.graph.Create(archive, nil, "Imported from "+src, "", nil)
  480. if err != nil {
  481. return err
  482. }
  483. // Optionally register the image at REPO/TAG
  484. if repository := cmd.Arg(1); repository != "" {
  485. tag := cmd.Arg(2) // Repository will handle an empty tag properly
  486. if err := srv.runtime.repositories.Set(repository, tag, img.Id, true); err != nil {
  487. return err
  488. }
  489. }
  490. fmt.Fprintln(stdout, img.ShortId())
  491. return nil
  492. }
  493. func (srv *Server) CmdPush(stdin io.ReadCloser, stdout rcli.DockerConn, args ...string) error {
  494. cmd := rcli.Subcmd(stdout, "push", "NAME", "Push an image or a repository to the registry")
  495. if err := cmd.Parse(args); err != nil {
  496. return nil
  497. }
  498. local := cmd.Arg(0)
  499. if local == "" {
  500. cmd.Usage()
  501. return nil
  502. }
  503. // If the login failed, abort
  504. if srv.runtime.authConfig == nil || srv.runtime.authConfig.Username == "" {
  505. if err := srv.CmdLogin(stdin, stdout, args...); err != nil {
  506. return err
  507. }
  508. if srv.runtime.authConfig == nil || srv.runtime.authConfig.Username == "" {
  509. return fmt.Errorf("Please login prior to push. ('docker login')")
  510. }
  511. }
  512. var remote string
  513. tmp := strings.SplitN(local, "/", 2)
  514. if len(tmp) == 1 {
  515. return fmt.Errorf(
  516. "Impossible to push a \"root\" repository. Please rename your repository in <user>/<repo> (ex: %s/%s)",
  517. srv.runtime.authConfig.Username, local)
  518. } else {
  519. remote = local
  520. }
  521. Debugf("Pushing [%s] to [%s]\n", local, remote)
  522. // Try to get the image
  523. // FIXME: Handle lookup
  524. // FIXME: Also push the tags in case of ./docker push myrepo:mytag
  525. // img, err := srv.runtime.LookupImage(cmd.Arg(0))
  526. img, err := srv.runtime.graph.Get(local)
  527. if err != nil {
  528. Debugf("The push refers to a repository [%s] (len: %d)\n", local, len(srv.runtime.repositories.Repositories[local]))
  529. // If it fails, try to get the repository
  530. if localRepo, exists := srv.runtime.repositories.Repositories[local]; exists {
  531. if err := srv.runtime.graph.PushRepository(stdout, remote, localRepo, srv.runtime.authConfig); err != nil {
  532. return err
  533. }
  534. return nil
  535. }
  536. return err
  537. }
  538. err = srv.runtime.graph.PushImage(stdout, img, srv.runtime.authConfig)
  539. if err != nil {
  540. return err
  541. }
  542. return nil
  543. }
  544. func (srv *Server) CmdPull(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  545. cmd := rcli.Subcmd(stdout, "pull", "NAME", "Pull an image or a repository from the registry")
  546. if err := cmd.Parse(args); err != nil {
  547. return nil
  548. }
  549. remote := cmd.Arg(0)
  550. if remote == "" {
  551. cmd.Usage()
  552. return nil
  553. }
  554. // FIXME: CmdPull should be a wrapper around Runtime.Pull()
  555. if srv.runtime.graph.LookupRemoteImage(remote, srv.runtime.authConfig) {
  556. if err := srv.runtime.graph.PullImage(stdout, remote, srv.runtime.authConfig); err != nil {
  557. return err
  558. }
  559. return nil
  560. }
  561. // FIXME: Allow pull repo:tag
  562. if err := srv.runtime.graph.PullRepository(stdout, remote, "", srv.runtime.repositories, srv.runtime.authConfig); err != nil {
  563. return err
  564. }
  565. return nil
  566. }
  567. func (srv *Server) CmdImages(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  568. cmd := rcli.Subcmd(stdout, "images", "[OPTIONS] [NAME]", "List images")
  569. //limit := cmd.Int("l", 0, "Only show the N most recent versions of each image")
  570. quiet := cmd.Bool("q", false, "only show numeric IDs")
  571. flAll := cmd.Bool("a", false, "show all images")
  572. if err := cmd.Parse(args); err != nil {
  573. return nil
  574. }
  575. if cmd.NArg() > 1 {
  576. cmd.Usage()
  577. return nil
  578. }
  579. var nameFilter string
  580. if cmd.NArg() == 1 {
  581. nameFilter = cmd.Arg(0)
  582. }
  583. w := tabwriter.NewWriter(stdout, 20, 1, 3, ' ', 0)
  584. if !*quiet {
  585. fmt.Fprintln(w, "REPOSITORY\tTAG\tID\tCREATED")
  586. }
  587. var allImages map[string]*Image
  588. var err error
  589. if *flAll {
  590. allImages, err = srv.runtime.graph.Map()
  591. } else {
  592. allImages, err = srv.runtime.graph.Heads()
  593. }
  594. if err != nil {
  595. return err
  596. }
  597. for name, repository := range srv.runtime.repositories.Repositories {
  598. if nameFilter != "" && name != nameFilter {
  599. continue
  600. }
  601. for tag, id := range repository {
  602. image, err := srv.runtime.graph.Get(id)
  603. if err != nil {
  604. log.Printf("Warning: couldn't load %s from %s/%s: %s", id, name, tag, err)
  605. continue
  606. }
  607. delete(allImages, id)
  608. if !*quiet {
  609. for idx, field := range []string{
  610. /* REPOSITORY */ name,
  611. /* TAG */ tag,
  612. /* ID */ TruncateId(id),
  613. /* CREATED */ HumanDuration(time.Now().Sub(image.Created)) + " ago",
  614. } {
  615. if idx == 0 {
  616. w.Write([]byte(field))
  617. } else {
  618. w.Write([]byte("\t" + field))
  619. }
  620. }
  621. w.Write([]byte{'\n'})
  622. } else {
  623. stdout.Write([]byte(image.ShortId() + "\n"))
  624. }
  625. }
  626. }
  627. // Display images which aren't part of a
  628. if nameFilter == "" {
  629. for id, image := range allImages {
  630. if !*quiet {
  631. for idx, field := range []string{
  632. /* REPOSITORY */ "<none>",
  633. /* TAG */ "<none>",
  634. /* ID */ TruncateId(id),
  635. /* CREATED */ HumanDuration(time.Now().Sub(image.Created)) + " ago",
  636. } {
  637. if idx == 0 {
  638. w.Write([]byte(field))
  639. } else {
  640. w.Write([]byte("\t" + field))
  641. }
  642. }
  643. w.Write([]byte{'\n'})
  644. } else {
  645. stdout.Write([]byte(image.ShortId() + "\n"))
  646. }
  647. }
  648. }
  649. if !*quiet {
  650. w.Flush()
  651. }
  652. return nil
  653. }
  654. func (srv *Server) CmdPs(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  655. cmd := rcli.Subcmd(stdout,
  656. "ps", "[OPTIONS]", "List containers")
  657. quiet := cmd.Bool("q", false, "Only display numeric IDs")
  658. flAll := cmd.Bool("a", false, "Show all containers. Only running containers are shown by default.")
  659. flFull := cmd.Bool("notrunc", false, "Don't truncate output")
  660. latest := cmd.Bool("l", false, "Show only the latest created container, include non-running ones.")
  661. nLast := cmd.Int("n", -1, "Show n last created containers, include non-running ones.")
  662. if err := cmd.Parse(args); err != nil {
  663. return nil
  664. }
  665. if *nLast == -1 && *latest {
  666. *nLast = 1
  667. }
  668. w := tabwriter.NewWriter(stdout, 12, 1, 3, ' ', 0)
  669. if !*quiet {
  670. fmt.Fprintln(w, "ID\tIMAGE\tCOMMAND\tCREATED\tSTATUS\tCOMMENT\tPORTS")
  671. }
  672. for i, container := range srv.runtime.List() {
  673. if !container.State.Running && !*flAll && *nLast == -1 {
  674. continue
  675. }
  676. if i == *nLast {
  677. break
  678. }
  679. if !*quiet {
  680. command := fmt.Sprintf("%s %s", container.Path, strings.Join(container.Args, " "))
  681. if !*flFull {
  682. command = Trunc(command, 20)
  683. }
  684. for idx, field := range []string{
  685. /* ID */ container.ShortId(),
  686. /* IMAGE */ srv.runtime.repositories.ImageName(container.Image),
  687. /* COMMAND */ command,
  688. /* CREATED */ HumanDuration(time.Now().Sub(container.Created)) + " ago",
  689. /* STATUS */ container.State.String(),
  690. /* COMMENT */ "",
  691. /* PORTS */ container.NetworkSettings.PortMappingHuman(),
  692. } {
  693. if idx == 0 {
  694. w.Write([]byte(field))
  695. } else {
  696. w.Write([]byte("\t" + field))
  697. }
  698. }
  699. w.Write([]byte{'\n'})
  700. } else {
  701. stdout.Write([]byte(container.ShortId() + "\n"))
  702. }
  703. }
  704. if !*quiet {
  705. w.Flush()
  706. }
  707. return nil
  708. }
  709. func (srv *Server) CmdCommit(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  710. cmd := rcli.Subcmd(stdout,
  711. "commit", "[OPTIONS] CONTAINER [REPOSITORY [TAG]]",
  712. "Create a new image from a container's changes")
  713. flComment := cmd.String("m", "", "Commit message")
  714. flAuthor := cmd.String("author", "", "Author (eg. \"John Hannibal Smith <hannibal@a-team.com>\"")
  715. flConfig := cmd.String("run", "", "Config automatically applied when the image is run. "+`(ex: {"Cmd": ["cat", "/world"], "PortSpecs": ["22"]}')`)
  716. if err := cmd.Parse(args); err != nil {
  717. return nil
  718. }
  719. containerName, repository, tag := cmd.Arg(0), cmd.Arg(1), cmd.Arg(2)
  720. if containerName == "" {
  721. cmd.Usage()
  722. return nil
  723. }
  724. var config *Config
  725. if *flConfig != "" {
  726. config = &Config{}
  727. if err := json.Unmarshal([]byte(*flConfig), config); err != nil {
  728. return err
  729. }
  730. }
  731. img, err := srv.runtime.Commit(containerName, repository, tag, *flComment, *flAuthor, config)
  732. if err != nil {
  733. return err
  734. }
  735. fmt.Fprintln(stdout, img.ShortId())
  736. return nil
  737. }
  738. func (srv *Server) CmdExport(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  739. cmd := rcli.Subcmd(stdout,
  740. "export", "CONTAINER",
  741. "Export the contents of a filesystem as a tar archive")
  742. if err := cmd.Parse(args); err != nil {
  743. return nil
  744. }
  745. name := cmd.Arg(0)
  746. if container := srv.runtime.Get(name); container != nil {
  747. data, err := container.Export()
  748. if err != nil {
  749. return err
  750. }
  751. // Stream the entire contents of the container (basically a volatile snapshot)
  752. if _, err := io.Copy(stdout, data); err != nil {
  753. return err
  754. }
  755. return nil
  756. }
  757. return fmt.Errorf("No such container: %s", name)
  758. }
  759. func (srv *Server) CmdDiff(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  760. cmd := rcli.Subcmd(stdout,
  761. "diff", "CONTAINER",
  762. "Inspect changes on a container's filesystem")
  763. if err := cmd.Parse(args); err != nil {
  764. return nil
  765. }
  766. if cmd.NArg() < 1 {
  767. cmd.Usage()
  768. return nil
  769. }
  770. if container := srv.runtime.Get(cmd.Arg(0)); container == nil {
  771. return fmt.Errorf("No such container")
  772. } else {
  773. changes, err := container.Changes()
  774. if err != nil {
  775. return err
  776. }
  777. for _, change := range changes {
  778. fmt.Fprintln(stdout, change.String())
  779. }
  780. }
  781. return nil
  782. }
  783. func (srv *Server) CmdLogs(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  784. cmd := rcli.Subcmd(stdout, "logs", "CONTAINER", "Fetch the logs of a container")
  785. if err := cmd.Parse(args); err != nil {
  786. return nil
  787. }
  788. if cmd.NArg() != 1 {
  789. cmd.Usage()
  790. return nil
  791. }
  792. name := cmd.Arg(0)
  793. if container := srv.runtime.Get(name); container != nil {
  794. logStdout, err := container.ReadLog("stdout")
  795. if err != nil {
  796. return err
  797. }
  798. logStderr, err := container.ReadLog("stderr")
  799. if err != nil {
  800. return err
  801. }
  802. // FIXME: Interpolate stdout and stderr instead of concatenating them
  803. // FIXME: Differentiate stdout and stderr in the remote protocol
  804. if _, err := io.Copy(stdout, logStdout); err != nil {
  805. return err
  806. }
  807. if _, err := io.Copy(stdout, logStderr); err != nil {
  808. return err
  809. }
  810. return nil
  811. }
  812. return fmt.Errorf("No such container: %s", cmd.Arg(0))
  813. }
  814. func (srv *Server) CmdAttach(stdin io.ReadCloser, stdout rcli.DockerConn, args ...string) error {
  815. cmd := rcli.Subcmd(stdout, "attach", "CONTAINER", "Attach to a running container")
  816. if err := cmd.Parse(args); err != nil {
  817. return nil
  818. }
  819. if cmd.NArg() != 1 {
  820. cmd.Usage()
  821. return nil
  822. }
  823. name := cmd.Arg(0)
  824. container := srv.runtime.Get(name)
  825. if container == nil {
  826. return fmt.Errorf("No such container: %s", name)
  827. }
  828. if container.State.Ghost {
  829. return fmt.Errorf("Impossible to attach to a ghost container")
  830. }
  831. if container.Config.Tty {
  832. stdout.SetOptionRawTerminal()
  833. }
  834. // Flush the options to make sure the client sets the raw mode
  835. stdout.Flush()
  836. return <-container.Attach(stdin, nil, stdout, stdout)
  837. }
  838. // Ports type - Used to parse multiple -p flags
  839. type ports []int
  840. func (p *ports) String() string {
  841. return fmt.Sprint(*p)
  842. }
  843. func (p *ports) Set(value string) error {
  844. port, err := strconv.Atoi(value)
  845. if err != nil {
  846. return fmt.Errorf("Invalid port: %v", value)
  847. }
  848. *p = append(*p, port)
  849. return nil
  850. }
  851. // ListOpts type
  852. type ListOpts []string
  853. func (opts *ListOpts) String() string {
  854. return fmt.Sprint(*opts)
  855. }
  856. func (opts *ListOpts) Set(value string) error {
  857. *opts = append(*opts, value)
  858. return nil
  859. }
  860. // AttachOpts stores arguments to 'docker run -a', eg. which streams to attach to
  861. type AttachOpts map[string]bool
  862. func NewAttachOpts() AttachOpts {
  863. return make(AttachOpts)
  864. }
  865. func (opts AttachOpts) String() string {
  866. // Cast to underlying map type to avoid infinite recursion
  867. return fmt.Sprintf("%v", map[string]bool(opts))
  868. }
  869. func (opts AttachOpts) Set(val string) error {
  870. if val != "stdin" && val != "stdout" && val != "stderr" {
  871. return fmt.Errorf("Unsupported stream name: %s", val)
  872. }
  873. opts[val] = true
  874. return nil
  875. }
  876. func (opts AttachOpts) Get(val string) bool {
  877. if res, exists := opts[val]; exists {
  878. return res
  879. }
  880. return false
  881. }
  882. // PathOpts stores a unique set of absolute paths
  883. type PathOpts map[string]struct{}
  884. func NewPathOpts() PathOpts {
  885. return make(PathOpts)
  886. }
  887. func (opts PathOpts) String() string {
  888. return fmt.Sprintf("%v", map[string]struct{}(opts))
  889. }
  890. func (opts PathOpts) Set(val string) error {
  891. if !filepath.IsAbs(val) {
  892. return fmt.Errorf("%s is not an absolute path", val)
  893. }
  894. opts[filepath.Clean(val)] = struct{}{}
  895. return nil
  896. }
  897. func (srv *Server) CmdTag(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  898. cmd := rcli.Subcmd(stdout, "tag", "[OPTIONS] IMAGE REPOSITORY [TAG]", "Tag an image into a repository")
  899. force := cmd.Bool("f", false, "Force")
  900. if err := cmd.Parse(args); err != nil {
  901. return nil
  902. }
  903. if cmd.NArg() < 2 {
  904. cmd.Usage()
  905. return nil
  906. }
  907. return srv.runtime.repositories.Set(cmd.Arg(1), cmd.Arg(2), cmd.Arg(0), *force)
  908. }
  909. func (srv *Server) CmdRun(stdin io.ReadCloser, stdout rcli.DockerConn, args ...string) error {
  910. config, err := ParseRun(args, stdout, srv.runtime.capabilities)
  911. if err != nil {
  912. return err
  913. }
  914. if config.Image == "" {
  915. fmt.Fprintln(stdout, "Error: Image not specified")
  916. return fmt.Errorf("Image not specified")
  917. }
  918. if config.Tty {
  919. stdout.SetOptionRawTerminal()
  920. }
  921. // Flush the options to make sure the client sets the raw mode
  922. // or tell the client there is no options
  923. stdout.Flush()
  924. // Create new container
  925. container, err := srv.runtime.Create(config)
  926. if err != nil {
  927. // If container not found, try to pull it
  928. if srv.runtime.graph.IsNotExist(err) {
  929. fmt.Fprintf(stdout, "Image %s not found, trying to pull it from registry.\r\n", config.Image)
  930. if err = srv.CmdPull(stdin, stdout, config.Image); err != nil {
  931. return err
  932. }
  933. if container, err = srv.runtime.Create(config); err != nil {
  934. return err
  935. }
  936. } else {
  937. return err
  938. }
  939. }
  940. var (
  941. cStdin io.ReadCloser
  942. cStdout, cStderr io.Writer
  943. )
  944. if config.AttachStdin {
  945. r, w := io.Pipe()
  946. go func() {
  947. defer w.Close()
  948. defer Debugf("Closing buffered stdin pipe")
  949. io.Copy(w, stdin)
  950. }()
  951. cStdin = r
  952. }
  953. if config.AttachStdout {
  954. cStdout = stdout
  955. }
  956. if config.AttachStderr {
  957. cStderr = stdout // FIXME: rcli can't differentiate stdout from stderr
  958. }
  959. attachErr := container.Attach(cStdin, stdin, cStdout, cStderr)
  960. Debugf("Starting\n")
  961. if err := container.Start(); err != nil {
  962. return err
  963. }
  964. if cStdout == nil && cStderr == nil {
  965. fmt.Fprintln(stdout, container.ShortId())
  966. }
  967. Debugf("Waiting for attach to return\n")
  968. <-attachErr
  969. // Expecting I/O pipe error, discarding
  970. // If we are in stdinonce mode, wait for the process to end
  971. // otherwise, simply return
  972. if config.StdinOnce && !config.Tty {
  973. container.Wait()
  974. }
  975. return nil
  976. }
  977. func NewServer(autoRestart bool) (*Server, error) {
  978. if runtime.GOARCH != "amd64" {
  979. log.Fatalf("The docker runtime currently only supports amd64 (not %s). This will change in the future. Aborting.", runtime.GOARCH)
  980. }
  981. runtime, err := NewRuntime(autoRestart)
  982. if err != nil {
  983. return nil, err
  984. }
  985. srv := &Server{
  986. runtime: runtime,
  987. }
  988. return srv, nil
  989. }
  990. type Server struct {
  991. runtime *Runtime
  992. }