server.go 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981
  1. package server
  2. import (
  3. ".."
  4. "../fs"
  5. "../future"
  6. "../rcli"
  7. "bufio"
  8. "bytes"
  9. "encoding/json"
  10. "errors"
  11. "fmt"
  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. {"pull", "Download a new image from a remote location"},
  59. {"put", "Import a new image from a local archive"},
  60. {"reset", "Reset changes to a container's filesystem"},
  61. {"restart", "Restart a running container"},
  62. {"rm", "Remove a container"},
  63. {"rmimage", "Remove an image"},
  64. {"run", "Run a command in a new container"},
  65. {"start", "Start a stopped container"},
  66. {"stop", "Stop a running container"},
  67. {"tar", "Stream the contents of a container as a tar archive"},
  68. {"umount", "(debug only) Mount a container's filesystem"},
  69. {"wait", "Block until a container stops, then print its exit code"},
  70. {"web", "A web UI for docker"},
  71. {"write", "Write the contents of standard input to a container's file"},
  72. } {
  73. help += fmt.Sprintf(" %-10.10s%s\n", cmd...)
  74. }
  75. return help
  76. }
  77. // 'docker wait': block until a container stops
  78. func (srv *Server) CmdWait(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  79. cmd := rcli.Subcmd(stdout, "wait", "[OPTIONS] NAME", "Block until a container stops, then print its exit code.")
  80. if err := cmd.Parse(args); err != nil {
  81. return nil
  82. }
  83. if cmd.NArg() < 1 {
  84. cmd.Usage()
  85. return nil
  86. }
  87. for _, name := range cmd.Args() {
  88. if container := srv.containers.Get(name); container != nil {
  89. fmt.Fprintln(stdout, container.Wait())
  90. } else {
  91. return errors.New("No such container: " + name)
  92. }
  93. }
  94. return nil
  95. }
  96. // 'docker info': display system-wide information.
  97. func (srv *Server) CmdInfo(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  98. images, _ := srv.images.Images()
  99. var imgcount int
  100. if images == nil {
  101. imgcount = 0
  102. } else {
  103. imgcount = len(images)
  104. }
  105. cmd := rcli.Subcmd(stdout, "info", "", "Display system-wide information.")
  106. if err := cmd.Parse(args); err != nil {
  107. return nil
  108. }
  109. if cmd.NArg() > 0 {
  110. cmd.Usage()
  111. return nil
  112. }
  113. fmt.Fprintf(stdout, "containers: %d\nversion: %s\nimages: %d\n",
  114. len(srv.containers.List()),
  115. VERSION,
  116. imgcount)
  117. return nil
  118. }
  119. func (srv *Server) CmdStop(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  120. cmd := rcli.Subcmd(stdout, "stop", "[OPTIONS] NAME", "Stop a running container")
  121. if err := cmd.Parse(args); err != nil {
  122. return nil
  123. }
  124. if cmd.NArg() < 1 {
  125. cmd.Usage()
  126. return nil
  127. }
  128. for _, name := range cmd.Args() {
  129. if container := srv.containers.Get(name); container != nil {
  130. if err := container.Stop(); err != nil {
  131. return err
  132. }
  133. fmt.Fprintln(stdout, container.Id)
  134. } else {
  135. return errors.New("No such container: " + name)
  136. }
  137. }
  138. return nil
  139. }
  140. func (srv *Server) CmdRestart(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  141. cmd := rcli.Subcmd(stdout, "restart", "[OPTIONS] NAME", "Restart a running container")
  142. if err := cmd.Parse(args); err != nil {
  143. return nil
  144. }
  145. if cmd.NArg() < 1 {
  146. cmd.Usage()
  147. return nil
  148. }
  149. for _, name := range cmd.Args() {
  150. if container := srv.containers.Get(name); container != nil {
  151. if err := container.Restart(); err != nil {
  152. return err
  153. }
  154. fmt.Fprintln(stdout, container.Id)
  155. } else {
  156. return errors.New("No such container: " + name)
  157. }
  158. }
  159. return nil
  160. }
  161. func (srv *Server) CmdStart(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  162. cmd := rcli.Subcmd(stdout, "start", "[OPTIONS] NAME", "Start a stopped container")
  163. if err := cmd.Parse(args); err != nil {
  164. return nil
  165. }
  166. if cmd.NArg() < 1 {
  167. cmd.Usage()
  168. return nil
  169. }
  170. for _, name := range cmd.Args() {
  171. if container := srv.containers.Get(name); container != nil {
  172. if err := container.Start(); err != nil {
  173. return err
  174. }
  175. fmt.Fprintln(stdout, container.Id)
  176. } else {
  177. return errors.New("No such container: " + name)
  178. }
  179. }
  180. return nil
  181. }
  182. func (srv *Server) CmdUmount(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  183. cmd := rcli.Subcmd(stdout, "umount", "[OPTIONS] NAME", "umount a container's filesystem (debug only)")
  184. if err := cmd.Parse(args); err != nil {
  185. return nil
  186. }
  187. if cmd.NArg() < 1 {
  188. cmd.Usage()
  189. return nil
  190. }
  191. for _, name := range cmd.Args() {
  192. if container := srv.containers.Get(name); container != nil {
  193. if err := container.Mountpoint.Umount(); err != nil {
  194. return err
  195. }
  196. fmt.Fprintln(stdout, container.Id)
  197. } else {
  198. return errors.New("No such container: " + name)
  199. }
  200. }
  201. return nil
  202. }
  203. func (srv *Server) CmdMount(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  204. cmd := rcli.Subcmd(stdout, "umount", "[OPTIONS] NAME", "mount a container's filesystem (debug only)")
  205. if err := cmd.Parse(args); err != nil {
  206. return nil
  207. }
  208. if cmd.NArg() < 1 {
  209. cmd.Usage()
  210. return nil
  211. }
  212. for _, name := range cmd.Args() {
  213. if container := srv.containers.Get(name); container != nil {
  214. if err := container.Mountpoint.EnsureMounted(); err != nil {
  215. return err
  216. }
  217. fmt.Fprintln(stdout, container.Id)
  218. } else {
  219. return errors.New("No such container: " + name)
  220. }
  221. }
  222. return nil
  223. }
  224. func (srv *Server) CmdCat(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  225. cmd := rcli.Subcmd(stdout, "cat", "[OPTIONS] CONTAINER PATH", "write the contents of a container's file to standard output")
  226. if err := cmd.Parse(args); err != nil {
  227. return nil
  228. }
  229. if cmd.NArg() < 2 {
  230. cmd.Usage()
  231. return nil
  232. }
  233. name, path := cmd.Arg(0), cmd.Arg(1)
  234. if container := srv.containers.Get(name); container != nil {
  235. if f, err := container.Mountpoint.OpenFile(path, os.O_RDONLY, 0); err != nil {
  236. return err
  237. } else if _, err := io.Copy(stdout, f); err != nil {
  238. return err
  239. }
  240. return nil
  241. }
  242. return errors.New("No such container: " + name)
  243. }
  244. func (srv *Server) CmdWrite(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  245. cmd := rcli.Subcmd(stdout, "write", "[OPTIONS] CONTAINER PATH", "write the contents of standard input to a container's file")
  246. if err := cmd.Parse(args); err != nil {
  247. return nil
  248. }
  249. if cmd.NArg() < 2 {
  250. cmd.Usage()
  251. return nil
  252. }
  253. name, path := cmd.Arg(0), cmd.Arg(1)
  254. if container := srv.containers.Get(name); container != nil {
  255. if f, err := container.Mountpoint.OpenFile(path, os.O_WRONLY|os.O_CREATE, 0600); err != nil {
  256. return err
  257. } else if _, err := io.Copy(f, stdin); err != nil {
  258. return err
  259. }
  260. return nil
  261. }
  262. return errors.New("No such container: " + name)
  263. }
  264. func (srv *Server) CmdLs(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  265. cmd := rcli.Subcmd(stdout, "ls", "[OPTIONS] CONTAINER PATH", "List the contents of a container's directory")
  266. if err := cmd.Parse(args); err != nil {
  267. return nil
  268. }
  269. if cmd.NArg() < 2 {
  270. cmd.Usage()
  271. return nil
  272. }
  273. name, path := cmd.Arg(0), cmd.Arg(1)
  274. if container := srv.containers.Get(name); container != nil {
  275. if files, err := container.Mountpoint.ReadDir(path); err != nil {
  276. return err
  277. } else {
  278. for _, f := range files {
  279. fmt.Fprintln(stdout, f.Name())
  280. }
  281. }
  282. return nil
  283. }
  284. return errors.New("No such container: " + name)
  285. }
  286. func (srv *Server) CmdInspect(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  287. cmd := rcli.Subcmd(stdout, "inspect", "[OPTIONS] CONTAINER", "Return low-level information on a container")
  288. if err := cmd.Parse(args); err != nil {
  289. return nil
  290. }
  291. if cmd.NArg() < 1 {
  292. cmd.Usage()
  293. return nil
  294. }
  295. name := cmd.Arg(0)
  296. var obj interface{}
  297. if container := srv.containers.Get(name); container != nil {
  298. obj = container
  299. //} else if image, err := srv.images.List(name); image != nil {
  300. // obj = image
  301. } else {
  302. return errors.New("No such container or image: " + name)
  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. return nil
  316. }
  317. func (srv *Server) CmdPort(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  318. cmd := rcli.Subcmd(stdout, "port", "[OPTIONS] CONTAINER PRIVATE_PORT", "Lookup the public-facing port which is NAT-ed to PRIVATE_PORT")
  319. if err := cmd.Parse(args); err != nil {
  320. return nil
  321. }
  322. if cmd.NArg() != 2 {
  323. cmd.Usage()
  324. return nil
  325. }
  326. name := cmd.Arg(0)
  327. privatePort := cmd.Arg(1)
  328. if container := srv.containers.Get(name); container == nil {
  329. return errors.New("No such container: " + name)
  330. } else {
  331. if frontend, exists := container.NetworkSettings.PortMapping[privatePort]; !exists {
  332. return fmt.Errorf("No private port '%s' allocated on %s", privatePort, name)
  333. } else {
  334. fmt.Fprintln(stdout, frontend)
  335. }
  336. }
  337. return nil
  338. }
  339. // 'docker rmi NAME' removes all images with the name NAME
  340. // func (srv *Server) CmdRmi(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  341. // cmd := rcli.Subcmd(stdout, "rmimage", "[OPTIONS] IMAGE", "Remove an image")
  342. // fl_regexp := cmd.Bool("r", false, "Use IMAGE as a regular expression instead of an exact name")
  343. // if err := cmd.Parse(args); err != nil {
  344. // cmd.Usage()
  345. // return nil
  346. // }
  347. // if cmd.NArg() < 1 {
  348. // cmd.Usage()
  349. // return nil
  350. // }
  351. // for _, name := range cmd.Args() {
  352. // var err error
  353. // if *fl_regexp {
  354. // err = srv.images.DeleteMatch(name)
  355. // } else {
  356. // image := srv.images.Find(name)
  357. // if image == nil {
  358. // return errors.New("No such image: " + name)
  359. // }
  360. // err = srv.images.Delete(name)
  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. }