commands.go 27 KB

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