server.go 27 KB

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