commands.go 23 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049
  1. package docker
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "flag"
  6. "fmt"
  7. "github.com/dotcloud/docker/term"
  8. "io"
  9. "io/ioutil"
  10. "net"
  11. "net/http"
  12. "net/http/httputil"
  13. "net/url"
  14. "os"
  15. "strconv"
  16. "text/tabwriter"
  17. )
  18. const VERSION = "0.1.4"
  19. var (
  20. GIT_COMMIT string
  21. NO_MEMORY_LIMIT bool
  22. )
  23. func ParseCommands(args []string) error {
  24. cmds := map[string]func(args []string) error{
  25. "attach": CmdAttach,
  26. "commit": CmdCommit,
  27. "diff": CmdDiff,
  28. "export": CmdExport,
  29. "images": CmdImages,
  30. "info": CmdInfo,
  31. "inspect": CmdInspect,
  32. "history": CmdHistory,
  33. "kill": CmdKill,
  34. "logs": CmdLogs,
  35. "port": CmdPort,
  36. "ps": CmdPs,
  37. "pull": CmdPull,
  38. "restart": CmdRestart,
  39. "rm": CmdRm,
  40. "rmi": CmdRmi,
  41. "run": CmdRun,
  42. "tag": CmdTag,
  43. "start": CmdStart,
  44. "stop": CmdStop,
  45. "version": CmdVersion,
  46. "wait": CmdWait,
  47. }
  48. if len(args) > 0 {
  49. cmd, exists := cmds[args[0]]
  50. if !exists {
  51. fmt.Println("Error: Command not found:", args[0])
  52. return cmdHelp(args)
  53. }
  54. return cmd(args[1:])
  55. }
  56. return cmdHelp(args)
  57. }
  58. func cmdHelp(args []string) error {
  59. help := "Usage: docker COMMAND [arg...]\n\nA self-sufficient runtime for linux containers.\n\nCommands:\n"
  60. for _, cmd := range [][]string{
  61. {"attach", "Attach to a running container"},
  62. {"commit", "Create a new image from a container's changes"},
  63. {"diff", "Inspect changes on a container's filesystem"},
  64. {"export", "Stream the contents of a container as a tar archive"},
  65. {"history", "Show the history of an image"},
  66. {"images", "List images"},
  67. // {"import", "Create a new filesystem image from the contents of a tarball"},
  68. {"info", "Display system-wide information"},
  69. {"inspect", "Return low-level information on a container/image"},
  70. {"kill", "Kill a running container"},
  71. // {"login", "Register or Login to the docker registry server"},
  72. {"logs", "Fetch the logs of a container"},
  73. {"port", "Lookup the public-facing port which is NAT-ed to PRIVATE_PORT"},
  74. {"ps", "List containers"},
  75. {"pull", "Pull an image or a repository from the docker registry server"},
  76. // {"push", "Push an image or a repository to the docker registry server"},
  77. {"restart", "Restart a running container"},
  78. {"rm", "Remove a container"},
  79. {"rmi", "Remove an image"},
  80. {"run", "Run a command in a new container"},
  81. {"start", "Start a stopped container"},
  82. {"stop", "Stop a running container"},
  83. {"tag", "Tag an image into a repository"},
  84. {"version", "Show the docker version information"},
  85. {"wait", "Block until a container stops, then print its exit code"},
  86. } {
  87. help += fmt.Sprintf(" %-10.10s%s\n", cmd[0], cmd[1])
  88. }
  89. fmt.Println(help)
  90. return nil
  91. }
  92. /*
  93. // 'docker login': login / register a user to registry service.
  94. func (srv *Server) CmdLogin(stdin io.ReadCloser, stdout rcli.DockerConn, args ...string) error {
  95. // Read a line on raw terminal with support for simple backspace
  96. // sequences and echo.
  97. //
  98. // This function is necessary because the login command must be done in a
  99. // raw terminal for two reasons:
  100. // - we have to read a password (without echoing it);
  101. // - the rcli "protocol" only supports cannonical and raw modes and you
  102. // can't tune it once the command as been started.
  103. var readStringOnRawTerminal = func(stdin io.Reader, stdout io.Writer, echo bool) string {
  104. char := make([]byte, 1)
  105. buffer := make([]byte, 64)
  106. var i = 0
  107. for i < len(buffer) {
  108. n, err := stdin.Read(char)
  109. if n > 0 {
  110. if char[0] == '\r' || char[0] == '\n' {
  111. stdout.Write([]byte{'\r', '\n'})
  112. break
  113. } else if char[0] == 127 || char[0] == '\b' {
  114. if i > 0 {
  115. if echo {
  116. stdout.Write([]byte{'\b', ' ', '\b'})
  117. }
  118. i--
  119. }
  120. } else if !unicode.IsSpace(rune(char[0])) &&
  121. !unicode.IsControl(rune(char[0])) {
  122. if echo {
  123. stdout.Write(char)
  124. }
  125. buffer[i] = char[0]
  126. i++
  127. }
  128. }
  129. if err != nil {
  130. if err != io.EOF {
  131. fmt.Fprintf(stdout, "Read error: %v\r\n", err)
  132. }
  133. break
  134. }
  135. }
  136. return string(buffer[:i])
  137. }
  138. var readAndEchoString = func(stdin io.Reader, stdout io.Writer) string {
  139. return readStringOnRawTerminal(stdin, stdout, true)
  140. }
  141. var readString = func(stdin io.Reader, stdout io.Writer) string {
  142. return readStringOnRawTerminal(stdin, stdout, false)
  143. }
  144. stdout.SetOptionRawTerminal()
  145. cmd := rcli.Subcmd(stdout, "login", "", "Register or Login to the docker registry server")
  146. if err := cmd.Parse(args); err != nil {
  147. return nil
  148. }
  149. var username string
  150. var password string
  151. var email string
  152. fmt.Fprint(stdout, "Username (", srv.runtime.authConfig.Username, "): ")
  153. username = readAndEchoString(stdin, stdout)
  154. if username == "" {
  155. username = srv.runtime.authConfig.Username
  156. }
  157. if username != srv.runtime.authConfig.Username {
  158. fmt.Fprint(stdout, "Password: ")
  159. password = readString(stdin, stdout)
  160. if password == "" {
  161. return fmt.Errorf("Error : Password Required")
  162. }
  163. fmt.Fprint(stdout, "Email (", srv.runtime.authConfig.Email, "): ")
  164. email = readAndEchoString(stdin, stdout)
  165. if email == "" {
  166. email = srv.runtime.authConfig.Email
  167. }
  168. } else {
  169. password = srv.runtime.authConfig.Password
  170. email = srv.runtime.authConfig.Email
  171. }
  172. newAuthConfig := auth.NewAuthConfig(username, password, email, srv.runtime.root)
  173. status, err := auth.Login(newAuthConfig)
  174. if err != nil {
  175. fmt.Fprintf(stdout, "Error: %s\r\n", err)
  176. } else {
  177. srv.runtime.authConfig = newAuthConfig
  178. }
  179. if status != "" {
  180. fmt.Fprint(stdout, status)
  181. }
  182. return nil
  183. }
  184. */
  185. // 'docker wait': block until a container stops
  186. func CmdWait(args []string) error {
  187. cmd := Subcmd("wait", "CONTAINER [CONTAINER...]", "Block until a container stops, then print its exit code.")
  188. if err := cmd.Parse(args); err != nil {
  189. return nil
  190. }
  191. if cmd.NArg() < 1 {
  192. cmd.Usage()
  193. return nil
  194. }
  195. for _, name := range cmd.Args() {
  196. body, err := call("POST", "/containers/"+name+"/wait")
  197. if err != nil {
  198. fmt.Printf("%s", err)
  199. } else {
  200. var out ApiWait
  201. err = json.Unmarshal(body, &out)
  202. if err != nil {
  203. return err
  204. }
  205. fmt.Println(out.StatusCode)
  206. }
  207. }
  208. return nil
  209. }
  210. // 'docker version': show version information
  211. func CmdVersion(args []string) error {
  212. cmd := Subcmd("version", "", "Show the docker version information.")
  213. if err := cmd.Parse(args); err != nil {
  214. return nil
  215. }
  216. if cmd.NArg() > 0 {
  217. cmd.Usage()
  218. return nil
  219. }
  220. body, err := call("GET", "/version")
  221. if err != nil {
  222. return err
  223. }
  224. var out ApiVersion
  225. err = json.Unmarshal(body, &out)
  226. if err != nil {
  227. return err
  228. }
  229. fmt.Println("Version:", out.Version)
  230. fmt.Println("Git Commit:", out.GitCommit)
  231. if out.MemoryLimitDisabled {
  232. fmt.Println("Memory limit disabled")
  233. }
  234. return nil
  235. }
  236. // 'docker info': display system-wide information.
  237. func CmdInfo(args []string) error {
  238. cmd := Subcmd("info", "", "Display system-wide information")
  239. if err := cmd.Parse(args); err != nil {
  240. return nil
  241. }
  242. if cmd.NArg() > 0 {
  243. cmd.Usage()
  244. return nil
  245. }
  246. body, err := call("GET", "/info")
  247. if err != nil {
  248. return err
  249. }
  250. var out ApiInfo
  251. err = json.Unmarshal(body, &out)
  252. if err != nil {
  253. return err
  254. }
  255. fmt.Printf("containers: %d\nversion: %s\nimages: %d\n", out.Containers, out.Version, out.Images)
  256. if out.Debug {
  257. fmt.Println("debug mode enabled")
  258. fmt.Printf("fds: %d\ngoroutines: %d\n", out.NFd, out.NGoroutines)
  259. }
  260. return nil
  261. }
  262. func CmdStop(args []string) error {
  263. cmd := Subcmd("stop", "CONTAINER [CONTAINER...]", "Stop a running container")
  264. if err := cmd.Parse(args); err != nil {
  265. return nil
  266. }
  267. if cmd.NArg() < 1 {
  268. cmd.Usage()
  269. return nil
  270. }
  271. for _, name := range args {
  272. _, err := call("POST", "/containers/"+name+"/stop")
  273. if err != nil {
  274. fmt.Printf("%s", err)
  275. } else {
  276. fmt.Println(name)
  277. }
  278. }
  279. return nil
  280. }
  281. func CmdRestart(args []string) error {
  282. cmd := Subcmd("restart", "CONTAINER [CONTAINER...]", "Restart a running container")
  283. if err := cmd.Parse(args); err != nil {
  284. return nil
  285. }
  286. if cmd.NArg() < 1 {
  287. cmd.Usage()
  288. return nil
  289. }
  290. for _, name := range args {
  291. _, err := call("POST", "/containers/"+name+"/restart")
  292. if err != nil {
  293. fmt.Printf("%s", err)
  294. } else {
  295. fmt.Println(name)
  296. }
  297. }
  298. return nil
  299. }
  300. func CmdStart(args []string) error {
  301. cmd := Subcmd("start", "CONTAINER [CONTAINER...]", "Restart a stopped container")
  302. if err := cmd.Parse(args); err != nil {
  303. return nil
  304. }
  305. if cmd.NArg() < 1 {
  306. cmd.Usage()
  307. return nil
  308. }
  309. for _, name := range args {
  310. _, err := call("POST", "/containers/"+name+"/start")
  311. if err != nil {
  312. fmt.Printf("%s", err)
  313. } else {
  314. fmt.Println(name)
  315. }
  316. }
  317. return nil
  318. }
  319. func CmdInspect(args []string) error {
  320. cmd := Subcmd("inspect", "CONTAINER|IMAGE", "Return low-level information on a container/image")
  321. if err := cmd.Parse(args); err != nil {
  322. return nil
  323. }
  324. if cmd.NArg() != 1 {
  325. cmd.Usage()
  326. return nil
  327. }
  328. obj, err := call("GET", "/containers/"+cmd.Arg(0))
  329. if err != nil {
  330. obj, err = call("GET", "/images/"+cmd.Arg(0))
  331. if err != nil {
  332. return err
  333. }
  334. }
  335. fmt.Printf("%s\n", obj)
  336. return nil
  337. }
  338. func CmdPort(args []string) error {
  339. cmd := Subcmd("port", "CONTAINER PRIVATE_PORT", "Lookup the public-facing port which is NAT-ed to PRIVATE_PORT")
  340. if err := cmd.Parse(args); err != nil {
  341. return nil
  342. }
  343. if cmd.NArg() != 2 {
  344. cmd.Usage()
  345. return nil
  346. }
  347. v := url.Values{}
  348. v.Set("port", cmd.Arg(1))
  349. body, err := call("GET", "/containers/"+cmd.Arg(0)+"/port?"+v.Encode())
  350. if err != nil {
  351. return err
  352. }
  353. var out ApiPort
  354. err = json.Unmarshal(body, &out)
  355. if err != nil {
  356. return err
  357. }
  358. fmt.Println(out.Port)
  359. return nil
  360. }
  361. // 'docker rmi IMAGE' removes all images with the name IMAGE
  362. func CmdRmi(args []string) error {
  363. cmd := Subcmd("rmi", "IMAGE [IMAGE...]", "Remove an image")
  364. if err := cmd.Parse(args); err != nil {
  365. return nil
  366. }
  367. if cmd.NArg() < 1 {
  368. cmd.Usage()
  369. return nil
  370. }
  371. for _, name := range args {
  372. _, err := call("DELETE", "/images/"+name)
  373. if err != nil {
  374. fmt.Printf("%s", err)
  375. } else {
  376. fmt.Println(name)
  377. }
  378. }
  379. return nil
  380. }
  381. func CmdHistory(args []string) error {
  382. cmd := Subcmd("history", "IMAGE", "Show the history of an image")
  383. if err := cmd.Parse(args); err != nil {
  384. return nil
  385. }
  386. if cmd.NArg() != 1 {
  387. cmd.Usage()
  388. return nil
  389. }
  390. body, err := call("GET", "/images/"+cmd.Arg(0)+"/history")
  391. if err != nil {
  392. return err
  393. }
  394. var outs []ApiHistory
  395. err = json.Unmarshal(body, &outs)
  396. if err != nil {
  397. return err
  398. }
  399. w := tabwriter.NewWriter(os.Stdout, 20, 1, 3, ' ', 0)
  400. fmt.Fprintln(w, "ID\tCREATED\tCREATED BY")
  401. for _, out := range outs {
  402. fmt.Fprintf(w, "%s\t%s\t%s\n", out.Id, out.Created, out.CreatedBy)
  403. }
  404. w.Flush()
  405. return nil
  406. }
  407. func CmdRm(args []string) error {
  408. cmd := Subcmd("rm", "CONTAINER [CONTAINER...]", "Remove a container")
  409. if err := cmd.Parse(args); err != nil {
  410. return nil
  411. }
  412. if cmd.NArg() < 1 {
  413. cmd.Usage()
  414. return nil
  415. }
  416. for _, name := range args {
  417. _, err := call("DELETE", "/containers/"+name)
  418. if err != nil {
  419. fmt.Printf("%s", err)
  420. } else {
  421. fmt.Println(name)
  422. }
  423. }
  424. return nil
  425. }
  426. // 'docker kill NAME' kills a running container
  427. func CmdKill(args []string) error {
  428. cmd := Subcmd("kill", "CONTAINER [CONTAINER...]", "Kill a running container")
  429. if err := cmd.Parse(args); err != nil {
  430. return nil
  431. }
  432. if cmd.NArg() < 1 {
  433. cmd.Usage()
  434. return nil
  435. }
  436. for _, name := range args {
  437. _, err := call("POST", "/containers/"+name+"/kill")
  438. if err != nil {
  439. fmt.Printf("%s", err)
  440. } else {
  441. fmt.Println(name)
  442. }
  443. }
  444. return nil
  445. }
  446. /*
  447. func (srv *Server) CmdImport(stdin io.ReadCloser, stdout rcli.DockerConn, args ...string) error {
  448. stdout.Flush()
  449. cmd := rcli.Subcmd(stdout, "import", "URL|- [REPOSITORY [TAG]]", "Create a new filesystem image from the contents of a tarball")
  450. var archive io.Reader
  451. var resp *http.Response
  452. if err := cmd.Parse(args); err != nil {
  453. return nil
  454. }
  455. if cmd.NArg() < 1 {
  456. cmd.Usage()
  457. return nil
  458. }
  459. src := cmd.Arg(0)
  460. if src == "-" {
  461. archive = stdin
  462. } else {
  463. u, err := url.Parse(src)
  464. if err != nil {
  465. return err
  466. }
  467. if u.Scheme == "" {
  468. u.Scheme = "http"
  469. u.Host = src
  470. u.Path = ""
  471. }
  472. fmt.Fprintln(stdout, "Downloading from", u)
  473. // Download with curl (pretty progress bar)
  474. // If curl is not available, fallback to http.Get()
  475. resp, err = Download(u.String(), stdout)
  476. if err != nil {
  477. return err
  478. }
  479. archive = ProgressReader(resp.Body, int(resp.ContentLength), stdout)
  480. }
  481. img, err := srv.runtime.graph.Create(archive, nil, "Imported from "+src)
  482. if err != nil {
  483. return err
  484. }
  485. // Optionally register the image at REPO/TAG
  486. if repository := cmd.Arg(1); repository != "" {
  487. tag := cmd.Arg(2) // Repository will handle an empty tag properly
  488. if err := srv.runtime.repositories.Set(repository, tag, img.Id, true); err != nil {
  489. return err
  490. }
  491. }
  492. fmt.Fprintln(stdout, img.ShortId())
  493. return nil
  494. }
  495. */
  496. /*
  497. func (srv *Server) CmdPush(stdin io.ReadCloser, stdout rcli.DockerConn, args ...string) error {
  498. cmd := rcli.Subcmd(stdout, "push", "NAME", "Push an image or a repository to the registry")
  499. if err := cmd.Parse(args); err != nil {
  500. return nil
  501. }
  502. local := cmd.Arg(0)
  503. if local == "" {
  504. cmd.Usage()
  505. return nil
  506. }
  507. // If the login failed, abort
  508. if srv.runtime.authConfig == nil || srv.runtime.authConfig.Username == "" {
  509. if err := srv.CmdLogin(stdin, stdout, args...); err != nil {
  510. return err
  511. }
  512. if srv.runtime.authConfig == nil || srv.runtime.authConfig.Username == "" {
  513. return fmt.Errorf("Please login prior to push. ('docker login')")
  514. }
  515. }
  516. var remote string
  517. tmp := strings.SplitN(local, "/", 2)
  518. if len(tmp) == 1 {
  519. return fmt.Errorf(
  520. "Impossible to push a \"root\" repository. Please rename your repository in <user>/<repo> (ex: %s/%s)",
  521. srv.runtime.authConfig.Username, local)
  522. } else {
  523. remote = local
  524. }
  525. Debugf("Pushing [%s] to [%s]\n", local, remote)
  526. // Try to get the image
  527. // FIXME: Handle lookup
  528. // FIXME: Also push the tags in case of ./docker push myrepo:mytag
  529. // img, err := srv.runtime.LookupImage(cmd.Arg(0))
  530. img, err := srv.runtime.graph.Get(local)
  531. if err != nil {
  532. Debugf("The push refers to a repository [%s] (len: %d)\n", local, len(srv.runtime.repositories.Repositories[local]))
  533. // If it fails, try to get the repository
  534. if localRepo, exists := srv.runtime.repositories.Repositories[local]; exists {
  535. if err := srv.runtime.graph.PushRepository(stdout, remote, localRepo, srv.runtime.authConfig); err != nil {
  536. return err
  537. }
  538. return nil
  539. }
  540. return err
  541. }
  542. err = srv.runtime.graph.PushImage(stdout, img, srv.runtime.authConfig)
  543. if err != nil {
  544. return err
  545. }
  546. return nil
  547. }
  548. */
  549. func CmdPull(args []string) error {
  550. cmd := Subcmd("pull", "NAME", "Pull an image or a repository from the registry")
  551. if err := cmd.Parse(args); err != nil {
  552. return nil
  553. }
  554. if cmd.NArg() != 1 {
  555. cmd.Usage()
  556. return nil
  557. }
  558. if err := callStream("POST", "/images/"+cmd.Arg(0)+"/pull", nil, false); err != nil {
  559. return err
  560. }
  561. return nil
  562. }
  563. func CmdImages(args []string) error {
  564. cmd := Subcmd("images", "[OPTIONS] [NAME]", "List images")
  565. quiet := cmd.Bool("q", false, "only show numeric IDs")
  566. all := cmd.Bool("a", false, "show all images")
  567. if err := cmd.Parse(args); err != nil {
  568. return nil
  569. }
  570. if cmd.NArg() > 1 {
  571. cmd.Usage()
  572. return nil
  573. }
  574. v := url.Values{}
  575. if cmd.NArg() == 1 {
  576. v.Set("filter", cmd.Arg(0))
  577. }
  578. if *quiet {
  579. v.Set("quiet", "1")
  580. }
  581. if *all {
  582. v.Set("all", "1")
  583. }
  584. body, err := call("GET", "/images?"+v.Encode())
  585. if err != nil {
  586. return err
  587. }
  588. var outs []ApiImages
  589. err = json.Unmarshal(body, &outs)
  590. if err != nil {
  591. return err
  592. }
  593. w := tabwriter.NewWriter(os.Stdout, 20, 1, 3, ' ', 0)
  594. if !*quiet {
  595. fmt.Fprintln(w, "REPOSITORY\tTAG\tID\tCREATED")
  596. }
  597. for _, out := range outs {
  598. if !*quiet {
  599. fmt.Fprintf(w, "%s\t%s\t%s\t%s\n", out.Repository, out.Tag, out.Id, out.Created)
  600. } else {
  601. fmt.Fprintln(w, out.Id)
  602. }
  603. }
  604. if !*quiet {
  605. w.Flush()
  606. }
  607. return nil
  608. }
  609. func CmdPs(args []string) error {
  610. cmd := Subcmd("ps", "[OPTIONS]", "List containers")
  611. quiet := cmd.Bool("q", false, "Only display numeric IDs")
  612. all := cmd.Bool("a", false, "Show all containers. Only running containers are shown by default.")
  613. noTrunc := cmd.Bool("notrunc", false, "Don't truncate output")
  614. nLatest := cmd.Bool("l", false, "Show only the latest created container, include non-running ones.")
  615. last := cmd.Int("n", -1, "Show n last created containers, include non-running ones.")
  616. if err := cmd.Parse(args); err != nil {
  617. return nil
  618. }
  619. v := url.Values{}
  620. if *last == -1 && *nLatest {
  621. *last = 1
  622. }
  623. if *quiet {
  624. v.Set("quiet", "1")
  625. }
  626. if *all {
  627. v.Set("all", "1")
  628. }
  629. if *noTrunc {
  630. v.Set("notrunc", "1")
  631. }
  632. if *last != -1 {
  633. v.Set("n", strconv.Itoa(*last))
  634. }
  635. body, err := call("GET", "/containers?"+v.Encode())
  636. if err != nil {
  637. return err
  638. }
  639. var outs []ApiContainers
  640. err = json.Unmarshal(body, &outs)
  641. if err != nil {
  642. return err
  643. }
  644. w := tabwriter.NewWriter(os.Stdout, 20, 1, 3, ' ', 0)
  645. if !*quiet {
  646. fmt.Fprintln(w, "ID\tIMAGE\tCOMMAND\tCREATED\tSTATUS")
  647. }
  648. for _, out := range outs {
  649. if !*quiet {
  650. fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\n", out.Id, out.Image, out.Command, out.Status, out.Created)
  651. } else {
  652. fmt.Fprintln(w, out.Id)
  653. }
  654. }
  655. if !*quiet {
  656. w.Flush()
  657. }
  658. return nil
  659. }
  660. func CmdCommit(args []string) error {
  661. cmd := Subcmd("commit", "[OPTIONS] CONTAINER [REPOSITORY [TAG]]", "Create a new image from a container's changes")
  662. flComment := cmd.String("m", "", "Commit message")
  663. if err := cmd.Parse(args); err != nil {
  664. return nil
  665. }
  666. name, repository, tag := cmd.Arg(0), cmd.Arg(1), cmd.Arg(2)
  667. if name == "" {
  668. cmd.Usage()
  669. return nil
  670. }
  671. v := url.Values{}
  672. v.Set("repo", repository)
  673. v.Set("tag", tag)
  674. v.Set("comment", *flComment)
  675. body, err := call("POST", "/containers/"+name+"/commit?"+v.Encode())
  676. if err != nil {
  677. return err
  678. }
  679. var out ApiCommit
  680. err = json.Unmarshal(body, &out)
  681. if err != nil {
  682. return err
  683. }
  684. fmt.Println(out.Id)
  685. return nil
  686. }
  687. func CmdExport(args []string) error {
  688. cmd := Subcmd("export", "CONTAINER", "Export the contents of a filesystem as a tar archive")
  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. if err := callStream("GET", "/containers/"+cmd.Arg(0)+"/export", nil, false); err != nil {
  697. return err
  698. }
  699. return nil
  700. }
  701. func CmdDiff(args []string) error {
  702. cmd := Subcmd("diff", "CONTAINER", "Inspect changes on a container's filesystem")
  703. if err := cmd.Parse(args); err != nil {
  704. return nil
  705. }
  706. if cmd.NArg() != 1 {
  707. cmd.Usage()
  708. return nil
  709. }
  710. body, err := call("GET", "/containers/"+cmd.Arg(0)+"/changes")
  711. if err != nil {
  712. return err
  713. }
  714. var changes []string
  715. err = json.Unmarshal(body, &changes)
  716. if err != nil {
  717. return err
  718. }
  719. for _, change := range changes {
  720. fmt.Println(change)
  721. }
  722. return nil
  723. }
  724. func CmdLogs(args []string) error {
  725. cmd := Subcmd("logs", "CONTAINER", "Fetch the logs of a container")
  726. if err := cmd.Parse(args); err != nil {
  727. return nil
  728. }
  729. if cmd.NArg() != 1 {
  730. cmd.Usage()
  731. return nil
  732. }
  733. body, err := call("GET", "/containers/"+cmd.Arg(0)+"/logs")
  734. if err != nil {
  735. return err
  736. }
  737. var out ApiLogs
  738. err = json.Unmarshal(body, &out)
  739. if err != nil {
  740. return err
  741. }
  742. fmt.Fprintln(os.Stdout, out.Stdout)
  743. fmt.Fprintln(os.Stderr, out.Stderr)
  744. return nil
  745. }
  746. func CmdAttach(args []string) error {
  747. cmd := Subcmd("attach", "CONTAINER", "Attach to a running container")
  748. if err := cmd.Parse(args); err != nil {
  749. return nil
  750. }
  751. if cmd.NArg() != 1 {
  752. cmd.Usage()
  753. return nil
  754. }
  755. body, err := call("GET", "/containers/"+cmd.Arg(0))
  756. if err != nil {
  757. return err
  758. }
  759. var container Container
  760. err = json.Unmarshal(body, &container)
  761. if err != nil {
  762. return err
  763. }
  764. if err := callStream("POST", "/containers/"+cmd.Arg(0)+"/attach", nil, container.Config.Tty); err != nil {
  765. return err
  766. }
  767. return nil
  768. }
  769. /*
  770. // Ports type - Used to parse multiple -p flags
  771. type ports []int
  772. func (p *ports) String() string {
  773. return fmt.Sprint(*p)
  774. }
  775. func (p *ports) Set(value string) error {
  776. port, err := strconv.Atoi(value)
  777. if err != nil {
  778. return fmt.Errorf("Invalid port: %v", value)
  779. }
  780. *p = append(*p, port)
  781. return nil
  782. }
  783. */
  784. // ListOpts type
  785. type ListOpts []string
  786. func (opts *ListOpts) String() string {
  787. return fmt.Sprint(*opts)
  788. }
  789. func (opts *ListOpts) Set(value string) error {
  790. *opts = append(*opts, value)
  791. return nil
  792. }
  793. // AttachOpts stores arguments to 'docker run -a', eg. which streams to attach to
  794. type AttachOpts map[string]bool
  795. func NewAttachOpts() AttachOpts {
  796. return make(AttachOpts)
  797. }
  798. func (opts AttachOpts) String() string {
  799. // Cast to underlying map type to avoid infinite recursion
  800. return fmt.Sprintf("%v", map[string]bool(opts))
  801. }
  802. func (opts AttachOpts) Set(val string) error {
  803. if val != "stdin" && val != "stdout" && val != "stderr" {
  804. return fmt.Errorf("Unsupported stream name: %s", val)
  805. }
  806. opts[val] = true
  807. return nil
  808. }
  809. func (opts AttachOpts) Get(val string) bool {
  810. if res, exists := opts[val]; exists {
  811. return res
  812. }
  813. return false
  814. }
  815. func CmdTag(args []string) error {
  816. cmd := Subcmd("tag", "[OPTIONS] IMAGE REPOSITORY [TAG]", "Tag an image into a repository")
  817. force := cmd.Bool("f", false, "Force")
  818. if err := cmd.Parse(args); err != nil {
  819. return nil
  820. }
  821. if cmd.NArg() != 2 && cmd.NArg() != 3 {
  822. cmd.Usage()
  823. return nil
  824. }
  825. v := url.Values{}
  826. v.Set("repo", cmd.Arg(1))
  827. if cmd.NArg() == 3 {
  828. v.Set("tag", cmd.Arg(2))
  829. }
  830. if *force {
  831. v.Set("force", "1")
  832. }
  833. if err := callStream("POST", "/images/"+cmd.Arg(0)+"/tag?"+v.Encode(), nil, false); err != nil {
  834. return err
  835. }
  836. return nil
  837. }
  838. func CmdRun(args []string) error {
  839. config, cmd, err := ParseRun(args)
  840. if err != nil {
  841. return err
  842. }
  843. if config.Image == "" {
  844. cmd.Usage()
  845. return nil
  846. }
  847. if len(config.Cmd) == 0 {
  848. cmd.Usage()
  849. return nil
  850. }
  851. if err := callStream("POST", "/containers", *config, config.Tty); err != nil {
  852. return err
  853. }
  854. return nil
  855. }
  856. func call(method, path string) ([]byte, error) {
  857. req, err := http.NewRequest(method, "http://0.0.0.0:4243"+path, nil)
  858. if err != nil {
  859. return nil, err
  860. }
  861. if method == "POST" {
  862. req.Header.Set("Content-Type", "plain/text")
  863. }
  864. resp, err := http.DefaultClient.Do(req)
  865. if err != nil {
  866. return nil, err
  867. }
  868. defer resp.Body.Close()
  869. body, err := ioutil.ReadAll(resp.Body)
  870. if err != nil {
  871. return nil, err
  872. }
  873. if resp.StatusCode != 200 {
  874. return nil, fmt.Errorf("error: %s", body)
  875. }
  876. return body, nil
  877. }
  878. func callStream(method, path string, data interface{}, setRawTerminal bool) error {
  879. var body io.Reader
  880. if data != nil {
  881. buf, err := json.Marshal(data)
  882. if err != nil {
  883. return err
  884. }
  885. body = bytes.NewBuffer(buf)
  886. }
  887. req, err := http.NewRequest(method, path, body)
  888. if err != nil {
  889. return err
  890. }
  891. if data != nil {
  892. req.Header.Set("Content-Type", "application/json")
  893. }
  894. dial, err := net.Dial("tcp", "0.0.0.0:4243")
  895. if err != nil {
  896. return err
  897. }
  898. clientconn := httputil.NewClientConn(dial, nil)
  899. clientconn.Do(req)
  900. defer clientconn.Close()
  901. rwc, _ := clientconn.Hijack()
  902. defer rwc.Close()
  903. if setRawTerminal && term.IsTerminal(int(os.Stdin.Fd())) && os.Getenv("NORAW") == "" {
  904. if oldState, err := SetRawTerminal(); err != nil {
  905. return err
  906. } else {
  907. defer RestoreTerminal(oldState)
  908. }
  909. }
  910. receiveStdout := Go(func() error {
  911. _, err := io.Copy(os.Stdout, rwc)
  912. return err
  913. })
  914. sendStdin := Go(func() error {
  915. _, err := io.Copy(rwc, os.Stdin)
  916. rwc.Close()
  917. return err
  918. })
  919. if err := <-receiveStdout; err != nil {
  920. return err
  921. }
  922. if !term.IsTerminal(int(os.Stdin.Fd())) {
  923. if err := <-sendStdin; err != nil {
  924. return err
  925. }
  926. }
  927. return nil
  928. }
  929. func Subcmd(name, signature, description string) *flag.FlagSet {
  930. flags := flag.NewFlagSet(name, flag.ContinueOnError)
  931. flags.Usage = func() {
  932. fmt.Printf("\nUsage: docker %s %s\n\n%s\n\n", name, signature, description)
  933. flags.PrintDefaults()
  934. }
  935. return flags
  936. }