commands.go 27 KB

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