commands.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904
  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 cmd.Parse(args) != nil || cmd.NArg() < 1 {
  270. cmd.Usage()
  271. return nil
  272. }
  273. for _, name := range cmd.Args() {
  274. if err := srv.runtime.graph.Delete(name); err != nil {
  275. return err
  276. }
  277. }
  278. return nil
  279. }
  280. func (srv *Server) CmdHistory(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  281. cmd := rcli.Subcmd(stdout, "history", "[OPTIONS] IMAGE", "Show the history of an image")
  282. if cmd.Parse(args) != nil || cmd.NArg() != 1 {
  283. cmd.Usage()
  284. return nil
  285. }
  286. image, err := srv.runtime.repositories.LookupImage(cmd.Arg(0))
  287. if err != nil {
  288. return err
  289. }
  290. w := tabwriter.NewWriter(stdout, 20, 1, 3, ' ', 0)
  291. defer w.Flush()
  292. fmt.Fprintf(w, "ID\tCREATED\tCREATED BY\n")
  293. return image.WalkHistory(func(img *Image) error {
  294. fmt.Fprintf(w, "%s\t%s\t%s\n",
  295. srv.runtime.repositories.ImageName(img.Id),
  296. HumanDuration(time.Now().Sub(img.Created))+" ago",
  297. strings.Join(img.ContainerConfig.Cmd, " "),
  298. )
  299. return nil
  300. })
  301. }
  302. func (srv *Server) CmdRm(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  303. cmd := rcli.Subcmd(stdout, "rm", "[OPTIONS] CONTAINER", "Remove a container")
  304. if err := cmd.Parse(args); err != nil {
  305. return nil
  306. }
  307. for _, name := range cmd.Args() {
  308. container := srv.runtime.Get(name)
  309. if container == nil {
  310. return errors.New("No such container: " + name)
  311. }
  312. if err := srv.runtime.Destroy(container); err != nil {
  313. fmt.Fprintln(stdout, "Error destroying container "+name+": "+err.Error())
  314. }
  315. }
  316. return nil
  317. }
  318. // 'docker kill NAME' kills a running container
  319. func (srv *Server) CmdKill(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  320. cmd := rcli.Subcmd(stdout, "kill", "[OPTIONS] CONTAINER [CONTAINER...]", "Kill a running container")
  321. if err := cmd.Parse(args); err != nil {
  322. return nil
  323. }
  324. for _, name := range cmd.Args() {
  325. container := srv.runtime.Get(name)
  326. if container == nil {
  327. return errors.New("No such container: " + name)
  328. }
  329. if err := container.Kill(); err != nil {
  330. fmt.Fprintln(stdout, "Error killing container "+name+": "+err.Error())
  331. }
  332. }
  333. return nil
  334. }
  335. func (srv *Server) CmdImport(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  336. cmd := rcli.Subcmd(stdout, "import", "[OPTIONS] URL|- [REPOSITORY [TAG]]", "Create a new filesystem image from the contents of a tarball")
  337. var archive io.Reader
  338. var resp *http.Response
  339. if err := cmd.Parse(args); err != nil {
  340. return nil
  341. }
  342. src := cmd.Arg(0)
  343. if src == "" {
  344. return errors.New("Not enough arguments")
  345. } else if src == "-" {
  346. archive = stdin
  347. } else {
  348. u, err := url.Parse(src)
  349. if err != nil {
  350. return err
  351. }
  352. if u.Scheme == "" {
  353. u.Scheme = "http"
  354. u.Host = src
  355. u.Path = ""
  356. }
  357. fmt.Fprintf(stdout, "Downloading from %s\n", u.String())
  358. // Download with curl (pretty progress bar)
  359. // If curl is not available, fallback to http.Get()
  360. resp, err = Download(u.String(), stdout)
  361. if err != nil {
  362. return err
  363. }
  364. archive = ProgressReader(resp.Body, int(resp.ContentLength), stdout)
  365. }
  366. img, err := srv.runtime.graph.Create(archive, nil, "Imported from "+src)
  367. if err != nil {
  368. return err
  369. }
  370. // Optionally register the image at REPO/TAG
  371. if repository := cmd.Arg(1); repository != "" {
  372. tag := cmd.Arg(2) // Repository will handle an empty tag properly
  373. if err := srv.runtime.repositories.Set(repository, tag, img.Id, true); err != nil {
  374. return err
  375. }
  376. }
  377. fmt.Fprintln(stdout, img.Id)
  378. return nil
  379. }
  380. func (srv *Server) CmdPush(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  381. cmd := rcli.Subcmd(stdout, "push", "NAME", "Push an image or a repository to the registry")
  382. if err := cmd.Parse(args); err != nil {
  383. return nil
  384. }
  385. local := cmd.Arg(0)
  386. if local == "" {
  387. cmd.Usage()
  388. return nil
  389. }
  390. // If the login failed, abort
  391. if srv.runtime.authConfig == nil || srv.runtime.authConfig.Username == "" {
  392. if err := srv.CmdLogin(stdin, stdout, args...); err != nil {
  393. return err
  394. }
  395. if srv.runtime.authConfig == nil || srv.runtime.authConfig.Username == "" {
  396. return fmt.Errorf("Please login prior to push. ('docker login')")
  397. }
  398. }
  399. var remote string
  400. tmp := strings.SplitN(local, "/", 2)
  401. if len(tmp) == 1 {
  402. return fmt.Errorf(
  403. "Impossible to push a \"root\" repository. Please rename your repository in <user>/<repo> (ex: %s/%s)",
  404. srv.runtime.authConfig.Username, local)
  405. } else {
  406. remote = local
  407. }
  408. Debugf("Pushing [%s] to [%s]\n", local, remote)
  409. // Try to get the image
  410. // FIXME: Handle lookup
  411. // FIXME: Also push the tags in case of ./docker push myrepo:mytag
  412. // img, err := srv.runtime.LookupImage(cmd.Arg(0))
  413. img, err := srv.runtime.graph.Get(local)
  414. if err != nil {
  415. Debugf("The push refers to a repository [%s] (len: %d)\n", local, len(srv.runtime.repositories.Repositories[local]))
  416. // If it fails, try to get the repository
  417. if localRepo, exists := srv.runtime.repositories.Repositories[local]; exists {
  418. fmt.Fprintf(stdout, "Pushing %s (%d tags) on %s...\n", local, len(localRepo), remote)
  419. if err := srv.runtime.graph.PushRepository(stdout, remote, localRepo, srv.runtime.authConfig); err != nil {
  420. return err
  421. }
  422. fmt.Fprintf(stdout, "Push completed\n")
  423. return nil
  424. } else {
  425. return err
  426. }
  427. return nil
  428. }
  429. fmt.Fprintf(stdout, "Pushing image %s..\n", img.Id)
  430. err = srv.runtime.graph.PushImage(stdout, img, srv.runtime.authConfig)
  431. if err != nil {
  432. return err
  433. }
  434. fmt.Fprintf(stdout, "Push completed\n")
  435. return nil
  436. }
  437. func (srv *Server) CmdPull(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  438. cmd := rcli.Subcmd(stdout, "pull", "NAME", "Pull an image or a repository from the registry")
  439. if err := cmd.Parse(args); err != nil {
  440. return nil
  441. }
  442. remote := cmd.Arg(0)
  443. if remote == "" {
  444. cmd.Usage()
  445. return nil
  446. }
  447. if srv.runtime.graph.LookupRemoteImage(remote, srv.runtime.authConfig) {
  448. fmt.Fprintf(stdout, "Pulling %s...\n", remote)
  449. if err := srv.runtime.graph.PullImage(remote, srv.runtime.authConfig); err != nil {
  450. return err
  451. }
  452. fmt.Fprintf(stdout, "Pulled\n")
  453. return nil
  454. }
  455. // FIXME: Allow pull repo:tag
  456. fmt.Fprintf(stdout, "Pulling %s...\n", remote)
  457. if err := srv.runtime.graph.PullRepository(stdout, remote, "", srv.runtime.repositories, srv.runtime.authConfig); err != nil {
  458. return err
  459. }
  460. fmt.Fprintf(stdout, "Pull completed\n")
  461. return nil
  462. }
  463. func (srv *Server) CmdImages(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  464. cmd := rcli.Subcmd(stdout, "images", "[OPTIONS] [NAME]", "List images")
  465. //limit := cmd.Int("l", 0, "Only show the N most recent versions of each image")
  466. quiet := cmd.Bool("q", false, "only show numeric IDs")
  467. fl_a := cmd.Bool("a", false, "show all images")
  468. if err := cmd.Parse(args); err != nil {
  469. return nil
  470. }
  471. if cmd.NArg() > 1 {
  472. cmd.Usage()
  473. return nil
  474. }
  475. var nameFilter string
  476. if cmd.NArg() == 1 {
  477. nameFilter = cmd.Arg(0)
  478. }
  479. w := tabwriter.NewWriter(stdout, 20, 1, 3, ' ', 0)
  480. if !*quiet {
  481. fmt.Fprintf(w, "REPOSITORY\tTAG\tID\tCREATED\tPARENT\n")
  482. }
  483. var allImages map[string]*Image
  484. var err error
  485. if *fl_a {
  486. allImages, err = srv.runtime.graph.Map()
  487. } else {
  488. allImages, err = srv.runtime.graph.Heads()
  489. }
  490. if err != nil {
  491. return err
  492. }
  493. for name, repository := range srv.runtime.repositories.Repositories {
  494. if nameFilter != "" && name != nameFilter {
  495. continue
  496. }
  497. for tag, id := range repository {
  498. image, err := srv.runtime.graph.Get(id)
  499. if err != nil {
  500. log.Printf("Warning: couldn't load %s from %s/%s: %s", id, name, tag, err)
  501. continue
  502. }
  503. delete(allImages, id)
  504. if !*quiet {
  505. for idx, field := range []string{
  506. /* REPOSITORY */ name,
  507. /* TAG */ tag,
  508. /* ID */ id,
  509. /* CREATED */ HumanDuration(time.Now().Sub(image.Created)) + " ago",
  510. /* PARENT */ srv.runtime.repositories.ImageName(image.Parent),
  511. } {
  512. if idx == 0 {
  513. w.Write([]byte(field))
  514. } else {
  515. w.Write([]byte("\t" + field))
  516. }
  517. }
  518. w.Write([]byte{'\n'})
  519. } else {
  520. stdout.Write([]byte(image.Id + "\n"))
  521. }
  522. }
  523. }
  524. // Display images which aren't part of a
  525. if nameFilter == "" {
  526. for id, image := range allImages {
  527. if !*quiet {
  528. for idx, field := range []string{
  529. /* REPOSITORY */ "<none>",
  530. /* TAG */ "<none>",
  531. /* ID */ id,
  532. /* CREATED */ HumanDuration(time.Now().Sub(image.Created)) + " ago",
  533. /* PARENT */ srv.runtime.repositories.ImageName(image.Parent),
  534. } {
  535. if idx == 0 {
  536. w.Write([]byte(field))
  537. } else {
  538. w.Write([]byte("\t" + field))
  539. }
  540. }
  541. w.Write([]byte{'\n'})
  542. } else {
  543. stdout.Write([]byte(image.Id + "\n"))
  544. }
  545. }
  546. }
  547. if !*quiet {
  548. w.Flush()
  549. }
  550. return nil
  551. }
  552. func (srv *Server) CmdPs(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  553. cmd := rcli.Subcmd(stdout,
  554. "ps", "[OPTIONS]", "List containers")
  555. quiet := cmd.Bool("q", false, "Only display numeric IDs")
  556. fl_all := cmd.Bool("a", false, "Show all containers. Only running containers are shown by default.")
  557. fl_full := cmd.Bool("notrunc", false, "Don't truncate output")
  558. if err := cmd.Parse(args); err != nil {
  559. return nil
  560. }
  561. w := tabwriter.NewWriter(stdout, 12, 1, 3, ' ', 0)
  562. if !*quiet {
  563. fmt.Fprintf(w, "ID\tIMAGE\tCOMMAND\tCREATED\tSTATUS\tCOMMENT\n")
  564. }
  565. for _, container := range srv.runtime.List() {
  566. if !container.State.Running && !*fl_all {
  567. continue
  568. }
  569. if !*quiet {
  570. command := fmt.Sprintf("%s %s", container.Path, strings.Join(container.Args, " "))
  571. if !*fl_full {
  572. command = Trunc(command, 20)
  573. }
  574. for idx, field := range []string{
  575. /* ID */ container.Id,
  576. /* IMAGE */ srv.runtime.repositories.ImageName(container.Image),
  577. /* COMMAND */ command,
  578. /* CREATED */ HumanDuration(time.Now().Sub(container.Created)) + " ago",
  579. /* STATUS */ container.State.String(),
  580. /* COMMENT */ "",
  581. } {
  582. if idx == 0 {
  583. w.Write([]byte(field))
  584. } else {
  585. w.Write([]byte("\t" + field))
  586. }
  587. }
  588. w.Write([]byte{'\n'})
  589. } else {
  590. stdout.Write([]byte(container.Id + "\n"))
  591. }
  592. }
  593. if !*quiet {
  594. w.Flush()
  595. }
  596. return nil
  597. }
  598. func (srv *Server) CmdCommit(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  599. cmd := rcli.Subcmd(stdout,
  600. "commit", "[OPTIONS] CONTAINER [REPOSITORY [TAG]]",
  601. "Create a new image from a container's changes")
  602. fl_comment := cmd.String("m", "", "Commit message")
  603. if err := cmd.Parse(args); err != nil {
  604. return nil
  605. }
  606. containerName, repository, tag := cmd.Arg(0), cmd.Arg(1), cmd.Arg(2)
  607. if containerName == "" {
  608. cmd.Usage()
  609. return nil
  610. }
  611. img, err := srv.runtime.Commit(containerName, repository, tag, *fl_comment)
  612. if err != nil {
  613. return err
  614. }
  615. fmt.Fprintln(stdout, img.Id)
  616. return nil
  617. }
  618. func (srv *Server) CmdExport(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  619. cmd := rcli.Subcmd(stdout,
  620. "export", "CONTAINER",
  621. "Export the contents of a filesystem as a tar archive")
  622. if err := cmd.Parse(args); err != nil {
  623. return nil
  624. }
  625. name := cmd.Arg(0)
  626. if container := srv.runtime.Get(name); container != nil {
  627. data, err := container.Export()
  628. if err != nil {
  629. return err
  630. }
  631. // Stream the entire contents of the container (basically a volatile snapshot)
  632. if _, err := io.Copy(stdout, data); err != nil {
  633. return err
  634. }
  635. return nil
  636. }
  637. return errors.New("No such container: " + name)
  638. }
  639. func (srv *Server) CmdDiff(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  640. cmd := rcli.Subcmd(stdout,
  641. "diff", "CONTAINER [OPTIONS]",
  642. "Inspect changes on a container's filesystem")
  643. if err := cmd.Parse(args); err != nil {
  644. return nil
  645. }
  646. if cmd.NArg() < 1 {
  647. return errors.New("Not enough arguments")
  648. }
  649. if container := srv.runtime.Get(cmd.Arg(0)); container == nil {
  650. return errors.New("No such container")
  651. } else {
  652. changes, err := container.Changes()
  653. if err != nil {
  654. return err
  655. }
  656. for _, change := range changes {
  657. fmt.Fprintln(stdout, change.String())
  658. }
  659. }
  660. return nil
  661. }
  662. func (srv *Server) CmdLogs(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  663. cmd := rcli.Subcmd(stdout, "logs", "[OPTIONS] CONTAINER", "Fetch the logs of a container")
  664. if err := cmd.Parse(args); err != nil {
  665. return nil
  666. }
  667. if cmd.NArg() != 1 {
  668. cmd.Usage()
  669. return nil
  670. }
  671. name := cmd.Arg(0)
  672. if container := srv.runtime.Get(name); container != nil {
  673. log_stdout, err := container.ReadLog("stdout")
  674. if err != nil {
  675. return err
  676. }
  677. log_stderr, err := container.ReadLog("stderr")
  678. if err != nil {
  679. return err
  680. }
  681. // FIXME: Interpolate stdout and stderr instead of concatenating them
  682. // FIXME: Differentiate stdout and stderr in the remote protocol
  683. if _, err := io.Copy(stdout, log_stdout); err != nil {
  684. return err
  685. }
  686. if _, err := io.Copy(stdout, log_stderr); err != nil {
  687. return err
  688. }
  689. return nil
  690. }
  691. return errors.New("No such container: " + cmd.Arg(0))
  692. }
  693. func (srv *Server) CmdAttach(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  694. cmd := rcli.Subcmd(stdout, "attach", "[OPTIONS]", "Attach to a running container")
  695. fl_i := cmd.Bool("i", false, "Attach to stdin")
  696. fl_o := cmd.Bool("o", true, "Attach to stdout")
  697. fl_e := cmd.Bool("e", true, "Attach to stderr")
  698. if err := cmd.Parse(args); err != nil {
  699. return nil
  700. }
  701. if cmd.NArg() != 1 {
  702. cmd.Usage()
  703. return nil
  704. }
  705. name := cmd.Arg(0)
  706. container := srv.runtime.Get(name)
  707. if container == nil {
  708. return errors.New("No such container: " + name)
  709. }
  710. var wg sync.WaitGroup
  711. if *fl_i {
  712. c_stdin, err := container.StdinPipe()
  713. if err != nil {
  714. return err
  715. }
  716. wg.Add(1)
  717. go func() { io.Copy(c_stdin, stdin); wg.Add(-1) }()
  718. }
  719. if *fl_o {
  720. c_stdout, err := container.StdoutPipe()
  721. if err != nil {
  722. return err
  723. }
  724. wg.Add(1)
  725. go func() { io.Copy(stdout, c_stdout); wg.Add(-1) }()
  726. }
  727. if *fl_e {
  728. c_stderr, err := container.StderrPipe()
  729. if err != nil {
  730. return err
  731. }
  732. wg.Add(1)
  733. go func() { io.Copy(stdout, c_stderr); wg.Add(-1) }()
  734. }
  735. wg.Wait()
  736. return nil
  737. }
  738. // Ports type - Used to parse multiple -p flags
  739. type ports []int
  740. func (p *ports) String() string {
  741. return fmt.Sprint(*p)
  742. }
  743. func (p *ports) Set(value string) error {
  744. port, err := strconv.Atoi(value)
  745. if err != nil {
  746. return fmt.Errorf("Invalid port: %v", value)
  747. }
  748. *p = append(*p, port)
  749. return nil
  750. }
  751. // ListOpts type
  752. type ListOpts []string
  753. func (opts *ListOpts) String() string {
  754. return fmt.Sprint(*opts)
  755. }
  756. func (opts *ListOpts) Set(value string) error {
  757. *opts = append(*opts, value)
  758. return nil
  759. }
  760. func (srv *Server) CmdTag(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  761. cmd := rcli.Subcmd(stdout, "tag", "[OPTIONS] IMAGE REPOSITORY [TAG]", "Tag an image into a repository")
  762. force := cmd.Bool("f", false, "Force")
  763. if err := cmd.Parse(args); err != nil {
  764. return nil
  765. }
  766. if cmd.NArg() < 2 {
  767. cmd.Usage()
  768. return nil
  769. }
  770. return srv.runtime.repositories.Set(cmd.Arg(1), cmd.Arg(2), cmd.Arg(0), *force)
  771. }
  772. func (srv *Server) CmdRun(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  773. config, err := ParseRun(args)
  774. if err != nil {
  775. return err
  776. }
  777. if config.Image == "" {
  778. return fmt.Errorf("Image not specified")
  779. }
  780. if len(config.Cmd) == 0 {
  781. return fmt.Errorf("Command not specified")
  782. }
  783. // Create new container
  784. container, err := srv.runtime.Create(config)
  785. if err != nil {
  786. return errors.New("Error creating container: " + err.Error())
  787. }
  788. if config.OpenStdin {
  789. cmd_stdin, err := container.StdinPipe()
  790. if err != nil {
  791. return err
  792. }
  793. if !config.Detach {
  794. Go(func() error {
  795. _, err := io.Copy(cmd_stdin, stdin)
  796. cmd_stdin.Close()
  797. return err
  798. })
  799. }
  800. }
  801. // Run the container
  802. if !config.Detach {
  803. cmd_stderr, err := container.StderrPipe()
  804. if err != nil {
  805. return err
  806. }
  807. cmd_stdout, err := container.StdoutPipe()
  808. if err != nil {
  809. return err
  810. }
  811. if err := container.Start(); err != nil {
  812. return err
  813. }
  814. sending_stdout := Go(func() error {
  815. _, err := io.Copy(stdout, cmd_stdout)
  816. return err
  817. })
  818. sending_stderr := Go(func() error {
  819. _, err := io.Copy(stdout, cmd_stderr)
  820. return err
  821. })
  822. err_sending_stdout := <-sending_stdout
  823. err_sending_stderr := <-sending_stderr
  824. if err_sending_stdout != nil {
  825. return err_sending_stdout
  826. }
  827. if err_sending_stderr != nil {
  828. return err_sending_stderr
  829. }
  830. container.Wait()
  831. } else {
  832. if err := container.Start(); err != nil {
  833. return err
  834. }
  835. fmt.Fprintln(stdout, container.Id)
  836. }
  837. return nil
  838. }
  839. func NewServer() (*Server, error) {
  840. rand.Seed(time.Now().UTC().UnixNano())
  841. if runtime.GOARCH != "amd64" {
  842. log.Fatalf("The docker runtime currently only supports amd64 (not %s). This will change in the future. Aborting.", runtime.GOARCH)
  843. }
  844. runtime, err := NewRuntime()
  845. if err != nil {
  846. return nil, err
  847. }
  848. srv := &Server{
  849. runtime: runtime,
  850. }
  851. return srv, nil
  852. }
  853. type Server struct {
  854. runtime *Runtime
  855. }