commands.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977
  1. package commands
  2. import (
  3. "bufio"
  4. "bytes"
  5. "encoding/json"
  6. "errors"
  7. "fmt"
  8. "github.com/dotcloud/docker"
  9. "github.com/dotcloud/docker/fs"
  10. "github.com/dotcloud/docker/future"
  11. "github.com/dotcloud/docker/rcli"
  12. "io"
  13. "net/http"
  14. "net/url"
  15. "os"
  16. "path"
  17. "strconv"
  18. "strings"
  19. "sync"
  20. "text/tabwriter"
  21. "time"
  22. )
  23. const VERSION = "0.0.1"
  24. func (srv *Server) Name() string {
  25. return "docker"
  26. }
  27. // FIXME: Stop violating DRY by repeating usage here and in Subcmd declarations
  28. func (srv *Server) Help() string {
  29. help := "Usage: docker COMMAND [arg...]\n\nA self-sufficient runtime for linux containers.\n\nCommands:\n"
  30. for _, cmd := range [][]interface{}{
  31. {"run", "Run a command in a container"},
  32. {"ps", "Display a list of containers"},
  33. {"import", "Create a new filesystem image from the contents of a tarball"},
  34. {"attach", "Attach to a running container"},
  35. {"cat", "Write the contents of a container's file to standard output"},
  36. {"commit", "Create a new image from a container's changes"},
  37. {"cp", "Create a copy of IMAGE and call it NAME"},
  38. {"debug", "(debug only) (No documentation available)"},
  39. {"diff", "Inspect changes on a container's filesystem"},
  40. {"images", "List images"},
  41. {"info", "Display system-wide information"},
  42. {"inspect", "Return low-level information on a container"},
  43. {"kill", "Kill a running container"},
  44. {"layers", "(debug only) List filesystem layers"},
  45. {"logs", "Fetch the logs of a container"},
  46. {"ls", "List the contents of a container's directory"},
  47. {"mirror", "(debug only) (No documentation available)"},
  48. {"port", "Lookup the public-facing port which is NAT-ed to PRIVATE_PORT"},
  49. {"ps", "List containers"},
  50. {"reset", "Reset changes to a container's filesystem"},
  51. {"restart", "Restart a running container"},
  52. {"rm", "Remove a container"},
  53. {"rmimage", "Remove an image"},
  54. {"run", "Run a command in a new container"},
  55. {"start", "Start a stopped container"},
  56. {"stop", "Stop a running container"},
  57. {"tar", "Stream the contents of a container as a tar archive"},
  58. {"umount", "(debug only) Mount a container's filesystem"},
  59. {"version", "Show the docker version information"},
  60. {"wait", "Block until a container stops, then print its exit code"},
  61. {"web", "A web UI for docker"},
  62. {"write", "Write the contents of standard input to a container's file"},
  63. } {
  64. help += fmt.Sprintf(" %-10.10s%s\n", cmd...)
  65. }
  66. return help
  67. }
  68. // 'docker wait': block until a container stops
  69. func (srv *Server) CmdWait(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  70. cmd := rcli.Subcmd(stdout, "wait", "[OPTIONS] NAME", "Block until a container stops, then print its exit code.")
  71. if err := cmd.Parse(args); err != nil {
  72. return nil
  73. }
  74. if cmd.NArg() < 1 {
  75. cmd.Usage()
  76. return nil
  77. }
  78. for _, name := range cmd.Args() {
  79. if container := srv.containers.Get(name); container != nil {
  80. fmt.Fprintln(stdout, container.Wait())
  81. } else {
  82. return errors.New("No such container: " + name)
  83. }
  84. }
  85. return nil
  86. }
  87. // 'docker version': show version information
  88. func (srv *Server) CmdVersion(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  89. fmt.Fprintf(stdout, "Version:%s\n", VERSION)
  90. return nil
  91. }
  92. // 'docker info': display system-wide information.
  93. func (srv *Server) CmdInfo(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  94. images, _ := srv.images.Images()
  95. var imgcount int
  96. if images == nil {
  97. imgcount = 0
  98. } else {
  99. imgcount = len(images)
  100. }
  101. cmd := rcli.Subcmd(stdout, "info", "", "Display system-wide information.")
  102. if err := cmd.Parse(args); err != nil {
  103. return nil
  104. }
  105. if cmd.NArg() > 0 {
  106. cmd.Usage()
  107. return nil
  108. }
  109. fmt.Fprintf(stdout, "containers: %d\nversion: %s\nimages: %d\n",
  110. len(srv.containers.List()),
  111. VERSION,
  112. imgcount)
  113. return nil
  114. }
  115. func (srv *Server) CmdStop(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  116. cmd := rcli.Subcmd(stdout, "stop", "[OPTIONS] NAME", "Stop a running container")
  117. if err := cmd.Parse(args); err != nil {
  118. return nil
  119. }
  120. if cmd.NArg() < 1 {
  121. cmd.Usage()
  122. return nil
  123. }
  124. for _, name := range cmd.Args() {
  125. if container := srv.containers.Get(name); container != nil {
  126. if err := container.Stop(); err != nil {
  127. return err
  128. }
  129. fmt.Fprintln(stdout, container.Id)
  130. } else {
  131. return errors.New("No such container: " + name)
  132. }
  133. }
  134. return nil
  135. }
  136. func (srv *Server) CmdRestart(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  137. cmd := rcli.Subcmd(stdout, "restart", "[OPTIONS] NAME", "Restart a running container")
  138. if err := cmd.Parse(args); err != nil {
  139. return nil
  140. }
  141. if cmd.NArg() < 1 {
  142. cmd.Usage()
  143. return nil
  144. }
  145. for _, name := range cmd.Args() {
  146. if container := srv.containers.Get(name); container != nil {
  147. if err := container.Restart(); err != nil {
  148. return err
  149. }
  150. fmt.Fprintln(stdout, container.Id)
  151. } else {
  152. return errors.New("No such container: " + name)
  153. }
  154. }
  155. return nil
  156. }
  157. func (srv *Server) CmdStart(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  158. cmd := rcli.Subcmd(stdout, "start", "[OPTIONS] NAME", "Start a stopped container")
  159. if err := cmd.Parse(args); err != nil {
  160. return nil
  161. }
  162. if cmd.NArg() < 1 {
  163. cmd.Usage()
  164. return nil
  165. }
  166. for _, name := range cmd.Args() {
  167. if container := srv.containers.Get(name); container != nil {
  168. if err := container.Start(); err != nil {
  169. return err
  170. }
  171. fmt.Fprintln(stdout, container.Id)
  172. } else {
  173. return errors.New("No such container: " + name)
  174. }
  175. }
  176. return nil
  177. }
  178. func (srv *Server) CmdUmount(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  179. cmd := rcli.Subcmd(stdout, "umount", "[OPTIONS] NAME", "umount a container's filesystem (debug only)")
  180. if err := cmd.Parse(args); err != nil {
  181. return nil
  182. }
  183. if cmd.NArg() < 1 {
  184. cmd.Usage()
  185. return nil
  186. }
  187. for _, name := range cmd.Args() {
  188. if container := srv.containers.Get(name); container != nil {
  189. if err := container.Mountpoint.Umount(); err != nil {
  190. return err
  191. }
  192. fmt.Fprintln(stdout, container.Id)
  193. } else {
  194. return errors.New("No such container: " + name)
  195. }
  196. }
  197. return nil
  198. }
  199. func (srv *Server) CmdMount(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  200. cmd := rcli.Subcmd(stdout, "umount", "[OPTIONS] NAME", "mount a container's filesystem (debug only)")
  201. if err := cmd.Parse(args); err != nil {
  202. return nil
  203. }
  204. if cmd.NArg() < 1 {
  205. cmd.Usage()
  206. return nil
  207. }
  208. for _, name := range cmd.Args() {
  209. if container := srv.containers.Get(name); container != nil {
  210. if err := container.Mountpoint.EnsureMounted(); err != nil {
  211. return err
  212. }
  213. fmt.Fprintln(stdout, container.Id)
  214. } else {
  215. return errors.New("No such container: " + name)
  216. }
  217. }
  218. return nil
  219. }
  220. func (srv *Server) CmdCat(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  221. cmd := rcli.Subcmd(stdout, "cat", "[OPTIONS] CONTAINER PATH", "write the contents of a container's file to standard output")
  222. if err := cmd.Parse(args); err != nil {
  223. return nil
  224. }
  225. if cmd.NArg() < 2 {
  226. cmd.Usage()
  227. return nil
  228. }
  229. name, path := cmd.Arg(0), cmd.Arg(1)
  230. if container := srv.containers.Get(name); container != nil {
  231. if f, err := container.Mountpoint.OpenFile(path, os.O_RDONLY, 0); err != nil {
  232. return err
  233. } else if _, err := io.Copy(stdout, f); err != nil {
  234. return err
  235. }
  236. return nil
  237. }
  238. return errors.New("No such container: " + name)
  239. }
  240. func (srv *Server) CmdWrite(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  241. cmd := rcli.Subcmd(stdout, "write", "[OPTIONS] CONTAINER PATH", "write the contents of standard input to a container's file")
  242. if err := cmd.Parse(args); err != nil {
  243. return nil
  244. }
  245. if cmd.NArg() < 2 {
  246. cmd.Usage()
  247. return nil
  248. }
  249. name, path := cmd.Arg(0), cmd.Arg(1)
  250. if container := srv.containers.Get(name); container != nil {
  251. if f, err := container.Mountpoint.OpenFile(path, os.O_WRONLY|os.O_CREATE, 0600); err != nil {
  252. return err
  253. } else if _, err := io.Copy(f, stdin); err != nil {
  254. return err
  255. }
  256. return nil
  257. }
  258. return errors.New("No such container: " + name)
  259. }
  260. func (srv *Server) CmdLs(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  261. cmd := rcli.Subcmd(stdout, "ls", "[OPTIONS] CONTAINER PATH", "List the contents of a container's directory")
  262. if err := cmd.Parse(args); err != nil {
  263. return nil
  264. }
  265. if cmd.NArg() < 2 {
  266. cmd.Usage()
  267. return nil
  268. }
  269. name, path := cmd.Arg(0), cmd.Arg(1)
  270. if container := srv.containers.Get(name); container != nil {
  271. if files, err := container.Mountpoint.ReadDir(path); err != nil {
  272. return err
  273. } else {
  274. for _, f := range files {
  275. fmt.Fprintln(stdout, f.Name())
  276. }
  277. }
  278. return nil
  279. }
  280. return errors.New("No such container: " + name)
  281. }
  282. func (srv *Server) CmdInspect(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  283. cmd := rcli.Subcmd(stdout, "inspect", "[OPTIONS] CONTAINER", "Return low-level information on a container")
  284. if err := cmd.Parse(args); err != nil {
  285. return nil
  286. }
  287. if cmd.NArg() < 1 {
  288. cmd.Usage()
  289. return nil
  290. }
  291. name := cmd.Arg(0)
  292. var obj interface{}
  293. if container := srv.containers.Get(name); container != nil {
  294. obj = container
  295. //} else if image, err := srv.images.List(name); image != nil {
  296. // obj = image
  297. } else {
  298. return errors.New("No such container or image: " + name)
  299. }
  300. data, err := json.Marshal(obj)
  301. if err != nil {
  302. return err
  303. }
  304. indented := new(bytes.Buffer)
  305. if err = json.Indent(indented, data, "", " "); err != nil {
  306. return err
  307. }
  308. if _, err := io.Copy(stdout, indented); err != nil {
  309. return err
  310. }
  311. return nil
  312. }
  313. func (srv *Server) CmdPort(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  314. cmd := rcli.Subcmd(stdout, "port", "[OPTIONS] CONTAINER PRIVATE_PORT", "Lookup the public-facing port which is NAT-ed to PRIVATE_PORT")
  315. if err := cmd.Parse(args); err != nil {
  316. return nil
  317. }
  318. if cmd.NArg() != 2 {
  319. cmd.Usage()
  320. return nil
  321. }
  322. name := cmd.Arg(0)
  323. privatePort := cmd.Arg(1)
  324. if container := srv.containers.Get(name); container == nil {
  325. return errors.New("No such container: " + name)
  326. } else {
  327. if frontend, exists := container.NetworkSettings.PortMapping[privatePort]; !exists {
  328. return fmt.Errorf("No private port '%s' allocated on %s", privatePort, name)
  329. } else {
  330. fmt.Fprintln(stdout, frontend)
  331. }
  332. }
  333. return nil
  334. }
  335. // 'docker rmi NAME' removes all images with the name NAME
  336. // func (srv *Server) CmdRmi(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  337. // cmd := rcli.Subcmd(stdout, "rmimage", "[OPTIONS] IMAGE", "Remove an image")
  338. // fl_regexp := cmd.Bool("r", false, "Use IMAGE as a regular expression instead of an exact name")
  339. // if err := cmd.Parse(args); err != nil {
  340. // cmd.Usage()
  341. // return nil
  342. // }
  343. // if cmd.NArg() < 1 {
  344. // cmd.Usage()
  345. // return nil
  346. // }
  347. // for _, name := range cmd.Args() {
  348. // var err error
  349. // if *fl_regexp {
  350. // err = srv.images.DeleteMatch(name)
  351. // } else {
  352. // image := srv.images.Find(name)
  353. // if image == nil {
  354. // return errors.New("No such image: " + name)
  355. // }
  356. // err = srv.images.Delete(name)
  357. // }
  358. // if err != nil {
  359. // return err
  360. // }
  361. // }
  362. // return nil
  363. // }
  364. func (srv *Server) CmdRm(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  365. cmd := rcli.Subcmd(stdout, "rm", "[OPTIONS] CONTAINER", "Remove a container")
  366. if err := cmd.Parse(args); err != nil {
  367. return nil
  368. }
  369. for _, name := range cmd.Args() {
  370. container := srv.containers.Get(name)
  371. if container == nil {
  372. return errors.New("No such container: " + name)
  373. }
  374. if err := srv.containers.Destroy(container); err != nil {
  375. fmt.Fprintln(stdout, "Error destroying container "+name+": "+err.Error())
  376. }
  377. }
  378. return nil
  379. }
  380. // 'docker kill NAME' kills a running container
  381. func (srv *Server) CmdKill(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  382. cmd := rcli.Subcmd(stdout, "kill", "[OPTIONS] CONTAINER [CONTAINER...]", "Kill a running container")
  383. if err := cmd.Parse(args); err != nil {
  384. return nil
  385. }
  386. for _, name := range cmd.Args() {
  387. container := srv.containers.Get(name)
  388. if container == nil {
  389. return errors.New("No such container: " + name)
  390. }
  391. if err := container.Kill(); err != nil {
  392. fmt.Fprintln(stdout, "Error killing container "+name+": "+err.Error())
  393. }
  394. }
  395. return nil
  396. }
  397. func (srv *Server) CmdImport(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  398. cmd := rcli.Subcmd(stdout, "import", "[OPTIONS] NAME", "Create a new filesystem image from the contents of a tarball")
  399. fl_stdin := cmd.Bool("stdin", false, "Read tarball from stdin")
  400. if err := cmd.Parse(args); err != nil {
  401. return nil
  402. }
  403. var archive io.Reader
  404. name := cmd.Arg(0)
  405. if name == "" {
  406. return errors.New("Not enough arguments")
  407. }
  408. if *fl_stdin {
  409. archive = stdin
  410. } else {
  411. u, err := url.Parse(name)
  412. if err != nil {
  413. return err
  414. }
  415. if u.Scheme == "" {
  416. u.Scheme = "http"
  417. }
  418. // FIXME: hardcode a mirror URL that does not depend on a single provider.
  419. if u.Host == "" {
  420. u.Host = "s3.amazonaws.com"
  421. u.Path = path.Join("/docker.io/images", u.Path)
  422. }
  423. fmt.Fprintf(stdout, "Downloading from %s\n", u.String())
  424. // Download with curl (pretty progress bar)
  425. // If curl is not available, fallback to http.Get()
  426. archive, err = future.Curl(u.String(), stdout)
  427. if err != nil {
  428. if resp, err := http.Get(u.String()); err != nil {
  429. return err
  430. } else {
  431. archive = resp.Body
  432. }
  433. }
  434. }
  435. fmt.Fprintf(stdout, "Unpacking to %s\n", name)
  436. img, err := srv.images.Create(archive, nil, name, "")
  437. if err != nil {
  438. return err
  439. }
  440. fmt.Fprintln(stdout, img.Id)
  441. return nil
  442. }
  443. func (srv *Server) CmdImages(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  444. cmd := rcli.Subcmd(stdout, "images", "[OPTIONS] [NAME]", "List images")
  445. limit := cmd.Int("l", 0, "Only show the N most recent versions of each image")
  446. quiet := cmd.Bool("q", false, "only show numeric IDs")
  447. if err := cmd.Parse(args); err != nil {
  448. return nil
  449. }
  450. if cmd.NArg() > 1 {
  451. cmd.Usage()
  452. return nil
  453. }
  454. var nameFilter string
  455. if cmd.NArg() == 1 {
  456. nameFilter = cmd.Arg(0)
  457. }
  458. w := tabwriter.NewWriter(stdout, 20, 1, 3, ' ', 0)
  459. if !*quiet {
  460. fmt.Fprintf(w, "NAME\tID\tCREATED\tPARENT\n")
  461. }
  462. paths, err := srv.images.Paths()
  463. if err != nil {
  464. return err
  465. }
  466. for _, name := range paths {
  467. if nameFilter != "" && nameFilter != name {
  468. continue
  469. }
  470. ids, err := srv.images.List(name)
  471. if err != nil {
  472. return err
  473. }
  474. for idx, img := range ids {
  475. if *limit > 0 && idx >= *limit {
  476. break
  477. }
  478. if !*quiet {
  479. for idx, field := range []string{
  480. /* NAME */ name,
  481. /* ID */ img.Id,
  482. /* CREATED */ future.HumanDuration(time.Now().Sub(time.Unix(img.Created, 0))) + " ago",
  483. /* PARENT */ img.Parent,
  484. } {
  485. if idx == 0 {
  486. w.Write([]byte(field))
  487. } else {
  488. w.Write([]byte("\t" + field))
  489. }
  490. }
  491. w.Write([]byte{'\n'})
  492. } else {
  493. stdout.Write([]byte(img.Id + "\n"))
  494. }
  495. }
  496. }
  497. if !*quiet {
  498. w.Flush()
  499. }
  500. return nil
  501. }
  502. func (srv *Server) CmdPs(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  503. cmd := rcli.Subcmd(stdout,
  504. "ps", "[OPTIONS]", "List containers")
  505. quiet := cmd.Bool("q", false, "Only display numeric IDs")
  506. fl_all := cmd.Bool("a", false, "Show all containers. Only running containers are shown by default.")
  507. fl_full := cmd.Bool("notrunc", false, "Don't truncate output")
  508. if err := cmd.Parse(args); err != nil {
  509. return nil
  510. }
  511. w := tabwriter.NewWriter(stdout, 12, 1, 3, ' ', 0)
  512. if !*quiet {
  513. fmt.Fprintf(w, "ID\tIMAGE\tCOMMAND\tCREATED\tSTATUS\tCOMMENT\n")
  514. }
  515. for _, container := range srv.containers.List() {
  516. comment := container.GetUserData("comment")
  517. if !container.State.Running && !*fl_all {
  518. continue
  519. }
  520. if !*quiet {
  521. command := fmt.Sprintf("%s %s", container.Path, strings.Join(container.Args, " "))
  522. if !*fl_full {
  523. command = docker.Trunc(command, 20)
  524. }
  525. for idx, field := range []string{
  526. /* ID */ container.Id,
  527. /* IMAGE */ container.GetUserData("image"),
  528. /* COMMAND */ command,
  529. /* CREATED */ future.HumanDuration(time.Now().Sub(container.Created)) + " ago",
  530. /* STATUS */ container.State.String(),
  531. /* COMMENT */ comment,
  532. } {
  533. if idx == 0 {
  534. w.Write([]byte(field))
  535. } else {
  536. w.Write([]byte("\t" + field))
  537. }
  538. }
  539. w.Write([]byte{'\n'})
  540. } else {
  541. stdout.Write([]byte(container.Id + "\n"))
  542. }
  543. }
  544. if !*quiet {
  545. w.Flush()
  546. }
  547. return nil
  548. }
  549. func (srv *Server) CmdLayers(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  550. cmd := rcli.Subcmd(stdout,
  551. "layers", "[OPTIONS]",
  552. "List filesystem layers (debug only)")
  553. if err := cmd.Parse(args); err != nil {
  554. return nil
  555. }
  556. for _, layer := range srv.images.Layers() {
  557. fmt.Fprintln(stdout, layer)
  558. }
  559. return nil
  560. }
  561. func (srv *Server) CmdCp(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  562. cmd := rcli.Subcmd(stdout,
  563. "cp", "[OPTIONS] IMAGE NAME",
  564. "Create a copy of IMAGE and call it NAME")
  565. if err := cmd.Parse(args); err != nil {
  566. return nil
  567. }
  568. if image, err := srv.images.Get(cmd.Arg(0)); err != nil {
  569. return err
  570. } else if image == nil {
  571. return errors.New("Image " + cmd.Arg(0) + " does not exist")
  572. } else {
  573. if img, err := image.Copy(cmd.Arg(1)); err != nil {
  574. return err
  575. } else {
  576. fmt.Fprintln(stdout, img.Id)
  577. }
  578. }
  579. return nil
  580. }
  581. func (srv *Server) CmdCommit(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  582. cmd := rcli.Subcmd(stdout,
  583. "commit", "[OPTIONS] CONTAINER [DEST]",
  584. "Create a new image from a container's changes")
  585. if err := cmd.Parse(args); err != nil {
  586. return nil
  587. }
  588. containerName, imgName := cmd.Arg(0), cmd.Arg(1)
  589. if containerName == "" || imgName == "" {
  590. cmd.Usage()
  591. return nil
  592. }
  593. if container := srv.containers.Get(containerName); container != nil {
  594. // FIXME: freeze the container before copying it to avoid data corruption?
  595. rwTar, err := fs.Tar(container.Mountpoint.Rw, fs.Uncompressed)
  596. if err != nil {
  597. return err
  598. }
  599. // Create a new image from the container's base layers + a new layer from container changes
  600. parentImg, err := srv.images.Get(container.Image)
  601. if err != nil {
  602. return err
  603. }
  604. img, err := srv.images.Create(rwTar, parentImg, imgName, "")
  605. if err != nil {
  606. return err
  607. }
  608. fmt.Fprintln(stdout, img.Id)
  609. return nil
  610. }
  611. return errors.New("No such container: " + containerName)
  612. }
  613. func (srv *Server) CmdTar(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  614. cmd := rcli.Subcmd(stdout,
  615. "tar", "CONTAINER",
  616. "Stream the contents of a container as a tar archive")
  617. fl_sparse := cmd.Bool("s", false, "Generate a sparse tar stream (top layer + reference to bottom layers)")
  618. if err := cmd.Parse(args); err != nil {
  619. return nil
  620. }
  621. if *fl_sparse {
  622. return errors.New("Sparse mode not yet implemented") // FIXME
  623. }
  624. name := cmd.Arg(0)
  625. if container := srv.containers.Get(name); container != nil {
  626. if err := container.Mountpoint.EnsureMounted(); err != nil {
  627. return err
  628. }
  629. data, err := fs.Tar(container.Mountpoint.Root, fs.Uncompressed)
  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.containers.Get(cmd.Arg(0)); container == nil {
  652. return errors.New("No such container")
  653. } else {
  654. changes, err := srv.images.Changes(container.Mountpoint)
  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) CmdReset(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  665. cmd := rcli.Subcmd(stdout,
  666. "reset", "CONTAINER [OPTIONS]",
  667. "Reset changes to a container's filesystem")
  668. if err := cmd.Parse(args); err != nil {
  669. return nil
  670. }
  671. if cmd.NArg() < 1 {
  672. return errors.New("Not enough arguments")
  673. }
  674. for _, name := range cmd.Args() {
  675. if container := srv.containers.Get(name); container != nil {
  676. if err := container.Mountpoint.Reset(); err != nil {
  677. return errors.New("Reset " + container.Id + ": " + err.Error())
  678. }
  679. }
  680. }
  681. return nil
  682. }
  683. func (srv *Server) CmdLogs(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  684. cmd := rcli.Subcmd(stdout, "logs", "[OPTIONS] CONTAINER", "Fetch the logs of a container")
  685. if err := cmd.Parse(args); err != nil {
  686. return nil
  687. }
  688. if cmd.NArg() != 1 {
  689. cmd.Usage()
  690. return nil
  691. }
  692. name := cmd.Arg(0)
  693. if container := srv.containers.Get(name); container != nil {
  694. if _, err := io.Copy(stdout, container.StdoutLog()); err != nil {
  695. return err
  696. }
  697. if _, err := io.Copy(stdout, container.StderrLog()); err != nil {
  698. return err
  699. }
  700. return nil
  701. }
  702. return errors.New("No such container: " + cmd.Arg(0))
  703. }
  704. func (srv *Server) CreateContainer(img *fs.Image, ports []int, user string, tty bool, openStdin bool, memory int64, comment string, cmd string, args ...string) (*docker.Container, error) {
  705. id := future.RandomId()[:8]
  706. container, err := srv.containers.Create(id, cmd, args, img,
  707. &docker.Config{
  708. Hostname: id,
  709. Ports: ports,
  710. User: user,
  711. Tty: tty,
  712. OpenStdin: openStdin,
  713. Memory: memory,
  714. })
  715. if err != nil {
  716. return nil, err
  717. }
  718. if err := container.SetUserData("image", img.Id); err != nil {
  719. srv.containers.Destroy(container)
  720. return nil, errors.New("Error setting container userdata: " + err.Error())
  721. }
  722. if err := container.SetUserData("comment", comment); err != nil {
  723. srv.containers.Destroy(container)
  724. return nil, errors.New("Error setting container userdata: " + err.Error())
  725. }
  726. return container, nil
  727. }
  728. func (srv *Server) CmdAttach(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  729. cmd := rcli.Subcmd(stdout, "attach", "[OPTIONS]", "Attach to a running container")
  730. fl_i := cmd.Bool("i", false, "Attach to stdin")
  731. fl_o := cmd.Bool("o", true, "Attach to stdout")
  732. fl_e := cmd.Bool("e", true, "Attach to stderr")
  733. if err := cmd.Parse(args); err != nil {
  734. return nil
  735. }
  736. if cmd.NArg() != 1 {
  737. cmd.Usage()
  738. return nil
  739. }
  740. name := cmd.Arg(0)
  741. container := srv.containers.Get(name)
  742. if container == nil {
  743. return errors.New("No such container: " + name)
  744. }
  745. var wg sync.WaitGroup
  746. if *fl_i {
  747. c_stdin, err := container.StdinPipe()
  748. if err != nil {
  749. return err
  750. }
  751. wg.Add(1)
  752. go func() { io.Copy(c_stdin, stdin); wg.Add(-1) }()
  753. }
  754. if *fl_o {
  755. c_stdout, err := container.StdoutPipe()
  756. if err != nil {
  757. return err
  758. }
  759. wg.Add(1)
  760. go func() { io.Copy(stdout, c_stdout); wg.Add(-1) }()
  761. }
  762. if *fl_e {
  763. c_stderr, err := container.StderrPipe()
  764. if err != nil {
  765. return err
  766. }
  767. wg.Add(1)
  768. go func() { io.Copy(stdout, c_stderr); wg.Add(-1) }()
  769. }
  770. wg.Wait()
  771. return nil
  772. }
  773. // Ports type - Used to parse multiple -p flags
  774. type ports []int
  775. func (p *ports) String() string {
  776. return fmt.Sprint(*p)
  777. }
  778. func (p *ports) Set(value string) error {
  779. port, err := strconv.Atoi(value)
  780. if err != nil {
  781. return fmt.Errorf("Invalid port: %v", value)
  782. }
  783. *p = append(*p, port)
  784. return nil
  785. }
  786. func (srv *Server) CmdRun(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  787. cmd := rcli.Subcmd(stdout, "run", "[OPTIONS] IMAGE COMMAND [ARG...]", "Run a command in a new container")
  788. fl_user := cmd.String("u", "", "Username or UID")
  789. fl_attach := cmd.Bool("a", false, "Attach stdin and stdout")
  790. fl_stdin := cmd.Bool("i", false, "Keep stdin open even if not attached")
  791. fl_tty := cmd.Bool("t", false, "Allocate a pseudo-tty")
  792. fl_comment := cmd.String("c", "", "Comment")
  793. fl_memory := cmd.Int64("m", 0, "Memory limit (in bytes)")
  794. var fl_ports ports
  795. cmd.Var(&fl_ports, "p", "Map a network port to the container")
  796. if err := cmd.Parse(args); err != nil {
  797. return nil
  798. }
  799. name := cmd.Arg(0)
  800. var cmdline []string
  801. if len(cmd.Args()) >= 2 {
  802. cmdline = cmd.Args()[1:]
  803. }
  804. // Choose a default image if needed
  805. if name == "" {
  806. name = "base"
  807. }
  808. // Choose a default command if needed
  809. if len(cmdline) == 0 {
  810. *fl_stdin = true
  811. *fl_tty = true
  812. *fl_attach = true
  813. cmdline = []string{"/bin/bash", "-i"}
  814. }
  815. // Find the image
  816. img, err := srv.images.Find(name)
  817. if err != nil {
  818. return err
  819. } else if img == nil {
  820. return errors.New("No such image: " + name)
  821. }
  822. // Create new container
  823. container, err := srv.CreateContainer(img, fl_ports, *fl_user, *fl_tty,
  824. *fl_stdin, *fl_memory, *fl_comment, cmdline[0], cmdline[1:]...)
  825. if err != nil {
  826. return errors.New("Error creating container: " + err.Error())
  827. }
  828. if *fl_stdin {
  829. cmd_stdin, err := container.StdinPipe()
  830. if err != nil {
  831. return err
  832. }
  833. if *fl_attach {
  834. future.Go(func() error {
  835. _, err := io.Copy(cmd_stdin, stdin)
  836. cmd_stdin.Close()
  837. return err
  838. })
  839. }
  840. }
  841. // Run the container
  842. if *fl_attach {
  843. cmd_stderr, err := container.StderrPipe()
  844. if err != nil {
  845. return err
  846. }
  847. cmd_stdout, err := container.StdoutPipe()
  848. if err != nil {
  849. return err
  850. }
  851. if err := container.Start(); err != nil {
  852. return err
  853. }
  854. sending_stdout := future.Go(func() error {
  855. _, err := io.Copy(stdout, cmd_stdout)
  856. return err
  857. })
  858. sending_stderr := future.Go(func() error {
  859. _, err := io.Copy(stdout, cmd_stderr)
  860. return err
  861. })
  862. err_sending_stdout := <-sending_stdout
  863. err_sending_stderr := <-sending_stderr
  864. if err_sending_stdout != nil {
  865. return err_sending_stdout
  866. }
  867. if err_sending_stderr != nil {
  868. return err_sending_stderr
  869. }
  870. container.Wait()
  871. } else {
  872. if err := container.Start(); err != nil {
  873. return err
  874. }
  875. fmt.Fprintln(stdout, container.Id)
  876. }
  877. return nil
  878. }
  879. func New() (*Server, error) {
  880. future.Seed()
  881. // if err != nil {
  882. // return nil, err
  883. // }
  884. containers, err := docker.New()
  885. if err != nil {
  886. return nil, err
  887. }
  888. srv := &Server{
  889. images: containers.Store,
  890. containers: containers,
  891. }
  892. return srv, nil
  893. }
  894. func (srv *Server) CmdMirror(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  895. _, err := io.Copy(stdout, stdin)
  896. return err
  897. }
  898. func (srv *Server) CmdDebug(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  899. for {
  900. if line, err := bufio.NewReader(stdin).ReadString('\n'); err == nil {
  901. fmt.Printf("--- %s", line)
  902. } else if err == io.EOF {
  903. if len(line) > 0 {
  904. fmt.Printf("--- %s\n", line)
  905. }
  906. break
  907. } else {
  908. return err
  909. }
  910. }
  911. return nil
  912. }
  913. func (srv *Server) CmdWeb(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  914. cmd := rcli.Subcmd(stdout, "web", "[OPTIONS]", "A web UI for docker")
  915. showurl := cmd.Bool("u", false, "Return the URL of the web UI")
  916. if err := cmd.Parse(args); err != nil {
  917. return nil
  918. }
  919. if *showurl {
  920. fmt.Fprintln(stdout, "http://localhost:4242/web")
  921. } else {
  922. if file, err := os.Open("dockerweb.html"); err != nil {
  923. return err
  924. } else if _, err := io.Copy(stdout, file); err != nil {
  925. return err
  926. }
  927. }
  928. return nil
  929. }
  930. type Server struct {
  931. containers *docker.Docker
  932. images *fs.Store
  933. }