commands.go 27 KB

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