commands.go 26 KB

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