commands.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990
  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. "sync"
  16. "text/tabwriter"
  17. "time"
  18. "unicode"
  19. )
  20. const VERSION = "0.1.1"
  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 [][]interface{}{
  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 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.Fprint(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. return nil
  171. }
  172. // 'docker info': display system-wide information.
  173. func (srv *Server) CmdInfo(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  174. images, _ := srv.runtime.graph.All()
  175. var imgcount int
  176. if images == nil {
  177. imgcount = 0
  178. } else {
  179. imgcount = len(images)
  180. }
  181. cmd := rcli.Subcmd(stdout, "info", "", "Display system-wide information.")
  182. if err := cmd.Parse(args); err != nil {
  183. return nil
  184. }
  185. if cmd.NArg() > 0 {
  186. cmd.Usage()
  187. return nil
  188. }
  189. fmt.Fprintf(stdout, "containers: %d\nversion: %s\nimages: %d\n",
  190. len(srv.runtime.List()),
  191. VERSION,
  192. imgcount)
  193. if !rcli.DEBUG_FLAG {
  194. return nil
  195. }
  196. fmt.Fprintln(stdout, "debug mode enabled")
  197. fmt.Fprintf(stdout, "fds: %d\ngoroutines: %d\n", getTotalUsedFds(), runtime.NumGoroutine())
  198. return nil
  199. }
  200. func (srv *Server) CmdStop(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  201. cmd := rcli.Subcmd(stdout, "stop", "[OPTIONS] NAME", "Stop a running container")
  202. if err := cmd.Parse(args); err != nil {
  203. return nil
  204. }
  205. if cmd.NArg() < 1 {
  206. cmd.Usage()
  207. return nil
  208. }
  209. for _, name := range cmd.Args() {
  210. if container := srv.runtime.Get(name); container != nil {
  211. if err := container.Stop(); err != nil {
  212. return err
  213. }
  214. fmt.Fprintln(stdout, container.ShortId())
  215. } else {
  216. return fmt.Errorf("No such container: %s", name)
  217. }
  218. }
  219. return nil
  220. }
  221. func (srv *Server) CmdRestart(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  222. cmd := rcli.Subcmd(stdout, "restart", "[OPTIONS] NAME", "Restart a running container")
  223. if err := cmd.Parse(args); err != nil {
  224. return nil
  225. }
  226. if cmd.NArg() < 1 {
  227. cmd.Usage()
  228. return nil
  229. }
  230. for _, name := range cmd.Args() {
  231. if container := srv.runtime.Get(name); container != nil {
  232. if err := container.Restart(); err != nil {
  233. return err
  234. }
  235. fmt.Fprintln(stdout, container.ShortId())
  236. } else {
  237. return fmt.Errorf("No such container: %s", name)
  238. }
  239. }
  240. return nil
  241. }
  242. func (srv *Server) CmdStart(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  243. cmd := rcli.Subcmd(stdout, "start", "[OPTIONS] NAME", "Start a stopped container")
  244. if err := cmd.Parse(args); err != nil {
  245. return nil
  246. }
  247. if cmd.NArg() < 1 {
  248. cmd.Usage()
  249. return nil
  250. }
  251. for _, name := range cmd.Args() {
  252. if container := srv.runtime.Get(name); container != nil {
  253. if err := container.Start(); err != nil {
  254. return err
  255. }
  256. fmt.Fprintln(stdout, container.ShortId())
  257. } else {
  258. return fmt.Errorf("No such container: %s", name)
  259. }
  260. }
  261. return nil
  262. }
  263. func (srv *Server) CmdInspect(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  264. cmd := rcli.Subcmd(stdout, "inspect", "[OPTIONS] CONTAINER", "Return low-level information on a container")
  265. if err := cmd.Parse(args); err != nil {
  266. return nil
  267. }
  268. if cmd.NArg() < 1 {
  269. cmd.Usage()
  270. return nil
  271. }
  272. name := cmd.Arg(0)
  273. var obj interface{}
  274. if container := srv.runtime.Get(name); container != nil {
  275. obj = container
  276. } else if image, err := srv.runtime.repositories.LookupImage(name); err == nil && image != nil {
  277. obj = image
  278. } else {
  279. // No output means the object does not exist
  280. // (easier to script since stdout and stderr are not differentiated atm)
  281. return nil
  282. }
  283. data, err := json.Marshal(obj)
  284. if err != nil {
  285. return err
  286. }
  287. indented := new(bytes.Buffer)
  288. if err = json.Indent(indented, data, "", " "); err != nil {
  289. return err
  290. }
  291. if _, err := io.Copy(stdout, indented); err != nil {
  292. return err
  293. }
  294. stdout.Write([]byte{'\n'})
  295. return nil
  296. }
  297. func (srv *Server) CmdPort(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  298. cmd := rcli.Subcmd(stdout, "port", "[OPTIONS] CONTAINER PRIVATE_PORT", "Lookup the public-facing port which is NAT-ed to PRIVATE_PORT")
  299. if err := cmd.Parse(args); err != nil {
  300. return nil
  301. }
  302. if cmd.NArg() != 2 {
  303. cmd.Usage()
  304. return nil
  305. }
  306. name := cmd.Arg(0)
  307. privatePort := cmd.Arg(1)
  308. if container := srv.runtime.Get(name); container == nil {
  309. return fmt.Errorf("No such container: %s", name)
  310. } else {
  311. if frontend, exists := container.NetworkSettings.PortMapping[privatePort]; !exists {
  312. return fmt.Errorf("No private port '%s' allocated on %s", privatePort, name)
  313. } else {
  314. fmt.Fprintln(stdout, frontend)
  315. }
  316. }
  317. return nil
  318. }
  319. // 'docker rmi NAME' removes all images with the name NAME
  320. func (srv *Server) CmdRmi(stdin io.ReadCloser, stdout io.Writer, args ...string) (err error) {
  321. cmd := rcli.Subcmd(stdout, "rmimage", "[OPTIONS] IMAGE", "Remove an image")
  322. if err := cmd.Parse(args); err != nil {
  323. return nil
  324. }
  325. if cmd.NArg() < 1 {
  326. cmd.Usage()
  327. return nil
  328. }
  329. for _, name := range cmd.Args() {
  330. if err := srv.runtime.graph.Delete(name); err != nil {
  331. return err
  332. }
  333. }
  334. return nil
  335. }
  336. func (srv *Server) CmdHistory(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  337. cmd := rcli.Subcmd(stdout, "history", "[OPTIONS] IMAGE", "Show the history of an image")
  338. if err := cmd.Parse(args); err != nil {
  339. return nil
  340. }
  341. if cmd.NArg() != 1 {
  342. cmd.Usage()
  343. return nil
  344. }
  345. image, err := srv.runtime.repositories.LookupImage(cmd.Arg(0))
  346. if err != nil {
  347. return err
  348. }
  349. w := tabwriter.NewWriter(stdout, 20, 1, 3, ' ', 0)
  350. defer w.Flush()
  351. fmt.Fprintln(w, "ID\tCREATED\tCREATED BY")
  352. return image.WalkHistory(func(img *Image) error {
  353. fmt.Fprintf(w, "%s\t%s\t%s\n",
  354. srv.runtime.repositories.ImageName(img.ShortId()),
  355. HumanDuration(time.Now().Sub(img.Created))+" ago",
  356. strings.Join(img.ContainerConfig.Cmd, " "),
  357. )
  358. return nil
  359. })
  360. }
  361. func (srv *Server) CmdRm(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  362. cmd := rcli.Subcmd(stdout, "rm", "[OPTIONS] CONTAINER", "Remove a container")
  363. if err := cmd.Parse(args); err != nil {
  364. return nil
  365. }
  366. for _, name := range cmd.Args() {
  367. container := srv.runtime.Get(name)
  368. if container == nil {
  369. return fmt.Errorf("No such container: %s", name)
  370. }
  371. if err := srv.runtime.Destroy(container); err != nil {
  372. fmt.Fprintln(stdout, "Error destroying container "+name+": "+err.Error())
  373. }
  374. }
  375. return nil
  376. }
  377. // 'docker kill NAME' kills a running container
  378. func (srv *Server) CmdKill(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  379. cmd := rcli.Subcmd(stdout, "kill", "[OPTIONS] CONTAINER [CONTAINER...]", "Kill a running container")
  380. if err := cmd.Parse(args); err != nil {
  381. return nil
  382. }
  383. for _, name := range cmd.Args() {
  384. container := srv.runtime.Get(name)
  385. if container == nil {
  386. return fmt.Errorf("No such container: %s", name)
  387. }
  388. if err := container.Kill(); err != nil {
  389. fmt.Fprintln(stdout, "Error killing container "+name+": "+err.Error())
  390. }
  391. }
  392. return nil
  393. }
  394. func (srv *Server) CmdImport(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  395. cmd := rcli.Subcmd(stdout, "import", "[OPTIONS] URL|- [REPOSITORY [TAG]]", "Create a new filesystem image from the contents of a tarball")
  396. var archive io.Reader
  397. var resp *http.Response
  398. if err := cmd.Parse(args); err != nil {
  399. return nil
  400. }
  401. src := cmd.Arg(0)
  402. if src == "" {
  403. return fmt.Errorf("Not enough arguments")
  404. } else if src == "-" {
  405. archive = stdin
  406. } else {
  407. u, err := url.Parse(src)
  408. if err != nil {
  409. return err
  410. }
  411. if u.Scheme == "" {
  412. u.Scheme = "http"
  413. u.Host = src
  414. u.Path = ""
  415. }
  416. fmt.Fprintln(stdout, "Downloading from", u)
  417. // Download with curl (pretty progress bar)
  418. // If curl is not available, fallback to http.Get()
  419. resp, err = Download(u.String(), stdout)
  420. if err != nil {
  421. return err
  422. }
  423. archive = ProgressReader(resp.Body, int(resp.ContentLength), stdout)
  424. }
  425. img, err := srv.runtime.graph.Create(archive, nil, "Imported from "+src)
  426. if err != nil {
  427. return err
  428. }
  429. // Optionally register the image at REPO/TAG
  430. if repository := cmd.Arg(1); repository != "" {
  431. tag := cmd.Arg(2) // Repository will handle an empty tag properly
  432. if err := srv.runtime.repositories.Set(repository, tag, img.Id, true); err != nil {
  433. return err
  434. }
  435. }
  436. fmt.Fprintln(stdout, img.ShortId())
  437. return nil
  438. }
  439. func (srv *Server) CmdPush(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  440. cmd := rcli.Subcmd(stdout, "push", "NAME", "Push an image or a repository to the registry")
  441. if err := cmd.Parse(args); err != nil {
  442. return nil
  443. }
  444. local := cmd.Arg(0)
  445. if local == "" {
  446. cmd.Usage()
  447. return nil
  448. }
  449. // If the login failed, abort
  450. if srv.runtime.authConfig == nil || srv.runtime.authConfig.Username == "" {
  451. if err := srv.CmdLogin(stdin, stdout, args...); err != nil {
  452. return err
  453. }
  454. if srv.runtime.authConfig == nil || srv.runtime.authConfig.Username == "" {
  455. return fmt.Errorf("Please login prior to push. ('docker login')")
  456. }
  457. }
  458. var remote string
  459. tmp := strings.SplitN(local, "/", 2)
  460. if len(tmp) == 1 {
  461. return fmt.Errorf(
  462. "Impossible to push a \"root\" repository. Please rename your repository in <user>/<repo> (ex: %s/%s)",
  463. srv.runtime.authConfig.Username, local)
  464. } else {
  465. remote = local
  466. }
  467. Debugf("Pushing [%s] to [%s]\n", local, remote)
  468. // Try to get the image
  469. // FIXME: Handle lookup
  470. // FIXME: Also push the tags in case of ./docker push myrepo:mytag
  471. // img, err := srv.runtime.LookupImage(cmd.Arg(0))
  472. img, err := srv.runtime.graph.Get(local)
  473. if err != nil {
  474. Debugf("The push refers to a repository [%s] (len: %d)\n", local, len(srv.runtime.repositories.Repositories[local]))
  475. // If it fails, try to get the repository
  476. if localRepo, exists := srv.runtime.repositories.Repositories[local]; exists {
  477. if err := srv.runtime.graph.PushRepository(stdout, remote, localRepo, srv.runtime.authConfig); err != nil {
  478. return err
  479. }
  480. return nil
  481. } else {
  482. return err
  483. }
  484. return nil
  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. 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. cStdout, err := container.StdoutPipe()
  759. if err != nil {
  760. return err
  761. }
  762. cStderr, err := container.StderrPipe()
  763. if err != nil {
  764. return err
  765. }
  766. var wg sync.WaitGroup
  767. if container.Config.OpenStdin {
  768. cStdin, err := container.StdinPipe()
  769. if err != nil {
  770. return err
  771. }
  772. wg.Add(1)
  773. go func() {
  774. Debugf("Begin stdin pipe [attach]")
  775. io.Copy(cStdin, stdin)
  776. // When stdin get closed, it means the client has been detached
  777. // Make sure all pipes are closed.
  778. if err := cStdout.Close(); err != nil {
  779. Debugf("Error closing stdin pipe: %s", err)
  780. }
  781. if err := cStderr.Close(); err != nil {
  782. Debugf("Error closing stderr pipe: %s", err)
  783. }
  784. wg.Add(-1)
  785. Debugf("End of stdin pipe [attach]")
  786. }()
  787. }
  788. wg.Add(1)
  789. go func() {
  790. Debugf("Begin stdout pipe [attach]")
  791. io.Copy(stdout, cStdout)
  792. wg.Add(-1)
  793. Debugf("End of stdout pipe [attach]")
  794. }()
  795. wg.Add(1)
  796. go func() {
  797. Debugf("Begin stderr pipe [attach]")
  798. io.Copy(stdout, cStderr)
  799. wg.Add(-1)
  800. Debugf("End of stderr pipe [attach]")
  801. }()
  802. wg.Wait()
  803. return nil
  804. }
  805. // Ports type - Used to parse multiple -p flags
  806. type ports []int
  807. func (p *ports) String() string {
  808. return fmt.Sprint(*p)
  809. }
  810. func (p *ports) Set(value string) error {
  811. port, err := strconv.Atoi(value)
  812. if err != nil {
  813. return fmt.Errorf("Invalid port: %v", value)
  814. }
  815. *p = append(*p, port)
  816. return nil
  817. }
  818. // ListOpts type
  819. type ListOpts []string
  820. func (opts *ListOpts) String() string {
  821. return fmt.Sprint(*opts)
  822. }
  823. func (opts *ListOpts) Set(value string) error {
  824. *opts = append(*opts, value)
  825. return nil
  826. }
  827. func (srv *Server) CmdTag(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  828. cmd := rcli.Subcmd(stdout, "tag", "[OPTIONS] IMAGE REPOSITORY [TAG]", "Tag an image into a repository")
  829. force := cmd.Bool("f", false, "Force")
  830. if err := cmd.Parse(args); err != nil {
  831. return nil
  832. }
  833. if cmd.NArg() < 2 {
  834. cmd.Usage()
  835. return nil
  836. }
  837. return srv.runtime.repositories.Set(cmd.Arg(1), cmd.Arg(2), cmd.Arg(0), *force)
  838. }
  839. func (srv *Server) CmdRun(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  840. config, err := ParseRun(args, stdout)
  841. if err != nil {
  842. return err
  843. }
  844. if config.Image == "" {
  845. fmt.Fprintln(stdout, "Error: Image not specified")
  846. return fmt.Errorf("Image not specified")
  847. }
  848. if len(config.Cmd) == 0 {
  849. fmt.Fprintln(stdout, "Error: Command not specified")
  850. return fmt.Errorf("Command not specified")
  851. }
  852. // Create new container
  853. container, err := srv.runtime.Create(config)
  854. if err != nil {
  855. // If container not found, try to pull it
  856. if srv.runtime.graph.IsNotExist(err) {
  857. fmt.Fprintf(stdout, "Image %s not found, trying to pull it from registry.\n", config.Image)
  858. if err = srv.CmdPull(stdin, stdout, config.Image); err != nil {
  859. return err
  860. }
  861. if container, err = srv.runtime.Create(config); err != nil {
  862. return err
  863. }
  864. } else {
  865. return err
  866. }
  867. }
  868. if config.OpenStdin {
  869. cmdStdin, err := container.StdinPipe()
  870. if err != nil {
  871. return err
  872. }
  873. if !config.Detach {
  874. Go(func() error {
  875. _, err := io.Copy(cmdStdin, stdin)
  876. cmdStdin.Close()
  877. return err
  878. })
  879. }
  880. }
  881. // Run the container
  882. if !config.Detach {
  883. cmdStderr, err := container.StderrPipe()
  884. if err != nil {
  885. return err
  886. }
  887. cmdStdout, err := container.StdoutPipe()
  888. if err != nil {
  889. return err
  890. }
  891. if err := container.Start(); err != nil {
  892. return err
  893. }
  894. sendingStdout := Go(func() error {
  895. _, err := io.Copy(stdout, cmdStdout)
  896. return err
  897. })
  898. sendingStderr := Go(func() error {
  899. _, err := io.Copy(stdout, cmdStderr)
  900. return err
  901. })
  902. errSendingStdout := <-sendingStdout
  903. errSendingStderr := <-sendingStderr
  904. if errSendingStdout != nil {
  905. return errSendingStdout
  906. }
  907. if errSendingStderr != nil {
  908. return errSendingStderr
  909. }
  910. container.Wait()
  911. } else {
  912. if err := container.Start(); err != nil {
  913. return err
  914. }
  915. fmt.Fprintln(stdout, container.ShortId())
  916. }
  917. return nil
  918. }
  919. func NewServer() (*Server, error) {
  920. if runtime.GOARCH != "amd64" {
  921. log.Fatalf("The docker runtime currently only supports amd64 (not %s). This will change in the future. Aborting.", runtime.GOARCH)
  922. }
  923. runtime, err := NewRuntime()
  924. if err != nil {
  925. return nil, err
  926. }
  927. srv := &Server{
  928. runtime: runtime,
  929. }
  930. return srv, nil
  931. }
  932. type Server struct {
  933. runtime *Runtime
  934. }