commands.go 26 KB

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