commands.go 27 KB

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