commands.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892
  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.NewAuthConfig(username, password, email, srv.runtime.root)
  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 && image != nil {
  223. obj = image
  224. } else {
  225. // No output means the object does not exist
  226. // (easier to script since stdout and stderr are not differentiated atm)
  227. return nil
  228. }
  229. data, err := json.Marshal(obj)
  230. if err != nil {
  231. return err
  232. }
  233. indented := new(bytes.Buffer)
  234. if err = json.Indent(indented, data, "", " "); err != nil {
  235. return err
  236. }
  237. if _, err := io.Copy(stdout, indented); err != nil {
  238. return err
  239. }
  240. stdout.Write([]byte{'\n'})
  241. return nil
  242. }
  243. func (srv *Server) CmdPort(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  244. cmd := rcli.Subcmd(stdout, "port", "[OPTIONS] CONTAINER PRIVATE_PORT", "Lookup the public-facing port which is NAT-ed to PRIVATE_PORT")
  245. if err := cmd.Parse(args); err != nil {
  246. return nil
  247. }
  248. if cmd.NArg() != 2 {
  249. cmd.Usage()
  250. return nil
  251. }
  252. name := cmd.Arg(0)
  253. privatePort := cmd.Arg(1)
  254. if container := srv.runtime.Get(name); container == nil {
  255. return errors.New("No such container: " + name)
  256. } else {
  257. if frontend, exists := container.NetworkSettings.PortMapping[privatePort]; !exists {
  258. return fmt.Errorf("No private port '%s' allocated on %s", privatePort, name)
  259. } else {
  260. fmt.Fprintln(stdout, frontend)
  261. }
  262. }
  263. return nil
  264. }
  265. // 'docker rmi NAME' removes all images with the name NAME
  266. func (srv *Server) CmdRmi(stdin io.ReadCloser, stdout io.Writer, args ...string) (err error) {
  267. cmd := rcli.Subcmd(stdout, "rmimage", "[OPTIONS] IMAGE", "Remove an image")
  268. if cmd.Parse(args) != nil || cmd.NArg() < 1 {
  269. cmd.Usage()
  270. return nil
  271. }
  272. for _, name := range cmd.Args() {
  273. if err := srv.runtime.graph.Delete(name); err != nil {
  274. return err
  275. }
  276. }
  277. return nil
  278. }
  279. func (srv *Server) CmdHistory(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  280. cmd := rcli.Subcmd(stdout, "history", "[OPTIONS] IMAGE", "Show the history of an image")
  281. if cmd.Parse(args) != nil || cmd.NArg() != 1 {
  282. cmd.Usage()
  283. return nil
  284. }
  285. image, err := srv.runtime.repositories.LookupImage(cmd.Arg(0))
  286. if err != nil {
  287. return err
  288. }
  289. w := tabwriter.NewWriter(stdout, 20, 1, 3, ' ', 0)
  290. defer w.Flush()
  291. fmt.Fprintf(w, "ID\tCREATED\tCREATED BY\n")
  292. return image.WalkHistory(func(img *Image) error {
  293. fmt.Fprintf(w, "%s\t%s\t%s\n",
  294. srv.runtime.repositories.ImageName(img.Id),
  295. HumanDuration(time.Now().Sub(img.Created))+" ago",
  296. strings.Join(img.ContainerConfig.Cmd, " "),
  297. )
  298. return nil
  299. })
  300. }
  301. func (srv *Server) CmdRm(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  302. cmd := rcli.Subcmd(stdout, "rm", "[OPTIONS] CONTAINER", "Remove a container")
  303. if err := cmd.Parse(args); err != nil {
  304. return nil
  305. }
  306. for _, name := range cmd.Args() {
  307. container := srv.runtime.Get(name)
  308. if container == nil {
  309. return errors.New("No such container: " + name)
  310. }
  311. if err := srv.runtime.Destroy(container); err != nil {
  312. fmt.Fprintln(stdout, "Error destroying container "+name+": "+err.Error())
  313. }
  314. }
  315. return nil
  316. }
  317. // 'docker kill NAME' kills a running container
  318. func (srv *Server) CmdKill(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  319. cmd := rcli.Subcmd(stdout, "kill", "[OPTIONS] CONTAINER [CONTAINER...]", "Kill a running container")
  320. if err := cmd.Parse(args); err != nil {
  321. return nil
  322. }
  323. for _, name := range cmd.Args() {
  324. container := srv.runtime.Get(name)
  325. if container == nil {
  326. return errors.New("No such container: " + name)
  327. }
  328. if err := container.Kill(); err != nil {
  329. fmt.Fprintln(stdout, "Error killing container "+name+": "+err.Error())
  330. }
  331. }
  332. return nil
  333. }
  334. func (srv *Server) CmdImport(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  335. cmd := rcli.Subcmd(stdout, "import", "[OPTIONS] URL|- [REPOSITORY [TAG]]", "Create a new filesystem image from the contents of a tarball")
  336. var archive io.Reader
  337. var resp *http.Response
  338. if err := cmd.Parse(args); err != nil {
  339. return nil
  340. }
  341. src := cmd.Arg(0)
  342. if src == "" {
  343. return errors.New("Not enough arguments")
  344. } else if src == "-" {
  345. archive = stdin
  346. } else {
  347. u, err := url.Parse(src)
  348. if err != nil {
  349. return err
  350. }
  351. if u.Scheme == "" {
  352. u.Scheme = "http"
  353. u.Host = src
  354. u.Path = ""
  355. }
  356. fmt.Fprintf(stdout, "Downloading from %s\n", u.String())
  357. // Download with curl (pretty progress bar)
  358. // If curl is not available, fallback to http.Get()
  359. resp, err = Download(u.String(), stdout)
  360. if err != nil {
  361. return err
  362. }
  363. archive = ProgressReader(resp.Body, int(resp.ContentLength), stdout)
  364. }
  365. img, err := srv.runtime.graph.Create(archive, nil, "Imported from "+src)
  366. if err != nil {
  367. return err
  368. }
  369. // Optionally register the image at REPO/TAG
  370. if repository := cmd.Arg(1); repository != "" {
  371. tag := cmd.Arg(2) // Repository will handle an empty tag properly
  372. if err := srv.runtime.repositories.Set(repository, tag, img.Id, true); err != nil {
  373. return err
  374. }
  375. }
  376. fmt.Fprintln(stdout, img.Id)
  377. return nil
  378. }
  379. func (srv *Server) CmdPush(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  380. cmd := rcli.Subcmd(stdout, "push", "LOCAL", "Push an image or a repository to the registry")
  381. if err := cmd.Parse(args); err != nil {
  382. return nil
  383. }
  384. local := cmd.Arg(0)
  385. if local == "" {
  386. cmd.Usage()
  387. return nil
  388. }
  389. // If the login failed, abort
  390. if srv.runtime.authConfig == nil {
  391. return fmt.Errorf("Please login prior to push. ('docker login')")
  392. }
  393. var remote string
  394. tmp := strings.SplitN(local, "/", 2)
  395. if len(tmp) == 1 {
  396. remote = srv.runtime.authConfig.Username + "/" + local
  397. } else {
  398. remote = local
  399. }
  400. Debugf("Pushing [%s] to [%s]\n", local, remote)
  401. // Try to get the image
  402. // FIXME: Handle lookup
  403. // FIXME: Also push the tags in case of ./docker push myrepo:mytag
  404. // img, err := srv.runtime.LookupImage(cmd.Arg(0))
  405. img, err := srv.runtime.graph.Get(local)
  406. if err != nil {
  407. Debugf("The push refers to a repository [%s] (len: %d)\n", local, len(srv.runtime.repositories.Repositories[local]))
  408. // If it fails, try to get the repository
  409. if localRepo, exists := srv.runtime.repositories.Repositories[local]; exists {
  410. fmt.Fprintf(stdout, "Pushing %s (%d tags) on %s...\n", local, len(localRepo), remote)
  411. if err := srv.runtime.graph.PushRepository(stdout, remote, localRepo, srv.runtime.authConfig); err != nil {
  412. return err
  413. }
  414. fmt.Fprintf(stdout, "Push completed\n")
  415. return nil
  416. } else {
  417. return err
  418. }
  419. return nil
  420. }
  421. fmt.Fprintf(stdout, "Pushing image %s..\n", img.Id)
  422. err = srv.runtime.graph.PushImage(stdout, img, srv.runtime.authConfig)
  423. if err != nil {
  424. return err
  425. }
  426. fmt.Fprintf(stdout, "Push completed\n")
  427. return nil
  428. }
  429. func (srv *Server) CmdPull(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  430. cmd := rcli.Subcmd(stdout, "pull", "IMAGE", "Pull an image or a repository from the registry")
  431. if err := cmd.Parse(args); err != nil {
  432. return nil
  433. }
  434. remote := cmd.Arg(0)
  435. if remote == "" {
  436. cmd.Usage()
  437. return nil
  438. }
  439. if srv.runtime.authConfig == nil {
  440. return fmt.Errorf("Please login prior to push. ('docker login')")
  441. }
  442. if srv.runtime.graph.LookupRemoteImage(remote, srv.runtime.authConfig) {
  443. fmt.Fprintf(stdout, "Pulling %s...\n", remote)
  444. if err := srv.runtime.graph.PullImage(remote, srv.runtime.authConfig); err != nil {
  445. return err
  446. }
  447. fmt.Fprintf(stdout, "Pulled\n")
  448. return nil
  449. }
  450. // FIXME: Allow pull repo:tag
  451. fmt.Fprintf(stdout, "Pulling %s...\n", remote)
  452. if err := srv.runtime.graph.PullRepository(stdout, remote, "", srv.runtime.repositories, srv.runtime.authConfig); err != nil {
  453. return err
  454. }
  455. fmt.Fprintf(stdout, "Pull completed\n")
  456. return nil
  457. }
  458. func (srv *Server) CmdImages(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  459. cmd := rcli.Subcmd(stdout, "images", "[OPTIONS] [NAME]", "List images")
  460. //limit := cmd.Int("l", 0, "Only show the N most recent versions of each image")
  461. quiet := cmd.Bool("q", false, "only show numeric IDs")
  462. if err := cmd.Parse(args); err != nil {
  463. return nil
  464. }
  465. if cmd.NArg() > 1 {
  466. cmd.Usage()
  467. return nil
  468. }
  469. var nameFilter string
  470. if cmd.NArg() == 1 {
  471. nameFilter = cmd.Arg(0)
  472. }
  473. w := tabwriter.NewWriter(stdout, 20, 1, 3, ' ', 0)
  474. if !*quiet {
  475. fmt.Fprintf(w, "REPOSITORY\tTAG\tID\tCREATED\tPARENT\n")
  476. }
  477. allImages, err := srv.runtime.graph.Map()
  478. if err != nil {
  479. return err
  480. }
  481. for name, repository := range srv.runtime.repositories.Repositories {
  482. if nameFilter != "" && name != nameFilter {
  483. continue
  484. }
  485. for tag, id := range repository {
  486. image, err := srv.runtime.graph.Get(id)
  487. if err != nil {
  488. log.Printf("Warning: couldn't load %s from %s/%s: %s", id, name, tag, err)
  489. continue
  490. }
  491. delete(allImages, id)
  492. if !*quiet {
  493. for idx, field := range []string{
  494. /* REPOSITORY */ name,
  495. /* TAG */ tag,
  496. /* ID */ id,
  497. /* CREATED */ HumanDuration(time.Now().Sub(image.Created)) + " ago",
  498. /* PARENT */ srv.runtime.repositories.ImageName(image.Parent),
  499. } {
  500. if idx == 0 {
  501. w.Write([]byte(field))
  502. } else {
  503. w.Write([]byte("\t" + field))
  504. }
  505. }
  506. w.Write([]byte{'\n'})
  507. } else {
  508. stdout.Write([]byte(image.Id + "\n"))
  509. }
  510. }
  511. }
  512. // Display images which aren't part of a
  513. if nameFilter == "" {
  514. for id, image := range allImages {
  515. if !*quiet {
  516. for idx, field := range []string{
  517. /* REPOSITORY */ "",
  518. /* TAG */ "",
  519. /* ID */ id,
  520. /* CREATED */ HumanDuration(time.Now().Sub(image.Created)) + " ago",
  521. /* PARENT */ srv.runtime.repositories.ImageName(image.Parent),
  522. } {
  523. if idx == 0 {
  524. w.Write([]byte(field))
  525. } else {
  526. w.Write([]byte("\t" + field))
  527. }
  528. }
  529. w.Write([]byte{'\n'})
  530. } else {
  531. stdout.Write([]byte(image.Id + "\n"))
  532. }
  533. }
  534. }
  535. if !*quiet {
  536. w.Flush()
  537. }
  538. return nil
  539. }
  540. func (srv *Server) CmdPs(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  541. cmd := rcli.Subcmd(stdout,
  542. "ps", "[OPTIONS]", "List containers")
  543. quiet := cmd.Bool("q", false, "Only display numeric IDs")
  544. fl_all := cmd.Bool("a", false, "Show all containers. Only running containers are shown by default.")
  545. fl_full := cmd.Bool("notrunc", false, "Don't truncate output")
  546. if err := cmd.Parse(args); err != nil {
  547. return nil
  548. }
  549. w := tabwriter.NewWriter(stdout, 12, 1, 3, ' ', 0)
  550. if !*quiet {
  551. fmt.Fprintf(w, "ID\tIMAGE\tCOMMAND\tCREATED\tSTATUS\tCOMMENT\n")
  552. }
  553. for _, container := range srv.runtime.List() {
  554. if !container.State.Running && !*fl_all {
  555. continue
  556. }
  557. if !*quiet {
  558. command := fmt.Sprintf("%s %s", container.Path, strings.Join(container.Args, " "))
  559. if !*fl_full {
  560. command = Trunc(command, 20)
  561. }
  562. for idx, field := range []string{
  563. /* ID */ container.Id,
  564. /* IMAGE */ srv.runtime.repositories.ImageName(container.Image),
  565. /* COMMAND */ command,
  566. /* CREATED */ HumanDuration(time.Now().Sub(container.Created)) + " ago",
  567. /* STATUS */ container.State.String(),
  568. /* COMMENT */ "",
  569. } {
  570. if idx == 0 {
  571. w.Write([]byte(field))
  572. } else {
  573. w.Write([]byte("\t" + field))
  574. }
  575. }
  576. w.Write([]byte{'\n'})
  577. } else {
  578. stdout.Write([]byte(container.Id + "\n"))
  579. }
  580. }
  581. if !*quiet {
  582. w.Flush()
  583. }
  584. return nil
  585. }
  586. func (srv *Server) CmdCommit(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  587. cmd := rcli.Subcmd(stdout,
  588. "commit", "[OPTIONS] CONTAINER [REPOSITORY [TAG]]",
  589. "Create a new image from a container's changes")
  590. if err := cmd.Parse(args); err != nil {
  591. return nil
  592. }
  593. containerName, repository, tag := cmd.Arg(0), cmd.Arg(1), cmd.Arg(2)
  594. if containerName == "" {
  595. cmd.Usage()
  596. return nil
  597. }
  598. img, err := srv.runtime.Commit(containerName, repository, tag)
  599. if err != nil {
  600. return err
  601. }
  602. fmt.Fprintln(stdout, img.Id)
  603. return nil
  604. }
  605. func (srv *Server) CmdExport(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  606. cmd := rcli.Subcmd(stdout,
  607. "export", "CONTAINER",
  608. "Export the contents of a filesystem as a tar archive")
  609. if err := cmd.Parse(args); err != nil {
  610. return nil
  611. }
  612. name := cmd.Arg(0)
  613. if container := srv.runtime.Get(name); container != nil {
  614. data, err := container.Export()
  615. if err != nil {
  616. return err
  617. }
  618. // Stream the entire contents of the container (basically a volatile snapshot)
  619. if _, err := io.Copy(stdout, data); err != nil {
  620. return err
  621. }
  622. return nil
  623. }
  624. return errors.New("No such container: " + name)
  625. }
  626. func (srv *Server) CmdDiff(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  627. cmd := rcli.Subcmd(stdout,
  628. "diff", "CONTAINER [OPTIONS]",
  629. "Inspect changes on a container's filesystem")
  630. if err := cmd.Parse(args); err != nil {
  631. return nil
  632. }
  633. if cmd.NArg() < 1 {
  634. return errors.New("Not enough arguments")
  635. }
  636. if container := srv.runtime.Get(cmd.Arg(0)); container == nil {
  637. return errors.New("No such container")
  638. } else {
  639. changes, err := container.Changes()
  640. if err != nil {
  641. return err
  642. }
  643. for _, change := range changes {
  644. fmt.Fprintln(stdout, change.String())
  645. }
  646. }
  647. return nil
  648. }
  649. func (srv *Server) CmdLogs(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  650. cmd := rcli.Subcmd(stdout, "logs", "[OPTIONS] CONTAINER", "Fetch the logs of a container")
  651. if err := cmd.Parse(args); err != nil {
  652. return nil
  653. }
  654. if cmd.NArg() != 1 {
  655. cmd.Usage()
  656. return nil
  657. }
  658. name := cmd.Arg(0)
  659. if container := srv.runtime.Get(name); container != nil {
  660. log_stdout, err := container.ReadLog("stdout")
  661. if err != nil {
  662. return err
  663. }
  664. log_stderr, err := container.ReadLog("stderr")
  665. if err != nil {
  666. return err
  667. }
  668. // FIXME: Interpolate stdout and stderr instead of concatenating them
  669. // FIXME: Differentiate stdout and stderr in the remote protocol
  670. if _, err := io.Copy(stdout, log_stdout); err != nil {
  671. return err
  672. }
  673. if _, err := io.Copy(stdout, log_stderr); err != nil {
  674. return err
  675. }
  676. return nil
  677. }
  678. return errors.New("No such container: " + cmd.Arg(0))
  679. }
  680. func (srv *Server) CmdAttach(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  681. cmd := rcli.Subcmd(stdout, "attach", "[OPTIONS]", "Attach to a running container")
  682. fl_i := cmd.Bool("i", false, "Attach to stdin")
  683. fl_o := cmd.Bool("o", true, "Attach to stdout")
  684. fl_e := cmd.Bool("e", true, "Attach to stderr")
  685. if err := cmd.Parse(args); err != nil {
  686. return nil
  687. }
  688. if cmd.NArg() != 1 {
  689. cmd.Usage()
  690. return nil
  691. }
  692. name := cmd.Arg(0)
  693. container := srv.runtime.Get(name)
  694. if container == nil {
  695. return errors.New("No such container: " + name)
  696. }
  697. var wg sync.WaitGroup
  698. if *fl_i {
  699. c_stdin, err := container.StdinPipe()
  700. if err != nil {
  701. return err
  702. }
  703. wg.Add(1)
  704. go func() { io.Copy(c_stdin, stdin); wg.Add(-1) }()
  705. }
  706. if *fl_o {
  707. c_stdout, err := container.StdoutPipe()
  708. if err != nil {
  709. return err
  710. }
  711. wg.Add(1)
  712. go func() { io.Copy(stdout, c_stdout); wg.Add(-1) }()
  713. }
  714. if *fl_e {
  715. c_stderr, err := container.StderrPipe()
  716. if err != nil {
  717. return err
  718. }
  719. wg.Add(1)
  720. go func() { io.Copy(stdout, c_stderr); wg.Add(-1) }()
  721. }
  722. wg.Wait()
  723. return nil
  724. }
  725. // Ports type - Used to parse multiple -p flags
  726. type ports []int
  727. func (p *ports) String() string {
  728. return fmt.Sprint(*p)
  729. }
  730. func (p *ports) Set(value string) error {
  731. port, err := strconv.Atoi(value)
  732. if err != nil {
  733. return fmt.Errorf("Invalid port: %v", value)
  734. }
  735. *p = append(*p, port)
  736. return nil
  737. }
  738. // ListOpts type
  739. type ListOpts []string
  740. func (opts *ListOpts) String() string {
  741. return fmt.Sprint(*opts)
  742. }
  743. func (opts *ListOpts) Set(value string) error {
  744. *opts = append(*opts, value)
  745. return nil
  746. }
  747. func (srv *Server) CmdTag(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  748. cmd := rcli.Subcmd(stdout, "tag", "[OPTIONS] IMAGE REPOSITORY [TAG]", "Tag an image into a repository")
  749. force := cmd.Bool("f", false, "Force")
  750. if err := cmd.Parse(args); err != nil {
  751. return nil
  752. }
  753. if cmd.NArg() < 2 {
  754. cmd.Usage()
  755. return nil
  756. }
  757. return srv.runtime.repositories.Set(cmd.Arg(1), cmd.Arg(2), cmd.Arg(0), *force)
  758. }
  759. func (srv *Server) CmdRun(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  760. config, err := ParseRun(args)
  761. if err != nil {
  762. return err
  763. }
  764. if config.Image == "" {
  765. return fmt.Errorf("Image not specified")
  766. }
  767. if len(config.Cmd) == 0 {
  768. return fmt.Errorf("Command not specified")
  769. }
  770. // Create new container
  771. container, err := srv.runtime.Create(config)
  772. if err != nil {
  773. return errors.New("Error creating container: " + err.Error())
  774. }
  775. if config.OpenStdin {
  776. cmd_stdin, err := container.StdinPipe()
  777. if err != nil {
  778. return err
  779. }
  780. if !config.Detach {
  781. Go(func() error {
  782. _, err := io.Copy(cmd_stdin, stdin)
  783. cmd_stdin.Close()
  784. return err
  785. })
  786. }
  787. }
  788. // Run the container
  789. if !config.Detach {
  790. cmd_stderr, err := container.StderrPipe()
  791. if err != nil {
  792. return err
  793. }
  794. cmd_stdout, err := container.StdoutPipe()
  795. if err != nil {
  796. return err
  797. }
  798. if err := container.Start(); err != nil {
  799. return err
  800. }
  801. sending_stdout := Go(func() error {
  802. _, err := io.Copy(stdout, cmd_stdout)
  803. return err
  804. })
  805. sending_stderr := Go(func() error {
  806. _, err := io.Copy(stdout, cmd_stderr)
  807. return err
  808. })
  809. err_sending_stdout := <-sending_stdout
  810. err_sending_stderr := <-sending_stderr
  811. if err_sending_stdout != nil {
  812. return err_sending_stdout
  813. }
  814. if err_sending_stderr != nil {
  815. return err_sending_stderr
  816. }
  817. container.Wait()
  818. } else {
  819. if err := container.Start(); err != nil {
  820. return err
  821. }
  822. fmt.Fprintln(stdout, container.Id)
  823. }
  824. return nil
  825. }
  826. func NewServer() (*Server, error) {
  827. rand.Seed(time.Now().UTC().UnixNano())
  828. if runtime.GOARCH != "amd64" {
  829. log.Fatalf("The docker runtime currently only supports amd64 (not %s). This will change in the future. Aborting.", runtime.GOARCH)
  830. }
  831. runtime, err := NewRuntime()
  832. if err != nil {
  833. return nil, err
  834. }
  835. srv := &Server{
  836. runtime: runtime,
  837. }
  838. return srv, nil
  839. }
  840. type Server struct {
  841. runtime *Runtime
  842. }