commands.go 28 KB

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