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