commands.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895
  1. package docker
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "github.com/dotcloud/docker/auth"
  8. "github.com/dotcloud/docker/rcli"
  9. "io"
  10. "log"
  11. "math/rand"
  12. "net/http"
  13. "net/url"
  14. "runtime"
  15. "strconv"
  16. "strings"
  17. "sync"
  18. "text/tabwriter"
  19. "time"
  20. )
  21. const VERSION = "0.0.3"
  22. func (srv *Server) Name() string {
  23. return "docker"
  24. }
  25. // FIXME: Stop violating DRY by repeating usage here and in Subcmd declarations
  26. func (srv *Server) Help() string {
  27. help := "Usage: docker COMMAND [arg...]\n\nA self-sufficient runtime for linux containers.\n\nCommands:\n"
  28. for _, cmd := range [][]interface{}{
  29. {"run", "Run a command in a container"},
  30. {"ps", "Display a list of containers"},
  31. {"import", "Create a new filesystem image from the contents of a tarball"},
  32. {"attach", "Attach to a running container"},
  33. {"commit", "Create a new image from a container's changes"},
  34. {"history", "Show the history of an image"},
  35. {"diff", "Inspect changes on a container's filesystem"},
  36. {"images", "List images"},
  37. {"info", "Display system-wide information"},
  38. {"inspect", "Return low-level information on a container"},
  39. {"kill", "Kill a running container"},
  40. {"login", "Register or Login to the docker registry server"},
  41. {"logs", "Fetch the logs of a container"},
  42. {"port", "Lookup the public-facing port which is NAT-ed to PRIVATE_PORT"},
  43. {"ps", "List containers"},
  44. {"pull", "Pull an image or a repository to the docker registry server"},
  45. {"push", "Push an image or a repository to the docker registry server"},
  46. {"restart", "Restart a running container"},
  47. {"rm", "Remove a container"},
  48. {"rmi", "Remove an image"},
  49. {"run", "Run a command in a new container"},
  50. {"start", "Start a stopped container"},
  51. {"stop", "Stop a running container"},
  52. {"export", "Stream the contents of a container as a tar archive"},
  53. {"version", "Show the docker version information"},
  54. {"wait", "Block until a container stops, then print its exit code"},
  55. } {
  56. help += fmt.Sprintf(" %-10.10s%s\n", cmd[0], cmd[1])
  57. }
  58. return help
  59. }
  60. // 'docker login': login / register a user to registry service.
  61. func (srv *Server) CmdLogin(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  62. cmd := rcli.Subcmd(stdout, "login", "", "Register or Login to the docker registry server")
  63. if err := cmd.Parse(args); err != nil {
  64. return nil
  65. }
  66. var username string
  67. var password string
  68. var email string
  69. fmt.Fprint(stdout, "Username (", srv.runtime.authConfig.Username, "): ")
  70. fmt.Fscanf(stdin, "%s", &username)
  71. if username == "" {
  72. username = srv.runtime.authConfig.Username
  73. }
  74. if username != srv.runtime.authConfig.Username {
  75. fmt.Fprint(stdout, "Password: ")
  76. fmt.Fscanf(stdin, "%s", &password)
  77. if password == "" {
  78. return errors.New("Error : Password Required\n")
  79. }
  80. fmt.Fprint(stdout, "Email (", srv.runtime.authConfig.Email, "): ")
  81. fmt.Fscanf(stdin, "%s", &email)
  82. if email == "" {
  83. email = srv.runtime.authConfig.Email
  84. }
  85. } else {
  86. password = srv.runtime.authConfig.Password
  87. email = srv.runtime.authConfig.Email
  88. }
  89. newAuthConfig := &auth.AuthConfig{Username: username, Password: password, Email: email}
  90. status, err := auth.Login(newAuthConfig)
  91. if err != nil {
  92. fmt.Fprintf(stdout, "Error : %s\n", err)
  93. }
  94. if status != "" {
  95. fmt.Fprintf(stdout, status)
  96. }
  97. return nil
  98. }
  99. // 'docker wait': block until a container stops
  100. func (srv *Server) CmdWait(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  101. cmd := rcli.Subcmd(stdout, "wait", "[OPTIONS] NAME", "Block until a container stops, then print its exit code.")
  102. if err := cmd.Parse(args); err != nil {
  103. return nil
  104. }
  105. if cmd.NArg() < 1 {
  106. cmd.Usage()
  107. return nil
  108. }
  109. for _, name := range cmd.Args() {
  110. if container := srv.runtime.Get(name); container != nil {
  111. fmt.Fprintln(stdout, container.Wait())
  112. } else {
  113. return errors.New("No such container: " + name)
  114. }
  115. }
  116. return nil
  117. }
  118. // 'docker version': show version information
  119. func (srv *Server) CmdVersion(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  120. fmt.Fprintf(stdout, "Version:%s\n", VERSION)
  121. return nil
  122. }
  123. // 'docker info': display system-wide information.
  124. func (srv *Server) CmdInfo(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  125. images, _ := srv.runtime.graph.All()
  126. var imgcount int
  127. if images == nil {
  128. imgcount = 0
  129. } else {
  130. imgcount = len(images)
  131. }
  132. cmd := rcli.Subcmd(stdout, "info", "", "Display system-wide information.")
  133. if err := cmd.Parse(args); err != nil {
  134. return nil
  135. }
  136. if cmd.NArg() > 0 {
  137. cmd.Usage()
  138. return nil
  139. }
  140. fmt.Fprintf(stdout, "containers: %d\nversion: %s\nimages: %d\n",
  141. len(srv.runtime.List()),
  142. VERSION,
  143. imgcount)
  144. return nil
  145. }
  146. func (srv *Server) CmdStop(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  147. cmd := rcli.Subcmd(stdout, "stop", "[OPTIONS] NAME", "Stop a running container")
  148. if err := cmd.Parse(args); err != nil {
  149. return nil
  150. }
  151. if cmd.NArg() < 1 {
  152. cmd.Usage()
  153. return nil
  154. }
  155. for _, name := range cmd.Args() {
  156. if container := srv.runtime.Get(name); container != nil {
  157. if err := container.Stop(); err != nil {
  158. return err
  159. }
  160. fmt.Fprintln(stdout, container.Id)
  161. } else {
  162. return errors.New("No such container: " + name)
  163. }
  164. }
  165. return nil
  166. }
  167. func (srv *Server) CmdRestart(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  168. cmd := rcli.Subcmd(stdout, "restart", "[OPTIONS] NAME", "Restart a running container")
  169. if err := cmd.Parse(args); err != nil {
  170. return nil
  171. }
  172. if cmd.NArg() < 1 {
  173. cmd.Usage()
  174. return nil
  175. }
  176. for _, name := range cmd.Args() {
  177. if container := srv.runtime.Get(name); container != nil {
  178. if err := container.Restart(); err != nil {
  179. return err
  180. }
  181. fmt.Fprintln(stdout, container.Id)
  182. } else {
  183. return errors.New("No such container: " + name)
  184. }
  185. }
  186. return nil
  187. }
  188. func (srv *Server) CmdStart(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  189. cmd := rcli.Subcmd(stdout, "start", "[OPTIONS] NAME", "Start a stopped container")
  190. if err := cmd.Parse(args); err != nil {
  191. return nil
  192. }
  193. if cmd.NArg() < 1 {
  194. cmd.Usage()
  195. return nil
  196. }
  197. for _, name := range cmd.Args() {
  198. if container := srv.runtime.Get(name); container != nil {
  199. if err := container.Start(); err != nil {
  200. return err
  201. }
  202. fmt.Fprintln(stdout, container.Id)
  203. } else {
  204. return errors.New("No such container: " + name)
  205. }
  206. }
  207. return nil
  208. }
  209. func (srv *Server) CmdInspect(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  210. cmd := rcli.Subcmd(stdout, "inspect", "[OPTIONS] CONTAINER", "Return low-level information on a container")
  211. if err := cmd.Parse(args); err != nil {
  212. return nil
  213. }
  214. if cmd.NArg() < 1 {
  215. cmd.Usage()
  216. return nil
  217. }
  218. name := cmd.Arg(0)
  219. var obj interface{}
  220. if container := srv.runtime.Get(name); container != nil {
  221. obj = container
  222. } else if image, err := srv.runtime.repositories.LookupImage(name); err != nil {
  223. return err
  224. } else if image != nil {
  225. obj = image
  226. } else {
  227. // No output means the object does not exist
  228. // (easier to script since stdout and stderr are not differentiated atm)
  229. return nil
  230. }
  231. data, err := json.Marshal(obj)
  232. if err != nil {
  233. return err
  234. }
  235. indented := new(bytes.Buffer)
  236. if err = json.Indent(indented, data, "", " "); err != nil {
  237. return err
  238. }
  239. if _, err := io.Copy(stdout, indented); err != nil {
  240. return err
  241. }
  242. stdout.Write([]byte{'\n'})
  243. return nil
  244. }
  245. func (srv *Server) CmdPort(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  246. cmd := rcli.Subcmd(stdout, "port", "[OPTIONS] CONTAINER PRIVATE_PORT", "Lookup the public-facing port which is NAT-ed to PRIVATE_PORT")
  247. if err := cmd.Parse(args); err != nil {
  248. return nil
  249. }
  250. if cmd.NArg() != 2 {
  251. cmd.Usage()
  252. return nil
  253. }
  254. name := cmd.Arg(0)
  255. privatePort := cmd.Arg(1)
  256. if container := srv.runtime.Get(name); container == nil {
  257. return errors.New("No such container: " + name)
  258. } else {
  259. if frontend, exists := container.NetworkSettings.PortMapping[privatePort]; !exists {
  260. return fmt.Errorf("No private port '%s' allocated on %s", privatePort, name)
  261. } else {
  262. fmt.Fprintln(stdout, frontend)
  263. }
  264. }
  265. return nil
  266. }
  267. // 'docker rmi NAME' removes all images with the name NAME
  268. func (srv *Server) CmdRmi(stdin io.ReadCloser, stdout io.Writer, args ...string) (err error) {
  269. cmd := rcli.Subcmd(stdout, "rmimage", "[OPTIONS] IMAGE", "Remove an image")
  270. if cmd.Parse(args) != nil || cmd.NArg() < 1 {
  271. cmd.Usage()
  272. return nil
  273. }
  274. for _, name := range cmd.Args() {
  275. if err := srv.runtime.graph.Delete(name); err != nil {
  276. return err
  277. }
  278. }
  279. return nil
  280. }
  281. func (srv *Server) CmdHistory(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  282. cmd := rcli.Subcmd(stdout, "history", "[OPTIONS] IMAGE", "Show the history of an image")
  283. if cmd.Parse(args) != nil || cmd.NArg() != 1 {
  284. cmd.Usage()
  285. return nil
  286. }
  287. image, err := srv.runtime.repositories.LookupImage(cmd.Arg(0))
  288. if err != nil {
  289. return err
  290. }
  291. w := tabwriter.NewWriter(stdout, 20, 1, 3, ' ', 0)
  292. defer w.Flush()
  293. fmt.Fprintf(w, "ID\tCREATED\tCREATED BY\n")
  294. return image.WalkHistory(func(img *Image) error {
  295. fmt.Fprintf(w, "%s\t%s\t%s\n",
  296. srv.runtime.repositories.ImageName(img.Id),
  297. HumanDuration(time.Now().Sub(img.Created))+" ago",
  298. strings.Join(img.ParentCommand, " "),
  299. )
  300. return nil
  301. })
  302. }
  303. func (srv *Server) CmdRm(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  304. cmd := rcli.Subcmd(stdout, "rm", "[OPTIONS] CONTAINER", "Remove a container")
  305. if err := cmd.Parse(args); err != nil {
  306. return nil
  307. }
  308. for _, name := range cmd.Args() {
  309. container := srv.runtime.Get(name)
  310. if container == nil {
  311. return errors.New("No such container: " + name)
  312. }
  313. if err := srv.runtime.Destroy(container); err != nil {
  314. fmt.Fprintln(stdout, "Error destroying container "+name+": "+err.Error())
  315. }
  316. }
  317. return nil
  318. }
  319. // 'docker kill NAME' kills a running container
  320. func (srv *Server) CmdKill(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  321. cmd := rcli.Subcmd(stdout, "kill", "[OPTIONS] CONTAINER [CONTAINER...]", "Kill a running container")
  322. if err := cmd.Parse(args); err != nil {
  323. return nil
  324. }
  325. for _, name := range cmd.Args() {
  326. container := srv.runtime.Get(name)
  327. if container == nil {
  328. return errors.New("No such container: " + name)
  329. }
  330. if err := container.Kill(); err != nil {
  331. fmt.Fprintln(stdout, "Error killing container "+name+": "+err.Error())
  332. }
  333. }
  334. return nil
  335. }
  336. func (srv *Server) CmdImport(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  337. cmd := rcli.Subcmd(stdout, "import", "[OPTIONS] URL|- [REPOSITORY [TAG]]", "Create a new filesystem image from the contents of a tarball")
  338. var archive io.Reader
  339. var resp *http.Response
  340. if err := cmd.Parse(args); err != nil {
  341. return nil
  342. }
  343. src := cmd.Arg(0)
  344. if src == "" {
  345. return errors.New("Not enough arguments")
  346. } else if src == "-" {
  347. archive = stdin
  348. } else {
  349. u, err := url.Parse(src)
  350. if err != nil {
  351. return err
  352. }
  353. if u.Scheme == "" {
  354. u.Scheme = "http"
  355. u.Host = src
  356. u.Path = ""
  357. }
  358. fmt.Fprintf(stdout, "Downloading from %s\n", u.String())
  359. // Download with curl (pretty progress bar)
  360. // If curl is not available, fallback to http.Get()
  361. resp, err = Download(u.String(), stdout)
  362. if err != nil {
  363. return err
  364. }
  365. archive = ProgressReader(resp.Body, int(resp.ContentLength), stdout)
  366. }
  367. img, err := srv.runtime.graph.Create(archive, nil, "Imported from "+src)
  368. if err != nil {
  369. return err
  370. }
  371. // Optionally register the image at REPO/TAG
  372. if repository := cmd.Arg(1); repository != "" {
  373. tag := cmd.Arg(2) // Repository will handle an empty tag properly
  374. if err := srv.runtime.repositories.Set(repository, tag, img.Id, true); err != nil {
  375. return err
  376. }
  377. }
  378. fmt.Fprintln(stdout, img.Id)
  379. return nil
  380. }
  381. func (srv *Server) CmdPush(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  382. cmd := rcli.Subcmd(stdout, "push", "[OPTIONS] IMAGE", "Push an image or a repository to the registry")
  383. user := cmd.String("u", "", "specify the user for the repository")
  384. if err := cmd.Parse(args); err != nil {
  385. return nil
  386. }
  387. if cmd.NArg() == 0 || *user == "" {
  388. cmd.Usage()
  389. return nil
  390. }
  391. if srv.runtime.authConfig == nil {
  392. return fmt.Errorf("Please login prior to push. ('docker login')")
  393. }
  394. // Try to get the image
  395. // FIXME: Handle lookup
  396. // FIXME: Also push the tags in case of ./docker push myrepo:mytag
  397. // img, err := srv.runtime.LookupImage(cmd.Arg(0))
  398. img, err := srv.runtime.graph.Get(cmd.Arg(0))
  399. if err != nil {
  400. // If it fails, try to get the repository
  401. if repo, exists := srv.runtime.repositories.Repositories[cmd.Arg(0)]; exists {
  402. fmt.Fprintf(stdout, "Pushing %s (%d images) on %s...\n", cmd.Arg(0), len(repo), *user+"/"+cmd.Arg(0))
  403. if err := srv.runtime.graph.PushRepository(*user, cmd.Arg(0), repo, srv.runtime.authConfig); err != nil {
  404. return err
  405. }
  406. fmt.Fprintf(stdout, "Push completed\n")
  407. return nil
  408. } else {
  409. return err
  410. }
  411. return nil
  412. }
  413. fmt.Fprintf(stdout, "Pushing image %s..\n", img.Id)
  414. err = srv.runtime.graph.PushImage(img, srv.runtime.authConfig)
  415. if err != nil {
  416. return err
  417. }
  418. fmt.Fprintf(stdout, "Push completed\n")
  419. return nil
  420. }
  421. func (srv *Server) CmdPull(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  422. cmd := rcli.Subcmd(stdout, "pull", "[OPTIONS] IMAGE", "Pull an image or a repository from the registry")
  423. user := cmd.String("u", "", "specify the user for the repository")
  424. if err := cmd.Parse(args); err != nil {
  425. return nil
  426. }
  427. if cmd.NArg() == 0 || *user == "" {
  428. cmd.Usage()
  429. return nil
  430. }
  431. if srv.runtime.authConfig == nil {
  432. return fmt.Errorf("Please login prior to push. ('docker login')")
  433. }
  434. if srv.runtime.graph.LookupRemoteImage(cmd.Arg(0), srv.runtime.authConfig) {
  435. fmt.Fprintf(stdout, "Pulling %s...\n", cmd.Arg(0))
  436. if err := srv.runtime.graph.PullImage(cmd.Arg(0), srv.runtime.authConfig); err != nil {
  437. return err
  438. }
  439. fmt.Fprintf(stdout, "Pulled\n")
  440. return nil
  441. }
  442. // FIXME: Allow pull repo:tag
  443. fmt.Fprintf(stdout, "Pulling %s from %s...\n", cmd.Arg(0), *user+"/"+cmd.Arg(0))
  444. if err := srv.runtime.graph.PullRepository(*user, cmd.Arg(0), "", srv.runtime.repositories, srv.runtime.authConfig); err != nil {
  445. return err
  446. }
  447. fmt.Fprintf(stdout, "Pull completed\n")
  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, "REPOSITORY\tTAG\tID\tCREATED\tPARENT\n")
  468. }
  469. allImages, err := srv.runtime.graph.Map()
  470. if err != nil {
  471. return err
  472. }
  473. for name, repository := range srv.runtime.repositories.Repositories {
  474. if nameFilter != "" && name != nameFilter {
  475. continue
  476. }
  477. for tag, id := range repository {
  478. image, err := srv.runtime.graph.Get(id)
  479. if err != nil {
  480. log.Printf("Warning: couldn't load %s from %s/%s: %s", id, name, tag, err)
  481. continue
  482. }
  483. delete(allImages, id)
  484. if !*quiet {
  485. for idx, field := range []string{
  486. /* REPOSITORY */ name,
  487. /* TAG */ tag,
  488. /* ID */ id,
  489. /* CREATED */ HumanDuration(time.Now().Sub(image.Created)) + " ago",
  490. /* PARENT */ srv.runtime.repositories.ImageName(image.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(image.Id + "\n"))
  501. }
  502. }
  503. }
  504. // Display images which aren't part of a
  505. if nameFilter == "" {
  506. for id, image := range allImages {
  507. if !*quiet {
  508. for idx, field := range []string{
  509. /* REPOSITORY */ "",
  510. /* TAG */ "",
  511. /* ID */ id,
  512. /* CREATED */ HumanDuration(time.Now().Sub(image.Created)) + " ago",
  513. /* PARENT */ srv.runtime.repositories.ImageName(image.Parent),
  514. } {
  515. if idx == 0 {
  516. w.Write([]byte(field))
  517. } else {
  518. w.Write([]byte("\t" + field))
  519. }
  520. }
  521. w.Write([]byte{'\n'})
  522. } else {
  523. stdout.Write([]byte(image.Id + "\n"))
  524. }
  525. }
  526. }
  527. if !*quiet {
  528. w.Flush()
  529. }
  530. return nil
  531. }
  532. func (srv *Server) CmdPs(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  533. cmd := rcli.Subcmd(stdout,
  534. "ps", "[OPTIONS]", "List containers")
  535. quiet := cmd.Bool("q", false, "Only display numeric IDs")
  536. fl_all := cmd.Bool("a", false, "Show all containers. Only running containers are shown by default.")
  537. fl_full := cmd.Bool("notrunc", false, "Don't truncate output")
  538. if err := cmd.Parse(args); err != nil {
  539. return nil
  540. }
  541. w := tabwriter.NewWriter(stdout, 12, 1, 3, ' ', 0)
  542. if !*quiet {
  543. fmt.Fprintf(w, "ID\tIMAGE\tCOMMAND\tCREATED\tSTATUS\tCOMMENT\n")
  544. }
  545. for _, container := range srv.runtime.List() {
  546. if !container.State.Running && !*fl_all {
  547. continue
  548. }
  549. if !*quiet {
  550. command := fmt.Sprintf("%s %s", container.Path, strings.Join(container.Args, " "))
  551. if !*fl_full {
  552. command = Trunc(command, 20)
  553. }
  554. for idx, field := range []string{
  555. /* ID */ container.Id,
  556. /* IMAGE */ srv.runtime.repositories.ImageName(container.Image),
  557. /* COMMAND */ command,
  558. /* CREATED */ HumanDuration(time.Now().Sub(container.Created)) + " ago",
  559. /* STATUS */ container.State.String(),
  560. /* COMMENT */ "",
  561. } {
  562. if idx == 0 {
  563. w.Write([]byte(field))
  564. } else {
  565. w.Write([]byte("\t" + field))
  566. }
  567. }
  568. w.Write([]byte{'\n'})
  569. } else {
  570. stdout.Write([]byte(container.Id + "\n"))
  571. }
  572. }
  573. if !*quiet {
  574. w.Flush()
  575. }
  576. return nil
  577. }
  578. func (srv *Server) CmdCommit(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  579. cmd := rcli.Subcmd(stdout,
  580. "commit", "[OPTIONS] CONTAINER [REPOSITORY [TAG]]",
  581. "Create a new image from a container's changes")
  582. if err := cmd.Parse(args); err != nil {
  583. return nil
  584. }
  585. containerName, repository, tag := cmd.Arg(0), cmd.Arg(1), cmd.Arg(2)
  586. if containerName == "" {
  587. cmd.Usage()
  588. return nil
  589. }
  590. img, err := srv.runtime.Commit(containerName, repository, tag)
  591. if err != nil {
  592. return err
  593. }
  594. fmt.Fprintln(stdout, img.Id)
  595. return nil
  596. }
  597. func (srv *Server) CmdExport(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  598. cmd := rcli.Subcmd(stdout,
  599. "export", "CONTAINER",
  600. "Export the contents of a filesystem as a tar archive")
  601. if err := cmd.Parse(args); err != nil {
  602. return nil
  603. }
  604. name := cmd.Arg(0)
  605. if container := srv.runtime.Get(name); container != nil {
  606. data, err := container.Export()
  607. if err != nil {
  608. return err
  609. }
  610. // Stream the entire contents of the container (basically a volatile snapshot)
  611. if _, err := io.Copy(stdout, data); err != nil {
  612. return err
  613. }
  614. return nil
  615. }
  616. return errors.New("No such container: " + name)
  617. }
  618. func (srv *Server) CmdDiff(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  619. cmd := rcli.Subcmd(stdout,
  620. "diff", "CONTAINER [OPTIONS]",
  621. "Inspect changes on a container's filesystem")
  622. if err := cmd.Parse(args); err != nil {
  623. return nil
  624. }
  625. if cmd.NArg() < 1 {
  626. return errors.New("Not enough arguments")
  627. }
  628. if container := srv.runtime.Get(cmd.Arg(0)); container == nil {
  629. return errors.New("No such container")
  630. } else {
  631. changes, err := container.Changes()
  632. if err != nil {
  633. return err
  634. }
  635. for _, change := range changes {
  636. fmt.Fprintln(stdout, change.String())
  637. }
  638. }
  639. return nil
  640. }
  641. func (srv *Server) CmdLogs(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  642. cmd := rcli.Subcmd(stdout, "logs", "[OPTIONS] CONTAINER", "Fetch the logs of a container")
  643. if err := cmd.Parse(args); err != nil {
  644. return nil
  645. }
  646. if cmd.NArg() != 1 {
  647. cmd.Usage()
  648. return nil
  649. }
  650. name := cmd.Arg(0)
  651. if container := srv.runtime.Get(name); container != nil {
  652. log_stdout, err := container.ReadLog("stdout")
  653. if err != nil {
  654. return err
  655. }
  656. log_stderr, err := container.ReadLog("stderr")
  657. if err != nil {
  658. return err
  659. }
  660. // FIXME: Interpolate stdout and stderr instead of concatenating them
  661. // FIXME: Differentiate stdout and stderr in the remote protocol
  662. if _, err := io.Copy(stdout, log_stdout); err != nil {
  663. return err
  664. }
  665. if _, err := io.Copy(stdout, log_stderr); err != nil {
  666. return err
  667. }
  668. return nil
  669. }
  670. return errors.New("No such container: " + cmd.Arg(0))
  671. }
  672. func (srv *Server) CmdAttach(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  673. cmd := rcli.Subcmd(stdout, "attach", "[OPTIONS]", "Attach to a running container")
  674. fl_i := cmd.Bool("i", false, "Attach to stdin")
  675. fl_o := cmd.Bool("o", true, "Attach to stdout")
  676. fl_e := cmd.Bool("e", true, "Attach to stderr")
  677. if err := cmd.Parse(args); err != nil {
  678. return nil
  679. }
  680. if cmd.NArg() != 1 {
  681. cmd.Usage()
  682. return nil
  683. }
  684. name := cmd.Arg(0)
  685. container := srv.runtime.Get(name)
  686. if container == nil {
  687. return errors.New("No such container: " + name)
  688. }
  689. var wg sync.WaitGroup
  690. if *fl_i {
  691. c_stdin, err := container.StdinPipe()
  692. if err != nil {
  693. return err
  694. }
  695. wg.Add(1)
  696. go func() { io.Copy(c_stdin, stdin); wg.Add(-1) }()
  697. }
  698. if *fl_o {
  699. c_stdout, err := container.StdoutPipe()
  700. if err != nil {
  701. return err
  702. }
  703. wg.Add(1)
  704. go func() { io.Copy(stdout, c_stdout); wg.Add(-1) }()
  705. }
  706. if *fl_e {
  707. c_stderr, err := container.StderrPipe()
  708. if err != nil {
  709. return err
  710. }
  711. wg.Add(1)
  712. go func() { io.Copy(stdout, c_stderr); wg.Add(-1) }()
  713. }
  714. wg.Wait()
  715. return nil
  716. }
  717. // Ports type - Used to parse multiple -p flags
  718. type ports []int
  719. func (p *ports) String() string {
  720. return fmt.Sprint(*p)
  721. }
  722. func (p *ports) Set(value string) error {
  723. port, err := strconv.Atoi(value)
  724. if err != nil {
  725. return fmt.Errorf("Invalid port: %v", value)
  726. }
  727. *p = append(*p, port)
  728. return nil
  729. }
  730. func (srv *Server) CmdTag(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  731. cmd := rcli.Subcmd(stdout, "tag", "[OPTIONS] IMAGE REPOSITORY [TAG]", "Tag an image into a repository")
  732. force := cmd.Bool("f", false, "Force")
  733. if err := cmd.Parse(args); err != nil {
  734. return nil
  735. }
  736. if cmd.NArg() < 2 {
  737. cmd.Usage()
  738. return nil
  739. }
  740. return srv.runtime.repositories.Set(cmd.Arg(1), cmd.Arg(2), cmd.Arg(0), *force)
  741. }
  742. func (srv *Server) CmdRun(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  743. cmd := rcli.Subcmd(stdout, "run", "[OPTIONS] IMAGE COMMAND [ARG...]", "Run a command in a new container")
  744. fl_user := cmd.String("u", "", "Username or UID")
  745. fl_attach := cmd.Bool("a", false, "Attach stdin and stdout")
  746. fl_stdin := cmd.Bool("i", false, "Keep stdin open even if not attached")
  747. fl_tty := cmd.Bool("t", false, "Allocate a pseudo-tty")
  748. fl_memory := cmd.Int64("m", 0, "Memory limit (in bytes)")
  749. var fl_ports ports
  750. cmd.Var(&fl_ports, "p", "Map a network port to the container")
  751. if err := cmd.Parse(args); err != nil {
  752. return nil
  753. }
  754. name := cmd.Arg(0)
  755. var cmdline []string
  756. if len(cmd.Args()) >= 2 {
  757. cmdline = cmd.Args()[1:]
  758. }
  759. // Choose a default image if needed
  760. if name == "" {
  761. name = "base"
  762. }
  763. // Choose a default command if needed
  764. if len(cmdline) == 0 {
  765. *fl_stdin = true
  766. *fl_tty = true
  767. *fl_attach = true
  768. cmdline = []string{"/bin/bash", "-i"}
  769. }
  770. // Create new container
  771. container, err := srv.runtime.Create(cmdline[0], cmdline[1:], name,
  772. &Config{
  773. Ports: fl_ports,
  774. User: *fl_user,
  775. Tty: *fl_tty,
  776. OpenStdin: *fl_stdin,
  777. Memory: *fl_memory,
  778. })
  779. if err != nil {
  780. return errors.New("Error creating container: " + err.Error())
  781. }
  782. if *fl_stdin {
  783. cmd_stdin, err := container.StdinPipe()
  784. if err != nil {
  785. return err
  786. }
  787. if *fl_attach {
  788. Go(func() error {
  789. _, err := io.Copy(cmd_stdin, stdin)
  790. cmd_stdin.Close()
  791. return err
  792. })
  793. }
  794. }
  795. // Run the container
  796. if *fl_attach {
  797. cmd_stderr, err := container.StderrPipe()
  798. if err != nil {
  799. return err
  800. }
  801. cmd_stdout, err := container.StdoutPipe()
  802. if err != nil {
  803. return err
  804. }
  805. if err := container.Start(); err != nil {
  806. return err
  807. }
  808. sending_stdout := Go(func() error {
  809. _, err := io.Copy(stdout, cmd_stdout)
  810. return err
  811. })
  812. sending_stderr := Go(func() error {
  813. _, err := io.Copy(stdout, cmd_stderr)
  814. return err
  815. })
  816. err_sending_stdout := <-sending_stdout
  817. err_sending_stderr := <-sending_stderr
  818. if err_sending_stdout != nil {
  819. return err_sending_stdout
  820. }
  821. if err_sending_stderr != nil {
  822. return err_sending_stderr
  823. }
  824. container.Wait()
  825. } else {
  826. if err := container.Start(); err != nil {
  827. return err
  828. }
  829. fmt.Fprintln(stdout, container.Id)
  830. }
  831. return nil
  832. }
  833. func NewServer() (*Server, error) {
  834. rand.Seed(time.Now().UTC().UnixNano())
  835. if runtime.GOARCH != "amd64" {
  836. log.Fatalf("The docker runtime currently only supports amd64 (not %s). This will change in the future. Aborting.", runtime.GOARCH)
  837. }
  838. runtime, err := NewRuntime()
  839. if err != nil {
  840. return nil, err
  841. }
  842. srv := &Server{
  843. runtime: runtime,
  844. }
  845. return srv, nil
  846. }
  847. type Server struct {
  848. runtime *Runtime
  849. }