commands.go 24 KB

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