commands.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981
  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.Find(name); err != nil {
  296. return err
  297. } else if image != nil {
  298. obj = image
  299. } else {
  300. return errors.New("No such container or image: " + name)
  301. }
  302. data, err := json.Marshal(obj)
  303. if err != nil {
  304. return err
  305. }
  306. indented := new(bytes.Buffer)
  307. if err = json.Indent(indented, data, "", " "); err != nil {
  308. return err
  309. }
  310. if _, err := io.Copy(stdout, indented); err != nil {
  311. return err
  312. }
  313. return nil
  314. }
  315. func (srv *Server) CmdPort(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  316. cmd := rcli.Subcmd(stdout, "port", "[OPTIONS] CONTAINER PRIVATE_PORT", "Lookup the public-facing port which is NAT-ed to PRIVATE_PORT")
  317. if err := cmd.Parse(args); err != nil {
  318. return nil
  319. }
  320. if cmd.NArg() != 2 {
  321. cmd.Usage()
  322. return nil
  323. }
  324. name := cmd.Arg(0)
  325. privatePort := cmd.Arg(1)
  326. if container := srv.containers.Get(name); container == nil {
  327. return errors.New("No such container: " + name)
  328. } else {
  329. if frontend, exists := container.NetworkSettings.PortMapping[privatePort]; !exists {
  330. return fmt.Errorf("No private port '%s' allocated on %s", privatePort, name)
  331. } else {
  332. fmt.Fprintln(stdout, frontend)
  333. }
  334. }
  335. return nil
  336. }
  337. // 'docker rmi NAME' removes all images with the name NAME
  338. func (srv *Server) CmdRmi(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  339. cmd := rcli.Subcmd(stdout, "rmimage", "[OPTIONS] IMAGE", "Remove an image")
  340. fl_all := cmd.Bool("a", false, "Use IMAGE as a path and remove ALL images in this path")
  341. if err := cmd.Parse(args); err != nil {
  342. cmd.Usage()
  343. return nil
  344. }
  345. if cmd.NArg() < 1 {
  346. cmd.Usage()
  347. return nil
  348. }
  349. for _, name := range cmd.Args() {
  350. var err error
  351. if *fl_all {
  352. err = srv.images.RemoveInPath(name)
  353. } else {
  354. image, err := srv.images.Get(name)
  355. if err != nil {
  356. return err
  357. } else if image == nil {
  358. return errors.New("No such image: " + name)
  359. }
  360. err = srv.images.Remove(image)
  361. }
  362. if err != nil {
  363. return err
  364. }
  365. }
  366. return nil
  367. }
  368. func (srv *Server) CmdRm(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  369. cmd := rcli.Subcmd(stdout, "rm", "[OPTIONS] CONTAINER", "Remove a container")
  370. if err := cmd.Parse(args); err != nil {
  371. return nil
  372. }
  373. for _, name := range cmd.Args() {
  374. container := srv.containers.Get(name)
  375. if container == nil {
  376. return errors.New("No such container: " + name)
  377. }
  378. if err := srv.containers.Destroy(container); err != nil {
  379. fmt.Fprintln(stdout, "Error destroying container "+name+": "+err.Error())
  380. }
  381. }
  382. return nil
  383. }
  384. // 'docker kill NAME' kills a running container
  385. func (srv *Server) CmdKill(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  386. cmd := rcli.Subcmd(stdout, "kill", "[OPTIONS] CONTAINER [CONTAINER...]", "Kill a running container")
  387. if err := cmd.Parse(args); err != nil {
  388. return nil
  389. }
  390. for _, name := range cmd.Args() {
  391. container := srv.containers.Get(name)
  392. if container == nil {
  393. return errors.New("No such container: " + name)
  394. }
  395. if err := container.Kill(); err != nil {
  396. fmt.Fprintln(stdout, "Error killing container "+name+": "+err.Error())
  397. }
  398. }
  399. return nil
  400. }
  401. func (srv *Server) CmdImport(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  402. cmd := rcli.Subcmd(stdout, "import", "[OPTIONS] NAME", "Create a new filesystem image from the contents of a tarball")
  403. fl_stdin := cmd.Bool("stdin", false, "Read tarball from stdin")
  404. if err := cmd.Parse(args); err != nil {
  405. return nil
  406. }
  407. var archive io.Reader
  408. name := cmd.Arg(0)
  409. if name == "" {
  410. return errors.New("Not enough arguments")
  411. }
  412. if *fl_stdin {
  413. archive = stdin
  414. } else {
  415. u, err := url.Parse(name)
  416. if err != nil {
  417. return err
  418. }
  419. if u.Scheme == "" {
  420. u.Scheme = "http"
  421. }
  422. // FIXME: hardcode a mirror URL that does not depend on a single provider.
  423. if u.Host == "" {
  424. u.Host = "s3.amazonaws.com"
  425. u.Path = path.Join("/docker.io/images", u.Path)
  426. }
  427. fmt.Fprintf(stdout, "Downloading from %s\n", u.String())
  428. // Download with curl (pretty progress bar)
  429. // If curl is not available, fallback to http.Get()
  430. archive, err = future.Curl(u.String(), stdout)
  431. if err != nil {
  432. if resp, err := http.Get(u.String()); err != nil {
  433. return err
  434. } else {
  435. archive = resp.Body
  436. }
  437. }
  438. }
  439. fmt.Fprintf(stdout, "Unpacking to %s\n", name)
  440. img, err := srv.images.Create(archive, nil, name, "")
  441. if err != nil {
  442. return err
  443. }
  444. fmt.Fprintln(stdout, img.Id)
  445. return nil
  446. }
  447. func (srv *Server) CmdImages(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  448. cmd := rcli.Subcmd(stdout, "images", "[OPTIONS] [NAME]", "List images")
  449. limit := cmd.Int("l", 0, "Only show the N most recent versions of each image")
  450. quiet := cmd.Bool("q", false, "only show numeric IDs")
  451. if err := cmd.Parse(args); err != nil {
  452. return nil
  453. }
  454. if cmd.NArg() > 1 {
  455. cmd.Usage()
  456. return nil
  457. }
  458. var nameFilter string
  459. if cmd.NArg() == 1 {
  460. nameFilter = cmd.Arg(0)
  461. }
  462. w := tabwriter.NewWriter(stdout, 20, 1, 3, ' ', 0)
  463. if !*quiet {
  464. fmt.Fprintf(w, "NAME\tID\tCREATED\tPARENT\n")
  465. }
  466. paths, err := srv.images.Paths()
  467. if err != nil {
  468. return err
  469. }
  470. for _, name := range paths {
  471. if nameFilter != "" && nameFilter != name {
  472. continue
  473. }
  474. ids, err := srv.images.List(name)
  475. if err != nil {
  476. return err
  477. }
  478. for idx, img := range ids {
  479. if *limit > 0 && idx >= *limit {
  480. break
  481. }
  482. if !*quiet {
  483. for idx, field := range []string{
  484. /* NAME */ name,
  485. /* ID */ img.Id,
  486. /* CREATED */ future.HumanDuration(time.Now().Sub(time.Unix(img.Created, 0))) + " ago",
  487. /* PARENT */ img.Parent,
  488. } {
  489. if idx == 0 {
  490. w.Write([]byte(field))
  491. } else {
  492. w.Write([]byte("\t" + field))
  493. }
  494. }
  495. w.Write([]byte{'\n'})
  496. } else {
  497. stdout.Write([]byte(img.Id + "\n"))
  498. }
  499. }
  500. }
  501. if !*quiet {
  502. w.Flush()
  503. }
  504. return nil
  505. }
  506. func (srv *Server) CmdPs(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  507. cmd := rcli.Subcmd(stdout,
  508. "ps", "[OPTIONS]", "List containers")
  509. quiet := cmd.Bool("q", false, "Only display numeric IDs")
  510. fl_all := cmd.Bool("a", false, "Show all containers. Only running containers are shown by default.")
  511. fl_full := cmd.Bool("notrunc", false, "Don't truncate output")
  512. if err := cmd.Parse(args); err != nil {
  513. return nil
  514. }
  515. w := tabwriter.NewWriter(stdout, 12, 1, 3, ' ', 0)
  516. if !*quiet {
  517. fmt.Fprintf(w, "ID\tIMAGE\tCOMMAND\tCREATED\tSTATUS\tCOMMENT\n")
  518. }
  519. for _, container := range srv.containers.List() {
  520. comment := container.GetUserData("comment")
  521. if !container.State.Running && !*fl_all {
  522. continue
  523. }
  524. if !*quiet {
  525. command := fmt.Sprintf("%s %s", container.Path, strings.Join(container.Args, " "))
  526. if !*fl_full {
  527. command = docker.Trunc(command, 20)
  528. }
  529. for idx, field := range []string{
  530. /* ID */ container.Id,
  531. /* IMAGE */ container.GetUserData("image"),
  532. /* COMMAND */ command,
  533. /* CREATED */ future.HumanDuration(time.Now().Sub(container.Created)) + " ago",
  534. /* STATUS */ container.State.String(),
  535. /* COMMENT */ comment,
  536. } {
  537. if idx == 0 {
  538. w.Write([]byte(field))
  539. } else {
  540. w.Write([]byte("\t" + field))
  541. }
  542. }
  543. w.Write([]byte{'\n'})
  544. } else {
  545. stdout.Write([]byte(container.Id + "\n"))
  546. }
  547. }
  548. if !*quiet {
  549. w.Flush()
  550. }
  551. return nil
  552. }
  553. func (srv *Server) CmdLayers(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  554. cmd := rcli.Subcmd(stdout,
  555. "layers", "[OPTIONS]",
  556. "List filesystem layers (debug only)")
  557. if err := cmd.Parse(args); err != nil {
  558. return nil
  559. }
  560. for _, layer := range srv.images.Layers() {
  561. fmt.Fprintln(stdout, layer)
  562. }
  563. return nil
  564. }
  565. func (srv *Server) CmdCp(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  566. cmd := rcli.Subcmd(stdout,
  567. "cp", "[OPTIONS] IMAGE NAME",
  568. "Create a copy of IMAGE and call it NAME")
  569. if err := cmd.Parse(args); err != nil {
  570. return nil
  571. }
  572. if image, err := srv.images.Get(cmd.Arg(0)); err != nil {
  573. return err
  574. } else if image == nil {
  575. return errors.New("Image " + cmd.Arg(0) + " does not exist")
  576. } else {
  577. if img, err := image.Copy(cmd.Arg(1)); err != nil {
  578. return err
  579. } else {
  580. fmt.Fprintln(stdout, img.Id)
  581. }
  582. }
  583. return nil
  584. }
  585. func (srv *Server) CmdCommit(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  586. cmd := rcli.Subcmd(stdout,
  587. "commit", "[OPTIONS] CONTAINER [DEST]",
  588. "Create a new image from a container's changes")
  589. if err := cmd.Parse(args); err != nil {
  590. return nil
  591. }
  592. containerName, imgName := cmd.Arg(0), cmd.Arg(1)
  593. if containerName == "" || imgName == "" {
  594. cmd.Usage()
  595. return nil
  596. }
  597. if container := srv.containers.Get(containerName); container != nil {
  598. // FIXME: freeze the container before copying it to avoid data corruption?
  599. rwTar, err := fs.Tar(container.Mountpoint.Rw, fs.Uncompressed)
  600. if err != nil {
  601. return err
  602. }
  603. // Create a new image from the container's base layers + a new layer from container changes
  604. parentImg, err := srv.images.Get(container.Image)
  605. if err != nil {
  606. return err
  607. }
  608. img, err := srv.images.Create(rwTar, parentImg, imgName, "")
  609. if err != nil {
  610. return err
  611. }
  612. fmt.Fprintln(stdout, img.Id)
  613. return nil
  614. }
  615. return errors.New("No such container: " + containerName)
  616. }
  617. func (srv *Server) CmdTar(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  618. cmd := rcli.Subcmd(stdout,
  619. "tar", "CONTAINER",
  620. "Stream the contents of a container as a tar archive")
  621. fl_sparse := cmd.Bool("s", false, "Generate a sparse tar stream (top layer + reference to bottom layers)")
  622. if err := cmd.Parse(args); err != nil {
  623. return nil
  624. }
  625. if *fl_sparse {
  626. return errors.New("Sparse mode not yet implemented") // FIXME
  627. }
  628. name := cmd.Arg(0)
  629. if container := srv.containers.Get(name); container != nil {
  630. if err := container.Mountpoint.EnsureMounted(); err != nil {
  631. return err
  632. }
  633. data, err := fs.Tar(container.Mountpoint.Root, fs.Uncompressed)
  634. if err != nil {
  635. return err
  636. }
  637. // Stream the entire contents of the container (basically a volatile snapshot)
  638. if _, err := io.Copy(stdout, data); err != nil {
  639. return err
  640. }
  641. return nil
  642. }
  643. return errors.New("No such container: " + name)
  644. }
  645. func (srv *Server) CmdDiff(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  646. cmd := rcli.Subcmd(stdout,
  647. "diff", "CONTAINER [OPTIONS]",
  648. "Inspect changes on a container's filesystem")
  649. if err := cmd.Parse(args); err != nil {
  650. return nil
  651. }
  652. if cmd.NArg() < 1 {
  653. return errors.New("Not enough arguments")
  654. }
  655. if container := srv.containers.Get(cmd.Arg(0)); container == nil {
  656. return errors.New("No such container")
  657. } else {
  658. changes, err := srv.images.Changes(container.Mountpoint)
  659. if err != nil {
  660. return err
  661. }
  662. for _, change := range changes {
  663. fmt.Fprintln(stdout, change.String())
  664. }
  665. }
  666. return nil
  667. }
  668. func (srv *Server) CmdReset(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  669. cmd := rcli.Subcmd(stdout,
  670. "reset", "CONTAINER [OPTIONS]",
  671. "Reset changes to a container's filesystem")
  672. if err := cmd.Parse(args); err != nil {
  673. return nil
  674. }
  675. if cmd.NArg() < 1 {
  676. return errors.New("Not enough arguments")
  677. }
  678. for _, name := range cmd.Args() {
  679. if container := srv.containers.Get(name); container != nil {
  680. if err := container.Mountpoint.Reset(); err != nil {
  681. return errors.New("Reset " + container.Id + ": " + err.Error())
  682. }
  683. }
  684. }
  685. return nil
  686. }
  687. func (srv *Server) CmdLogs(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  688. cmd := rcli.Subcmd(stdout, "logs", "[OPTIONS] CONTAINER", "Fetch the logs of a container")
  689. if err := cmd.Parse(args); err != nil {
  690. return nil
  691. }
  692. if cmd.NArg() != 1 {
  693. cmd.Usage()
  694. return nil
  695. }
  696. name := cmd.Arg(0)
  697. if container := srv.containers.Get(name); container != nil {
  698. if _, err := io.Copy(stdout, container.StdoutLog()); err != nil {
  699. return err
  700. }
  701. if _, err := io.Copy(stdout, container.StderrLog()); err != nil {
  702. return err
  703. }
  704. return nil
  705. }
  706. return errors.New("No such container: " + cmd.Arg(0))
  707. }
  708. 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) {
  709. id := future.RandomId()[:8]
  710. container, err := srv.containers.Create(id, cmd, args, img,
  711. &docker.Config{
  712. Hostname: id,
  713. Ports: ports,
  714. User: user,
  715. Tty: tty,
  716. OpenStdin: openStdin,
  717. Memory: memory,
  718. })
  719. if err != nil {
  720. return nil, err
  721. }
  722. if err := container.SetUserData("image", img.Id); err != nil {
  723. srv.containers.Destroy(container)
  724. return nil, errors.New("Error setting container userdata: " + err.Error())
  725. }
  726. if err := container.SetUserData("comment", comment); err != nil {
  727. srv.containers.Destroy(container)
  728. return nil, errors.New("Error setting container userdata: " + err.Error())
  729. }
  730. return container, nil
  731. }
  732. func (srv *Server) CmdAttach(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  733. cmd := rcli.Subcmd(stdout, "attach", "[OPTIONS]", "Attach to a running container")
  734. fl_i := cmd.Bool("i", false, "Attach to stdin")
  735. fl_o := cmd.Bool("o", true, "Attach to stdout")
  736. fl_e := cmd.Bool("e", true, "Attach to stderr")
  737. if err := cmd.Parse(args); err != nil {
  738. return nil
  739. }
  740. if cmd.NArg() != 1 {
  741. cmd.Usage()
  742. return nil
  743. }
  744. name := cmd.Arg(0)
  745. container := srv.containers.Get(name)
  746. if container == nil {
  747. return errors.New("No such container: " + name)
  748. }
  749. var wg sync.WaitGroup
  750. if *fl_i {
  751. c_stdin, err := container.StdinPipe()
  752. if err != nil {
  753. return err
  754. }
  755. wg.Add(1)
  756. go func() { io.Copy(c_stdin, stdin); wg.Add(-1) }()
  757. }
  758. if *fl_o {
  759. c_stdout, err := container.StdoutPipe()
  760. if err != nil {
  761. return err
  762. }
  763. wg.Add(1)
  764. go func() { io.Copy(stdout, c_stdout); wg.Add(-1) }()
  765. }
  766. if *fl_e {
  767. c_stderr, err := container.StderrPipe()
  768. if err != nil {
  769. return err
  770. }
  771. wg.Add(1)
  772. go func() { io.Copy(stdout, c_stderr); wg.Add(-1) }()
  773. }
  774. wg.Wait()
  775. return nil
  776. }
  777. // Ports type - Used to parse multiple -p flags
  778. type ports []int
  779. func (p *ports) String() string {
  780. return fmt.Sprint(*p)
  781. }
  782. func (p *ports) Set(value string) error {
  783. port, err := strconv.Atoi(value)
  784. if err != nil {
  785. return fmt.Errorf("Invalid port: %v", value)
  786. }
  787. *p = append(*p, port)
  788. return nil
  789. }
  790. func (srv *Server) CmdRun(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  791. cmd := rcli.Subcmd(stdout, "run", "[OPTIONS] IMAGE COMMAND [ARG...]", "Run a command in a new container")
  792. fl_user := cmd.String("u", "", "Username or UID")
  793. fl_attach := cmd.Bool("a", false, "Attach stdin and stdout")
  794. fl_stdin := cmd.Bool("i", false, "Keep stdin open even if not attached")
  795. fl_tty := cmd.Bool("t", false, "Allocate a pseudo-tty")
  796. fl_comment := cmd.String("c", "", "Comment")
  797. fl_memory := cmd.Int64("m", 0, "Memory limit (in bytes)")
  798. var fl_ports ports
  799. cmd.Var(&fl_ports, "p", "Map a network port to the container")
  800. if err := cmd.Parse(args); err != nil {
  801. return nil
  802. }
  803. name := cmd.Arg(0)
  804. var cmdline []string
  805. if len(cmd.Args()) >= 2 {
  806. cmdline = cmd.Args()[1:]
  807. }
  808. // Choose a default image if needed
  809. if name == "" {
  810. name = "base"
  811. }
  812. // Choose a default command if needed
  813. if len(cmdline) == 0 {
  814. *fl_stdin = true
  815. *fl_tty = true
  816. *fl_attach = true
  817. cmdline = []string{"/bin/bash", "-i"}
  818. }
  819. // Find the image
  820. img, err := srv.images.Find(name)
  821. if err != nil {
  822. return err
  823. } else if img == nil {
  824. return errors.New("No such image: " + name)
  825. }
  826. // Create new container
  827. container, err := srv.CreateContainer(img, fl_ports, *fl_user, *fl_tty,
  828. *fl_stdin, *fl_memory, *fl_comment, cmdline[0], cmdline[1:]...)
  829. if err != nil {
  830. return errors.New("Error creating container: " + err.Error())
  831. }
  832. if *fl_stdin {
  833. cmd_stdin, err := container.StdinPipe()
  834. if err != nil {
  835. return err
  836. }
  837. if *fl_attach {
  838. future.Go(func() error {
  839. _, err := io.Copy(cmd_stdin, stdin)
  840. cmd_stdin.Close()
  841. return err
  842. })
  843. }
  844. }
  845. // Run the container
  846. if *fl_attach {
  847. cmd_stderr, err := container.StderrPipe()
  848. if err != nil {
  849. return err
  850. }
  851. cmd_stdout, err := container.StdoutPipe()
  852. if err != nil {
  853. return err
  854. }
  855. if err := container.Start(); err != nil {
  856. return err
  857. }
  858. sending_stdout := future.Go(func() error {
  859. _, err := io.Copy(stdout, cmd_stdout)
  860. return err
  861. })
  862. sending_stderr := future.Go(func() error {
  863. _, err := io.Copy(stdout, cmd_stderr)
  864. return err
  865. })
  866. err_sending_stdout := <-sending_stdout
  867. err_sending_stderr := <-sending_stderr
  868. if err_sending_stdout != nil {
  869. return err_sending_stdout
  870. }
  871. if err_sending_stderr != nil {
  872. return err_sending_stderr
  873. }
  874. container.Wait()
  875. } else {
  876. if err := container.Start(); err != nil {
  877. return err
  878. }
  879. fmt.Fprintln(stdout, container.Id)
  880. }
  881. return nil
  882. }
  883. func New() (*Server, error) {
  884. future.Seed()
  885. // if err != nil {
  886. // return nil, err
  887. // }
  888. containers, err := docker.New()
  889. if err != nil {
  890. return nil, err
  891. }
  892. srv := &Server{
  893. images: containers.Store,
  894. containers: containers,
  895. }
  896. return srv, nil
  897. }
  898. func (srv *Server) CmdMirror(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  899. _, err := io.Copy(stdout, stdin)
  900. return err
  901. }
  902. func (srv *Server) CmdDebug(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  903. for {
  904. if line, err := bufio.NewReader(stdin).ReadString('\n'); err == nil {
  905. fmt.Printf("--- %s", line)
  906. } else if err == io.EOF {
  907. if len(line) > 0 {
  908. fmt.Printf("--- %s\n", line)
  909. }
  910. break
  911. } else {
  912. return err
  913. }
  914. }
  915. return nil
  916. }
  917. func (srv *Server) CmdWeb(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  918. cmd := rcli.Subcmd(stdout, "web", "[OPTIONS]", "A web UI for docker")
  919. showurl := cmd.Bool("u", false, "Return the URL of the web UI")
  920. if err := cmd.Parse(args); err != nil {
  921. return nil
  922. }
  923. if *showurl {
  924. fmt.Fprintln(stdout, "http://localhost:4242/web")
  925. } else {
  926. if file, err := os.Open("dockerweb.html"); err != nil {
  927. return err
  928. } else if _, err := io.Copy(stdout, file); err != nil {
  929. return err
  930. }
  931. }
  932. return nil
  933. }
  934. type Server struct {
  935. containers *docker.Docker
  936. images *fs.Store
  937. }