commands.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968
  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.3"
  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. if err := cmd.Parse(args); err != nil {
  612. return nil
  613. }
  614. w := tabwriter.NewWriter(stdout, 12, 1, 3, ' ', 0)
  615. if !*quiet {
  616. fmt.Fprintln(w, "ID\tIMAGE\tCOMMAND\tCREATED\tSTATUS\tCOMMENT")
  617. }
  618. for _, container := range srv.runtime.List() {
  619. if !container.State.Running && !*flAll {
  620. continue
  621. }
  622. if !*quiet {
  623. command := fmt.Sprintf("%s %s", container.Path, strings.Join(container.Args, " "))
  624. if !*flFull {
  625. command = Trunc(command, 20)
  626. }
  627. for idx, field := range []string{
  628. /* ID */ container.ShortId(),
  629. /* IMAGE */ srv.runtime.repositories.ImageName(container.Image),
  630. /* COMMAND */ command,
  631. /* CREATED */ HumanDuration(time.Now().Sub(container.Created)) + " ago",
  632. /* STATUS */ container.State.String(),
  633. /* COMMENT */ "",
  634. } {
  635. if idx == 0 {
  636. w.Write([]byte(field))
  637. } else {
  638. w.Write([]byte("\t" + field))
  639. }
  640. }
  641. w.Write([]byte{'\n'})
  642. } else {
  643. stdout.Write([]byte(container.ShortId() + "\n"))
  644. }
  645. }
  646. if !*quiet {
  647. w.Flush()
  648. }
  649. return nil
  650. }
  651. func (srv *Server) CmdCommit(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  652. cmd := rcli.Subcmd(stdout,
  653. "commit", "[OPTIONS] CONTAINER [REPOSITORY [TAG]]",
  654. "Create a new image from a container's changes")
  655. flComment := cmd.String("m", "", "Commit message")
  656. if err := cmd.Parse(args); err != nil {
  657. return nil
  658. }
  659. containerName, repository, tag := cmd.Arg(0), cmd.Arg(1), cmd.Arg(2)
  660. if containerName == "" {
  661. cmd.Usage()
  662. return nil
  663. }
  664. img, err := srv.runtime.Commit(containerName, repository, tag, *flComment)
  665. if err != nil {
  666. return err
  667. }
  668. fmt.Fprintln(stdout, img.ShortId())
  669. return nil
  670. }
  671. func (srv *Server) CmdExport(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  672. cmd := rcli.Subcmd(stdout,
  673. "export", "CONTAINER",
  674. "Export the contents of a filesystem as a tar archive")
  675. if err := cmd.Parse(args); err != nil {
  676. return nil
  677. }
  678. name := cmd.Arg(0)
  679. if container := srv.runtime.Get(name); container != nil {
  680. data, err := container.Export()
  681. if err != nil {
  682. return err
  683. }
  684. // Stream the entire contents of the container (basically a volatile snapshot)
  685. if _, err := io.Copy(stdout, data); err != nil {
  686. return err
  687. }
  688. return nil
  689. }
  690. return fmt.Errorf("No such container: %s", name)
  691. }
  692. func (srv *Server) CmdDiff(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  693. cmd := rcli.Subcmd(stdout,
  694. "diff", "CONTAINER [OPTIONS]",
  695. "Inspect changes on a container's filesystem")
  696. if err := cmd.Parse(args); err != nil {
  697. return nil
  698. }
  699. if cmd.NArg() < 1 {
  700. return fmt.Errorf("Not enough arguments")
  701. }
  702. if container := srv.runtime.Get(cmd.Arg(0)); container == nil {
  703. return fmt.Errorf("No such container")
  704. } else {
  705. changes, err := container.Changes()
  706. if err != nil {
  707. return err
  708. }
  709. for _, change := range changes {
  710. fmt.Fprintln(stdout, change.String())
  711. }
  712. }
  713. return nil
  714. }
  715. func (srv *Server) CmdLogs(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  716. cmd := rcli.Subcmd(stdout, "logs", "[OPTIONS] CONTAINER", "Fetch the logs of a container")
  717. if err := cmd.Parse(args); err != nil {
  718. return nil
  719. }
  720. if cmd.NArg() != 1 {
  721. cmd.Usage()
  722. return nil
  723. }
  724. name := cmd.Arg(0)
  725. if container := srv.runtime.Get(name); container != nil {
  726. logStdout, err := container.ReadLog("stdout")
  727. if err != nil {
  728. return err
  729. }
  730. logStderr, err := container.ReadLog("stderr")
  731. if err != nil {
  732. return err
  733. }
  734. // FIXME: Interpolate stdout and stderr instead of concatenating them
  735. // FIXME: Differentiate stdout and stderr in the remote protocol
  736. if _, err := io.Copy(stdout, logStdout); err != nil {
  737. return err
  738. }
  739. if _, err := io.Copy(stdout, logStderr); err != nil {
  740. return err
  741. }
  742. return nil
  743. }
  744. return fmt.Errorf("No such container: %s", cmd.Arg(0))
  745. }
  746. func (srv *Server) CmdAttach(stdin io.ReadCloser, stdout rcli.DockerConn, args ...string) error {
  747. cmd := rcli.Subcmd(stdout, "attach", "CONTAINER", "Attach to a running container")
  748. if err := cmd.Parse(args); err != nil {
  749. return nil
  750. }
  751. if cmd.NArg() != 1 {
  752. cmd.Usage()
  753. return nil
  754. }
  755. name := cmd.Arg(0)
  756. container := srv.runtime.Get(name)
  757. if container == nil {
  758. return fmt.Errorf("No such container: %s", name)
  759. }
  760. if container.Config.Tty {
  761. stdout.SetOptionRawTerminal()
  762. }
  763. // Flush the options to make sure the client sets the raw mode
  764. stdout.Flush()
  765. return <-container.Attach(stdin, nil, stdout, stdout)
  766. }
  767. // Ports type - Used to parse multiple -p flags
  768. type ports []int
  769. func (p *ports) String() string {
  770. return fmt.Sprint(*p)
  771. }
  772. func (p *ports) Set(value string) error {
  773. port, err := strconv.Atoi(value)
  774. if err != nil {
  775. return fmt.Errorf("Invalid port: %v", value)
  776. }
  777. *p = append(*p, port)
  778. return nil
  779. }
  780. // ListOpts type
  781. type ListOpts []string
  782. func (opts *ListOpts) String() string {
  783. return fmt.Sprint(*opts)
  784. }
  785. func (opts *ListOpts) Set(value string) error {
  786. *opts = append(*opts, value)
  787. return nil
  788. }
  789. // AttachOpts stores arguments to 'docker run -a', eg. which streams to attach to
  790. type AttachOpts map[string]bool
  791. func NewAttachOpts() AttachOpts {
  792. return make(AttachOpts)
  793. }
  794. func (opts AttachOpts) String() string {
  795. // Cast to underlying map type to avoid infinite recursion
  796. return fmt.Sprintf("%v", map[string]bool(opts))
  797. }
  798. func (opts AttachOpts) Set(val string) error {
  799. if val != "stdin" && val != "stdout" && val != "stderr" {
  800. return fmt.Errorf("Unsupported stream name: %s", val)
  801. }
  802. opts[val] = true
  803. return nil
  804. }
  805. func (opts AttachOpts) Get(val string) bool {
  806. if res, exists := opts[val]; exists {
  807. return res
  808. }
  809. return false
  810. }
  811. func (srv *Server) CmdTag(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  812. cmd := rcli.Subcmd(stdout, "tag", "[OPTIONS] IMAGE REPOSITORY [TAG]", "Tag an image into a repository")
  813. force := cmd.Bool("f", false, "Force")
  814. if err := cmd.Parse(args); err != nil {
  815. return nil
  816. }
  817. if cmd.NArg() < 2 {
  818. cmd.Usage()
  819. return nil
  820. }
  821. return srv.runtime.repositories.Set(cmd.Arg(1), cmd.Arg(2), cmd.Arg(0), *force)
  822. }
  823. func (srv *Server) CmdRun(stdin io.ReadCloser, stdout rcli.DockerConn, args ...string) error {
  824. config, err := ParseRun(args, stdout)
  825. if err != nil {
  826. return err
  827. }
  828. if config.Image == "" {
  829. fmt.Fprintln(stdout, "Error: Image not specified")
  830. return fmt.Errorf("Image not specified")
  831. }
  832. if len(config.Cmd) == 0 {
  833. fmt.Fprintln(stdout, "Error: Command not specified")
  834. return fmt.Errorf("Command not specified")
  835. }
  836. if config.Tty {
  837. stdout.SetOptionRawTerminal()
  838. }
  839. // Flush the options to make sure the client sets the raw mode
  840. // or tell the client there is no options
  841. stdout.Flush()
  842. // Create new container
  843. container, err := srv.runtime.Create(config)
  844. if err != nil {
  845. // If container not found, try to pull it
  846. if srv.runtime.graph.IsNotExist(err) {
  847. fmt.Fprintf(stdout, "Image %s not found, trying to pull it from registry.\n", config.Image)
  848. if err = srv.CmdPull(stdin, stdout, config.Image); err != nil {
  849. return err
  850. }
  851. if container, err = srv.runtime.Create(config); err != nil {
  852. return err
  853. }
  854. } else {
  855. return err
  856. }
  857. }
  858. var (
  859. cStdin io.ReadCloser
  860. cStdout, cStderr io.Writer
  861. )
  862. if config.AttachStdin {
  863. r, w := io.Pipe()
  864. go func() {
  865. defer w.Close()
  866. defer Debugf("Closing buffered stdin pipe")
  867. io.Copy(w, stdin)
  868. }()
  869. cStdin = r
  870. }
  871. if config.AttachStdout {
  872. cStdout = stdout
  873. }
  874. if config.AttachStderr {
  875. cStderr = stdout // FIXME: rcli can't differentiate stdout from stderr
  876. }
  877. attachErr := container.Attach(cStdin, stdin, cStdout, cStderr)
  878. Debugf("Starting\n")
  879. if err := container.Start(); err != nil {
  880. return err
  881. }
  882. if cStdout == nil && cStderr == nil {
  883. fmt.Fprintln(stdout, container.ShortId())
  884. }
  885. Debugf("Waiting for attach to return\n")
  886. <-attachErr
  887. // Expecting I/O pipe error, discarding
  888. return nil
  889. }
  890. func NewServer() (*Server, error) {
  891. if runtime.GOARCH != "amd64" {
  892. log.Fatalf("The docker runtime currently only supports amd64 (not %s). This will change in the future. Aborting.", runtime.GOARCH)
  893. }
  894. runtime, err := NewRuntime()
  895. if err != nil {
  896. return nil, err
  897. }
  898. srv := &Server{
  899. runtime: runtime,
  900. }
  901. return srv, nil
  902. }
  903. type Server struct {
  904. runtime *Runtime
  905. }