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