commands.go 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020
  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.2.1"
  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", "[OPTIONS] CONTAINER [CONTAINER...]", "Stop a running container")
  213. nSeconds := cmd.Int("t", 10, "wait t seconds before killing the container")
  214. if err := cmd.Parse(args); err != nil {
  215. return nil
  216. }
  217. if cmd.NArg() < 1 {
  218. cmd.Usage()
  219. return nil
  220. }
  221. for _, name := range cmd.Args() {
  222. if container := srv.runtime.Get(name); container != nil {
  223. if err := container.Stop(*nSeconds); err != nil {
  224. return err
  225. }
  226. fmt.Fprintln(stdout, container.ShortId())
  227. } else {
  228. return fmt.Errorf("No such container: %s", name)
  229. }
  230. }
  231. return nil
  232. }
  233. func (srv *Server) CmdRestart(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  234. cmd := rcli.Subcmd(stdout, "restart", "CONTAINER [CONTAINER...]", "Restart a running container")
  235. nSeconds := cmd.Int("t", 10, "wait t seconds before killing the container")
  236. if err := cmd.Parse(args); err != nil {
  237. return nil
  238. }
  239. if cmd.NArg() < 1 {
  240. cmd.Usage()
  241. return nil
  242. }
  243. for _, name := range cmd.Args() {
  244. if container := srv.runtime.Get(name); container != nil {
  245. if err := container.Restart(*nSeconds); err != nil {
  246. return err
  247. }
  248. fmt.Fprintln(stdout, container.ShortId())
  249. } else {
  250. return fmt.Errorf("No such container: %s", name)
  251. }
  252. }
  253. return nil
  254. }
  255. func (srv *Server) CmdStart(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  256. cmd := rcli.Subcmd(stdout, "start", "CONTAINER [CONTAINER...]", "Start a stopped container")
  257. if err := cmd.Parse(args); err != nil {
  258. return nil
  259. }
  260. if cmd.NArg() < 1 {
  261. cmd.Usage()
  262. return nil
  263. }
  264. for _, name := range cmd.Args() {
  265. if container := srv.runtime.Get(name); container != nil {
  266. if err := container.Start(); err != nil {
  267. return err
  268. }
  269. fmt.Fprintln(stdout, container.ShortId())
  270. } else {
  271. return fmt.Errorf("No such container: %s", name)
  272. }
  273. }
  274. return nil
  275. }
  276. func (srv *Server) CmdInspect(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  277. cmd := rcli.Subcmd(stdout, "inspect", "CONTAINER", "Return low-level information on a container")
  278. if err := cmd.Parse(args); err != nil {
  279. return nil
  280. }
  281. if cmd.NArg() < 1 {
  282. cmd.Usage()
  283. return nil
  284. }
  285. name := cmd.Arg(0)
  286. var obj interface{}
  287. if container := srv.runtime.Get(name); container != nil {
  288. obj = container
  289. } else if image, err := srv.runtime.repositories.LookupImage(name); err == nil && image != nil {
  290. obj = image
  291. } else {
  292. // No output means the object does not exist
  293. // (easier to script since stdout and stderr are not differentiated atm)
  294. return nil
  295. }
  296. data, err := json.Marshal(obj)
  297. if err != nil {
  298. return err
  299. }
  300. indented := new(bytes.Buffer)
  301. if err = json.Indent(indented, data, "", " "); err != nil {
  302. return err
  303. }
  304. if _, err := io.Copy(stdout, indented); err != nil {
  305. return err
  306. }
  307. stdout.Write([]byte{'\n'})
  308. return nil
  309. }
  310. func (srv *Server) CmdPort(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  311. cmd := rcli.Subcmd(stdout, "port", "CONTAINER PRIVATE_PORT", "Lookup the public-facing port which is NAT-ed to PRIVATE_PORT")
  312. if err := cmd.Parse(args); err != nil {
  313. return nil
  314. }
  315. if cmd.NArg() != 2 {
  316. cmd.Usage()
  317. return nil
  318. }
  319. name := cmd.Arg(0)
  320. privatePort := cmd.Arg(1)
  321. if container := srv.runtime.Get(name); container == nil {
  322. return fmt.Errorf("No such container: %s", name)
  323. } else {
  324. if frontend, exists := container.NetworkSettings.PortMapping[privatePort]; !exists {
  325. return fmt.Errorf("No private port '%s' allocated on %s", privatePort, name)
  326. } else {
  327. fmt.Fprintln(stdout, frontend)
  328. }
  329. }
  330. return nil
  331. }
  332. // 'docker rmi IMAGE' removes all images with the name IMAGE
  333. func (srv *Server) CmdRmi(stdin io.ReadCloser, stdout io.Writer, args ...string) (err error) {
  334. cmd := rcli.Subcmd(stdout, "rmimage", "IMAGE [IMAGE...]", "Remove an image")
  335. if err := cmd.Parse(args); err != nil {
  336. return nil
  337. }
  338. if cmd.NArg() < 1 {
  339. cmd.Usage()
  340. return nil
  341. }
  342. for _, name := range cmd.Args() {
  343. img, err := srv.runtime.repositories.LookupImage(name)
  344. if err != nil {
  345. return err
  346. }
  347. if err := srv.runtime.graph.Delete(img.Id); err != nil {
  348. return err
  349. }
  350. }
  351. return nil
  352. }
  353. func (srv *Server) CmdHistory(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  354. cmd := rcli.Subcmd(stdout, "history", "IMAGE", "Show the history of an image")
  355. if err := cmd.Parse(args); err != nil {
  356. return nil
  357. }
  358. if cmd.NArg() != 1 {
  359. cmd.Usage()
  360. return nil
  361. }
  362. image, err := srv.runtime.repositories.LookupImage(cmd.Arg(0))
  363. if err != nil {
  364. return err
  365. }
  366. w := tabwriter.NewWriter(stdout, 20, 1, 3, ' ', 0)
  367. defer w.Flush()
  368. fmt.Fprintln(w, "ID\tCREATED\tCREATED BY")
  369. return image.WalkHistory(func(img *Image) error {
  370. fmt.Fprintf(w, "%s\t%s\t%s\n",
  371. srv.runtime.repositories.ImageName(img.ShortId()),
  372. HumanDuration(time.Now().Sub(img.Created))+" ago",
  373. strings.Join(img.ContainerConfig.Cmd, " "),
  374. )
  375. return nil
  376. })
  377. }
  378. func (srv *Server) CmdRm(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  379. cmd := rcli.Subcmd(stdout, "rm", "CONTAINER [CONTAINER...]", "Remove a container")
  380. if err := cmd.Parse(args); err != nil {
  381. return nil
  382. }
  383. if cmd.NArg() < 1 {
  384. cmd.Usage()
  385. return nil
  386. }
  387. for _, name := range cmd.Args() {
  388. container := srv.runtime.Get(name)
  389. if container == nil {
  390. return fmt.Errorf("No such container: %s", name)
  391. }
  392. if err := srv.runtime.Destroy(container); err != nil {
  393. fmt.Fprintln(stdout, "Error destroying container "+name+": "+err.Error())
  394. }
  395. }
  396. return nil
  397. }
  398. // 'docker kill NAME' kills a running container
  399. func (srv *Server) CmdKill(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  400. cmd := rcli.Subcmd(stdout, "kill", "CONTAINER [CONTAINER...]", "Kill a running container")
  401. if err := cmd.Parse(args); err != nil {
  402. return nil
  403. }
  404. if cmd.NArg() < 1 {
  405. cmd.Usage()
  406. return nil
  407. }
  408. for _, name := range cmd.Args() {
  409. container := srv.runtime.Get(name)
  410. if container == nil {
  411. return fmt.Errorf("No such container: %s", name)
  412. }
  413. if err := container.Kill(); err != nil {
  414. fmt.Fprintln(stdout, "Error killing container "+name+": "+err.Error())
  415. }
  416. }
  417. return nil
  418. }
  419. func (srv *Server) CmdImport(stdin io.ReadCloser, stdout rcli.DockerConn, args ...string) error {
  420. stdout.Flush()
  421. cmd := rcli.Subcmd(stdout, "import", "URL|- [REPOSITORY [TAG]]", "Create a new filesystem image from the contents of a tarball")
  422. var archive io.Reader
  423. var resp *http.Response
  424. if err := cmd.Parse(args); err != nil {
  425. return nil
  426. }
  427. if cmd.NArg() < 1 {
  428. cmd.Usage()
  429. return nil
  430. }
  431. src := cmd.Arg(0)
  432. if src == "-" {
  433. archive = stdin
  434. } else {
  435. u, err := url.Parse(src)
  436. if err != nil {
  437. return err
  438. }
  439. if u.Scheme == "" {
  440. u.Scheme = "http"
  441. u.Host = src
  442. u.Path = ""
  443. }
  444. fmt.Fprintln(stdout, "Downloading from", u)
  445. // Download with curl (pretty progress bar)
  446. // If curl is not available, fallback to http.Get()
  447. resp, err = Download(u.String(), stdout)
  448. if err != nil {
  449. return err
  450. }
  451. archive = ProgressReader(resp.Body, int(resp.ContentLength), stdout, "Importing %v/%v (%v)")
  452. }
  453. img, err := srv.runtime.graph.Create(archive, nil, "Imported from "+src, "", nil)
  454. if err != nil {
  455. return err
  456. }
  457. // Optionally register the image at REPO/TAG
  458. if repository := cmd.Arg(1); repository != "" {
  459. tag := cmd.Arg(2) // Repository will handle an empty tag properly
  460. if err := srv.runtime.repositories.Set(repository, tag, img.Id, true); err != nil {
  461. return err
  462. }
  463. }
  464. fmt.Fprintln(stdout, img.ShortId())
  465. return nil
  466. }
  467. func (srv *Server) CmdPush(stdin io.ReadCloser, stdout rcli.DockerConn, args ...string) error {
  468. cmd := rcli.Subcmd(stdout, "push", "NAME", "Push an image or a repository to the registry")
  469. if err := cmd.Parse(args); err != nil {
  470. return nil
  471. }
  472. local := cmd.Arg(0)
  473. if local == "" {
  474. cmd.Usage()
  475. return nil
  476. }
  477. // If the login failed, abort
  478. if srv.runtime.authConfig == nil || srv.runtime.authConfig.Username == "" {
  479. if err := srv.CmdLogin(stdin, stdout, args...); err != nil {
  480. return err
  481. }
  482. if srv.runtime.authConfig == nil || srv.runtime.authConfig.Username == "" {
  483. return fmt.Errorf("Please login prior to push. ('docker login')")
  484. }
  485. }
  486. var remote string
  487. tmp := strings.SplitN(local, "/", 2)
  488. if len(tmp) == 1 {
  489. return fmt.Errorf(
  490. "Impossible to push a \"root\" repository. Please rename your repository in <user>/<repo> (ex: %s/%s)",
  491. srv.runtime.authConfig.Username, local)
  492. } else {
  493. remote = local
  494. }
  495. Debugf("Pushing [%s] to [%s]\n", local, remote)
  496. // Try to get the image
  497. // FIXME: Handle lookup
  498. // FIXME: Also push the tags in case of ./docker push myrepo:mytag
  499. // img, err := srv.runtime.LookupImage(cmd.Arg(0))
  500. img, err := srv.runtime.graph.Get(local)
  501. if err != nil {
  502. Debugf("The push refers to a repository [%s] (len: %d)\n", local, len(srv.runtime.repositories.Repositories[local]))
  503. // If it fails, try to get the repository
  504. if localRepo, exists := srv.runtime.repositories.Repositories[local]; exists {
  505. if err := srv.runtime.graph.PushRepository(stdout, remote, localRepo, srv.runtime.authConfig); err != nil {
  506. return err
  507. }
  508. return nil
  509. }
  510. return err
  511. }
  512. err = srv.runtime.graph.PushImage(stdout, img, srv.runtime.authConfig)
  513. if err != nil {
  514. return err
  515. }
  516. return nil
  517. }
  518. func (srv *Server) CmdPull(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  519. cmd := rcli.Subcmd(stdout, "pull", "NAME", "Pull an image or a repository from the registry")
  520. tag := cmd.String("t", "", "Download tagged image in repository")
  521. registry := cmd.String("registry", "", "Registry to download from. Necessary if image is pulled by ID")
  522. if err := cmd.Parse(args); err != nil {
  523. return nil
  524. }
  525. remote := cmd.Arg(0)
  526. if remote == "" {
  527. cmd.Usage()
  528. return nil
  529. }
  530. // FIXME: CmdPull should be a wrapper around Runtime.Pull()
  531. if *registry != "" {
  532. if err := srv.runtime.graph.PullImage(stdout, remote, *registry, nil); err != nil {
  533. return err
  534. }
  535. return nil
  536. }
  537. // FIXME: Allow pull repo:tag
  538. if err := srv.runtime.graph.PullRepository(stdout, remote, *tag, srv.runtime.repositories, srv.runtime.authConfig); err != nil {
  539. return err
  540. }
  541. return nil
  542. }
  543. func (srv *Server) CmdImages(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  544. cmd := rcli.Subcmd(stdout, "images", "[OPTIONS] [NAME]", "List images")
  545. //limit := cmd.Int("l", 0, "Only show the N most recent versions of each image")
  546. quiet := cmd.Bool("q", false, "only show numeric IDs")
  547. flAll := cmd.Bool("a", false, "show all images")
  548. if err := cmd.Parse(args); err != nil {
  549. return nil
  550. }
  551. if cmd.NArg() > 1 {
  552. cmd.Usage()
  553. return nil
  554. }
  555. var nameFilter string
  556. if cmd.NArg() == 1 {
  557. nameFilter = cmd.Arg(0)
  558. }
  559. w := tabwriter.NewWriter(stdout, 20, 1, 3, ' ', 0)
  560. if !*quiet {
  561. fmt.Fprintln(w, "REPOSITORY\tTAG\tID\tCREATED")
  562. }
  563. var allImages map[string]*Image
  564. var err error
  565. if *flAll {
  566. allImages, err = srv.runtime.graph.Map()
  567. } else {
  568. allImages, err = srv.runtime.graph.Heads()
  569. }
  570. if err != nil {
  571. return err
  572. }
  573. for name, repository := range srv.runtime.repositories.Repositories {
  574. if nameFilter != "" && name != nameFilter {
  575. continue
  576. }
  577. for tag, id := range repository {
  578. image, err := srv.runtime.graph.Get(id)
  579. if err != nil {
  580. log.Printf("Warning: couldn't load %s from %s/%s: %s", id, name, tag, err)
  581. continue
  582. }
  583. delete(allImages, id)
  584. if !*quiet {
  585. for idx, field := range []string{
  586. /* REPOSITORY */ name,
  587. /* TAG */ tag,
  588. /* ID */ TruncateId(id),
  589. /* CREATED */ HumanDuration(time.Now().Sub(image.Created)) + " ago",
  590. } {
  591. if idx == 0 {
  592. w.Write([]byte(field))
  593. } else {
  594. w.Write([]byte("\t" + field))
  595. }
  596. }
  597. w.Write([]byte{'\n'})
  598. } else {
  599. stdout.Write([]byte(image.ShortId() + "\n"))
  600. }
  601. }
  602. }
  603. // Display images which aren't part of a
  604. if nameFilter == "" {
  605. for id, image := range allImages {
  606. if !*quiet {
  607. for idx, field := range []string{
  608. /* REPOSITORY */ "<none>",
  609. /* TAG */ "<none>",
  610. /* ID */ TruncateId(id),
  611. /* CREATED */ HumanDuration(time.Now().Sub(image.Created)) + " ago",
  612. } {
  613. if idx == 0 {
  614. w.Write([]byte(field))
  615. } else {
  616. w.Write([]byte("\t" + field))
  617. }
  618. }
  619. w.Write([]byte{'\n'})
  620. } else {
  621. stdout.Write([]byte(image.ShortId() + "\n"))
  622. }
  623. }
  624. }
  625. if !*quiet {
  626. w.Flush()
  627. }
  628. return nil
  629. }
  630. func (srv *Server) CmdPs(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  631. cmd := rcli.Subcmd(stdout,
  632. "ps", "[OPTIONS]", "List containers")
  633. quiet := cmd.Bool("q", false, "Only display numeric IDs")
  634. flAll := cmd.Bool("a", false, "Show all containers. Only running containers are shown by default.")
  635. flFull := cmd.Bool("notrunc", false, "Don't truncate output")
  636. latest := cmd.Bool("l", false, "Show only the latest created container, include non-running ones.")
  637. nLast := cmd.Int("n", -1, "Show n last created containers, include non-running ones.")
  638. if err := cmd.Parse(args); err != nil {
  639. return nil
  640. }
  641. if *nLast == -1 && *latest {
  642. *nLast = 1
  643. }
  644. w := tabwriter.NewWriter(stdout, 12, 1, 3, ' ', 0)
  645. if !*quiet {
  646. fmt.Fprintln(w, "ID\tIMAGE\tCOMMAND\tCREATED\tSTATUS\tCOMMENT\tPORTS")
  647. }
  648. for i, container := range srv.runtime.List() {
  649. if !container.State.Running && !*flAll && *nLast == -1 {
  650. continue
  651. }
  652. if i == *nLast {
  653. break
  654. }
  655. if !*quiet {
  656. command := fmt.Sprintf("%s %s", container.Path, strings.Join(container.Args, " "))
  657. if !*flFull {
  658. command = Trunc(command, 20)
  659. }
  660. for idx, field := range []string{
  661. /* ID */ container.ShortId(),
  662. /* IMAGE */ srv.runtime.repositories.ImageName(container.Image),
  663. /* COMMAND */ command,
  664. /* CREATED */ HumanDuration(time.Now().Sub(container.Created)) + " ago",
  665. /* STATUS */ container.State.String(),
  666. /* COMMENT */ "",
  667. /* PORTS */ container.NetworkSettings.PortMappingHuman(),
  668. } {
  669. if idx == 0 {
  670. w.Write([]byte(field))
  671. } else {
  672. w.Write([]byte("\t" + field))
  673. }
  674. }
  675. w.Write([]byte{'\n'})
  676. } else {
  677. stdout.Write([]byte(container.ShortId() + "\n"))
  678. }
  679. }
  680. if !*quiet {
  681. w.Flush()
  682. }
  683. return nil
  684. }
  685. func (srv *Server) CmdCommit(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  686. cmd := rcli.Subcmd(stdout,
  687. "commit", "[OPTIONS] CONTAINER [REPOSITORY [TAG]]",
  688. "Create a new image from a container's changes")
  689. flComment := cmd.String("m", "", "Commit message")
  690. flAuthor := cmd.String("author", "", "Author (eg. \"John Hannibal Smith <hannibal@a-team.com>\"")
  691. flConfig := cmd.String("run", "", "Config automatically applied when the image is run. "+`(ex: {"Cmd": ["cat", "/world"], "PortSpecs": ["22"]}')`)
  692. if err := cmd.Parse(args); err != nil {
  693. return nil
  694. }
  695. containerName, repository, tag := cmd.Arg(0), cmd.Arg(1), cmd.Arg(2)
  696. if containerName == "" {
  697. cmd.Usage()
  698. return nil
  699. }
  700. var config *Config
  701. if *flConfig != "" {
  702. config = &Config{}
  703. if err := json.Unmarshal([]byte(*flConfig), config); err != nil {
  704. return err
  705. }
  706. }
  707. img, err := srv.runtime.Commit(containerName, repository, tag, *flComment, *flAuthor, config)
  708. if err != nil {
  709. return err
  710. }
  711. fmt.Fprintln(stdout, img.ShortId())
  712. return nil
  713. }
  714. func (srv *Server) CmdExport(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  715. cmd := rcli.Subcmd(stdout,
  716. "export", "CONTAINER",
  717. "Export the contents of a filesystem as a tar archive")
  718. if err := cmd.Parse(args); err != nil {
  719. return nil
  720. }
  721. name := cmd.Arg(0)
  722. if container := srv.runtime.Get(name); container != nil {
  723. data, err := container.Export()
  724. if err != nil {
  725. return err
  726. }
  727. // Stream the entire contents of the container (basically a volatile snapshot)
  728. if _, err := io.Copy(stdout, data); err != nil {
  729. return err
  730. }
  731. return nil
  732. }
  733. return fmt.Errorf("No such container: %s", name)
  734. }
  735. func (srv *Server) CmdDiff(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  736. cmd := rcli.Subcmd(stdout,
  737. "diff", "CONTAINER",
  738. "Inspect changes on a container's filesystem")
  739. if err := cmd.Parse(args); err != nil {
  740. return nil
  741. }
  742. if cmd.NArg() < 1 {
  743. cmd.Usage()
  744. return nil
  745. }
  746. if container := srv.runtime.Get(cmd.Arg(0)); container == nil {
  747. return fmt.Errorf("No such container")
  748. } else {
  749. changes, err := container.Changes()
  750. if err != nil {
  751. return err
  752. }
  753. for _, change := range changes {
  754. fmt.Fprintln(stdout, change.String())
  755. }
  756. }
  757. return nil
  758. }
  759. func (srv *Server) CmdLogs(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  760. cmd := rcli.Subcmd(stdout, "logs", "CONTAINER", "Fetch the logs of a container")
  761. if err := cmd.Parse(args); err != nil {
  762. return nil
  763. }
  764. if cmd.NArg() != 1 {
  765. cmd.Usage()
  766. return nil
  767. }
  768. name := cmd.Arg(0)
  769. if container := srv.runtime.Get(name); container != nil {
  770. logStdout, err := container.ReadLog("stdout")
  771. if err != nil {
  772. return err
  773. }
  774. logStderr, err := container.ReadLog("stderr")
  775. if err != nil {
  776. return err
  777. }
  778. // FIXME: Interpolate stdout and stderr instead of concatenating them
  779. // FIXME: Differentiate stdout and stderr in the remote protocol
  780. if _, err := io.Copy(stdout, logStdout); err != nil {
  781. return err
  782. }
  783. if _, err := io.Copy(stdout, logStderr); err != nil {
  784. return err
  785. }
  786. return nil
  787. }
  788. return fmt.Errorf("No such container: %s", cmd.Arg(0))
  789. }
  790. func (srv *Server) CmdAttach(stdin io.ReadCloser, stdout rcli.DockerConn, args ...string) error {
  791. cmd := rcli.Subcmd(stdout, "attach", "CONTAINER", "Attach to a running container")
  792. if err := cmd.Parse(args); err != nil {
  793. return nil
  794. }
  795. if cmd.NArg() != 1 {
  796. cmd.Usage()
  797. return nil
  798. }
  799. name := cmd.Arg(0)
  800. container := srv.runtime.Get(name)
  801. if container == nil {
  802. return fmt.Errorf("No such container: %s", name)
  803. }
  804. if container.State.Ghost {
  805. return fmt.Errorf("Impossible to attach to a ghost container")
  806. }
  807. if container.Config.Tty {
  808. stdout.SetOptionRawTerminal()
  809. }
  810. // Flush the options to make sure the client sets the raw mode
  811. stdout.Flush()
  812. return <-container.Attach(stdin, nil, stdout, stdout)
  813. }
  814. // Ports type - Used to parse multiple -p flags
  815. type ports []int
  816. func (p *ports) String() string {
  817. return fmt.Sprint(*p)
  818. }
  819. func (p *ports) Set(value string) error {
  820. port, err := strconv.Atoi(value)
  821. if err != nil {
  822. return fmt.Errorf("Invalid port: %v", value)
  823. }
  824. *p = append(*p, port)
  825. return nil
  826. }
  827. // ListOpts type
  828. type ListOpts []string
  829. func (opts *ListOpts) String() string {
  830. return fmt.Sprint(*opts)
  831. }
  832. func (opts *ListOpts) Set(value string) error {
  833. *opts = append(*opts, value)
  834. return nil
  835. }
  836. // AttachOpts stores arguments to 'docker run -a', eg. which streams to attach to
  837. type AttachOpts map[string]bool
  838. func NewAttachOpts() AttachOpts {
  839. return make(AttachOpts)
  840. }
  841. func (opts AttachOpts) String() string {
  842. // Cast to underlying map type to avoid infinite recursion
  843. return fmt.Sprintf("%v", map[string]bool(opts))
  844. }
  845. func (opts AttachOpts) Set(val string) error {
  846. if val != "stdin" && val != "stdout" && val != "stderr" {
  847. return fmt.Errorf("Unsupported stream name: %s", val)
  848. }
  849. opts[val] = true
  850. return nil
  851. }
  852. func (opts AttachOpts) Get(val string) bool {
  853. if res, exists := opts[val]; exists {
  854. return res
  855. }
  856. return false
  857. }
  858. func (srv *Server) CmdTag(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  859. cmd := rcli.Subcmd(stdout, "tag", "[OPTIONS] IMAGE REPOSITORY [TAG]", "Tag an image into a repository")
  860. force := cmd.Bool("f", false, "Force")
  861. if err := cmd.Parse(args); err != nil {
  862. return nil
  863. }
  864. if cmd.NArg() < 2 {
  865. cmd.Usage()
  866. return nil
  867. }
  868. return srv.runtime.repositories.Set(cmd.Arg(1), cmd.Arg(2), cmd.Arg(0), *force)
  869. }
  870. func (srv *Server) CmdRun(stdin io.ReadCloser, stdout rcli.DockerConn, args ...string) error {
  871. config, err := ParseRun(args, stdout, srv.runtime.capabilities)
  872. if err != nil {
  873. return err
  874. }
  875. if config.Image == "" {
  876. fmt.Fprintln(stdout, "Error: Image not specified")
  877. return fmt.Errorf("Image not specified")
  878. }
  879. if config.Tty {
  880. stdout.SetOptionRawTerminal()
  881. }
  882. // Flush the options to make sure the client sets the raw mode
  883. // or tell the client there is no options
  884. stdout.Flush()
  885. // Create new container
  886. container, err := srv.runtime.Create(config)
  887. if err != nil {
  888. // If container not found, try to pull it
  889. if srv.runtime.graph.IsNotExist(err) {
  890. fmt.Fprintf(stdout, "Image %s not found, trying to pull it from registry.\r\n", config.Image)
  891. if err = srv.CmdPull(stdin, stdout, config.Image); err != nil {
  892. return err
  893. }
  894. if container, err = srv.runtime.Create(config); err != nil {
  895. return err
  896. }
  897. } else {
  898. return err
  899. }
  900. }
  901. var (
  902. cStdin io.ReadCloser
  903. cStdout, cStderr io.Writer
  904. )
  905. if config.AttachStdin {
  906. r, w := io.Pipe()
  907. go func() {
  908. defer w.Close()
  909. defer Debugf("Closing buffered stdin pipe")
  910. io.Copy(w, stdin)
  911. }()
  912. cStdin = r
  913. }
  914. if config.AttachStdout {
  915. cStdout = stdout
  916. }
  917. if config.AttachStderr {
  918. cStderr = stdout // FIXME: rcli can't differentiate stdout from stderr
  919. }
  920. attachErr := container.Attach(cStdin, stdin, cStdout, cStderr)
  921. Debugf("Starting\n")
  922. if err := container.Start(); err != nil {
  923. return err
  924. }
  925. if cStdout == nil && cStderr == nil {
  926. fmt.Fprintln(stdout, container.ShortId())
  927. }
  928. Debugf("Waiting for attach to return\n")
  929. <-attachErr
  930. // Expecting I/O pipe error, discarding
  931. // If we are in stdinonce mode, wait for the process to end
  932. // otherwise, simply return
  933. if config.StdinOnce && !config.Tty {
  934. container.Wait()
  935. }
  936. return nil
  937. }
  938. func NewServer(autoRestart bool) (*Server, error) {
  939. if runtime.GOARCH != "amd64" {
  940. log.Fatalf("The docker runtime currently only supports amd64 (not %s). This will change in the future. Aborting.", runtime.GOARCH)
  941. }
  942. runtime, err := NewRuntime(autoRestart)
  943. if err != nil {
  944. return nil, err
  945. }
  946. srv := &Server{
  947. runtime: runtime,
  948. }
  949. return srv, nil
  950. }
  951. type Server struct {
  952. runtime *Runtime
  953. }