commands.go 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418
  1. package docker
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "flag"
  6. "fmt"
  7. "github.com/dotcloud/docker/auth"
  8. "github.com/dotcloud/docker/term"
  9. "github.com/dotcloud/docker/utils"
  10. "io"
  11. "io/ioutil"
  12. "net"
  13. "net/http"
  14. "net/http/httputil"
  15. "net/url"
  16. "os"
  17. "os/signal"
  18. "path/filepath"
  19. "reflect"
  20. "strconv"
  21. "strings"
  22. "syscall"
  23. "text/tabwriter"
  24. "time"
  25. "unicode"
  26. )
  27. const VERSION = "0.3.3"
  28. var (
  29. GIT_COMMIT string
  30. )
  31. func (cli *DockerCli) getMethod(name string) (reflect.Method, bool) {
  32. methodName := "Cmd" + strings.ToUpper(name[:1]) + strings.ToLower(name[1:])
  33. return reflect.TypeOf(cli).MethodByName(methodName)
  34. }
  35. func ParseCommands(addr string, port int, args ...string) error {
  36. cli := NewDockerCli(addr, port)
  37. if len(args) > 0 {
  38. method, exists := cli.getMethod(args[0])
  39. if !exists {
  40. fmt.Println("Error: Command not found:", args[0])
  41. return cli.CmdHelp(args[1:]...)
  42. }
  43. ret := method.Func.CallSlice([]reflect.Value{
  44. reflect.ValueOf(cli),
  45. reflect.ValueOf(args[1:]),
  46. })[0].Interface()
  47. if ret == nil {
  48. return nil
  49. }
  50. return ret.(error)
  51. }
  52. return cli.CmdHelp(args...)
  53. }
  54. func (cli *DockerCli) CmdHelp(args ...string) error {
  55. if len(args) > 0 {
  56. method, exists := cli.getMethod(args[0])
  57. if !exists {
  58. fmt.Println("Error: Command not found:", args[0])
  59. } else {
  60. method.Func.CallSlice([]reflect.Value{
  61. reflect.ValueOf(cli),
  62. reflect.ValueOf([]string{"--help"}),
  63. })[0].Interface()
  64. return nil
  65. }
  66. }
  67. help := fmt.Sprintf("Usage: docker [OPTIONS] COMMAND [arg...]\n -H=\"%s:%d\": Host:port to bind/connect to\n\nA self-sufficient runtime for linux containers.\n\nCommands:\n", cli.host, cli.port)
  68. for cmd, description := range map[string]string{
  69. "attach": "Attach to a running container",
  70. "build": "Build a container from Dockerfile or via stdin",
  71. "commit": "Create a new image from a container's changes",
  72. "diff": "Inspect changes on a container's filesystem",
  73. "export": "Stream the contents of a container as a tar archive",
  74. "history": "Show the history of an image",
  75. "images": "List images",
  76. "import": "Create a new filesystem image from the contents of a tarball",
  77. "info": "Display system-wide information",
  78. "insert": "Insert a file in an image",
  79. "inspect": "Return low-level information on a container",
  80. "kill": "Kill a running container",
  81. "login": "Register or Login to the docker registry server",
  82. "logs": "Fetch the logs of a container",
  83. "port": "Lookup the public-facing port which is NAT-ed to PRIVATE_PORT",
  84. "ps": "List containers",
  85. "pull": "Pull an image or a repository from the docker registry server",
  86. "push": "Push an image or a repository to the docker registry server",
  87. "restart": "Restart a running container",
  88. "rm": "Remove a container",
  89. "rmi": "Remove an image",
  90. "run": "Run a command in a new container",
  91. "search": "Search for an image in the docker index",
  92. "start": "Start a stopped container",
  93. "stop": "Stop a running container",
  94. "tag": "Tag an image into a repository",
  95. "version": "Show the docker version information",
  96. "wait": "Block until a container stops, then print its exit code",
  97. } {
  98. help += fmt.Sprintf(" %-10.10s%s\n", cmd, description)
  99. }
  100. fmt.Println(help)
  101. return nil
  102. }
  103. func (cli *DockerCli) CmdInsert(args ...string) error {
  104. cmd := Subcmd("insert", "IMAGE URL PATH", "Insert a file from URL in the IMAGE at PATH")
  105. if err := cmd.Parse(args); err != nil {
  106. return nil
  107. }
  108. if cmd.NArg() != 3 {
  109. cmd.Usage()
  110. return nil
  111. }
  112. v := url.Values{}
  113. v.Set("url", cmd.Arg(1))
  114. v.Set("path", cmd.Arg(2))
  115. err := cli.stream("POST", "/images/"+cmd.Arg(0)+"/insert?"+v.Encode(), nil, os.Stdout)
  116. if err != nil {
  117. return err
  118. }
  119. return nil
  120. }
  121. func (cli *DockerCli) CmdBuild(args ...string) error {
  122. cmd := Subcmd("build", "-|Dockerfile", "Build an image from Dockerfile or via stdin")
  123. if err := cmd.Parse(args); err != nil {
  124. return nil
  125. }
  126. var (
  127. file io.ReadCloser
  128. err error
  129. )
  130. if cmd.NArg() == 0 {
  131. file, err = os.Open("Dockerfile")
  132. if err != nil {
  133. return err
  134. }
  135. } else if cmd.Arg(0) == "-" {
  136. file = os.Stdin
  137. } else {
  138. file, err = os.Open(cmd.Arg(0))
  139. if err != nil {
  140. return err
  141. }
  142. }
  143. if _, err := NewBuilderClient("0.0.0.0", 4243).Build(file); err != nil {
  144. return err
  145. }
  146. return nil
  147. }
  148. // 'docker login': login / register a user to registry service.
  149. func (cli *DockerCli) CmdLogin(args ...string) error {
  150. var readStringOnRawTerminal = func(stdin io.Reader, stdout io.Writer, echo bool) string {
  151. char := make([]byte, 1)
  152. buffer := make([]byte, 64)
  153. var i = 0
  154. for i < len(buffer) {
  155. n, err := stdin.Read(char)
  156. if n > 0 {
  157. if char[0] == '\r' || char[0] == '\n' {
  158. stdout.Write([]byte{'\r', '\n'})
  159. break
  160. } else if char[0] == 127 || char[0] == '\b' {
  161. if i > 0 {
  162. if echo {
  163. stdout.Write([]byte{'\b', ' ', '\b'})
  164. }
  165. i--
  166. }
  167. } else if !unicode.IsSpace(rune(char[0])) &&
  168. !unicode.IsControl(rune(char[0])) {
  169. if echo {
  170. stdout.Write(char)
  171. }
  172. buffer[i] = char[0]
  173. i++
  174. }
  175. }
  176. if err != nil {
  177. if err != io.EOF {
  178. fmt.Fprintf(stdout, "Read error: %v\r\n", err)
  179. }
  180. break
  181. }
  182. }
  183. return string(buffer[:i])
  184. }
  185. var readAndEchoString = func(stdin io.Reader, stdout io.Writer) string {
  186. return readStringOnRawTerminal(stdin, stdout, true)
  187. }
  188. var readString = func(stdin io.Reader, stdout io.Writer) string {
  189. return readStringOnRawTerminal(stdin, stdout, false)
  190. }
  191. oldState, err := term.SetRawTerminal()
  192. if err != nil {
  193. return err
  194. } else {
  195. defer term.RestoreTerminal(oldState)
  196. }
  197. cmd := Subcmd("login", "", "Register or Login to the docker registry server")
  198. if err := cmd.Parse(args); err != nil {
  199. return nil
  200. }
  201. body, _, err := cli.call("GET", "/auth", nil)
  202. if err != nil {
  203. return err
  204. }
  205. var out auth.AuthConfig
  206. err = json.Unmarshal(body, &out)
  207. if err != nil {
  208. return err
  209. }
  210. var username string
  211. var password string
  212. var email string
  213. fmt.Print("Username (", out.Username, "): ")
  214. username = readAndEchoString(os.Stdin, os.Stdout)
  215. if username == "" {
  216. username = out.Username
  217. }
  218. if username != out.Username {
  219. fmt.Print("Password: ")
  220. password = readString(os.Stdin, os.Stdout)
  221. if password == "" {
  222. return fmt.Errorf("Error : Password Required")
  223. }
  224. fmt.Print("Email (", out.Email, "): ")
  225. email = readAndEchoString(os.Stdin, os.Stdout)
  226. if email == "" {
  227. email = out.Email
  228. }
  229. } else {
  230. email = out.Email
  231. }
  232. out.Username = username
  233. out.Password = password
  234. out.Email = email
  235. body, _, err = cli.call("POST", "/auth", out)
  236. if err != nil {
  237. return err
  238. }
  239. var out2 ApiAuth
  240. err = json.Unmarshal(body, &out2)
  241. if err != nil {
  242. return err
  243. }
  244. if out2.Status != "" {
  245. term.RestoreTerminal(oldState)
  246. fmt.Print(out2.Status)
  247. }
  248. return nil
  249. }
  250. // 'docker wait': block until a container stops
  251. func (cli *DockerCli) CmdWait(args ...string) error {
  252. cmd := Subcmd("wait", "CONTAINER [CONTAINER...]", "Block until a container stops, then print its exit code.")
  253. if err := cmd.Parse(args); err != nil {
  254. return nil
  255. }
  256. if cmd.NArg() < 1 {
  257. cmd.Usage()
  258. return nil
  259. }
  260. for _, name := range cmd.Args() {
  261. body, _, err := cli.call("POST", "/containers/"+name+"/wait", nil)
  262. if err != nil {
  263. fmt.Printf("%s", err)
  264. } else {
  265. var out ApiWait
  266. err = json.Unmarshal(body, &out)
  267. if err != nil {
  268. return err
  269. }
  270. fmt.Println(out.StatusCode)
  271. }
  272. }
  273. return nil
  274. }
  275. // 'docker version': show version information
  276. func (cli *DockerCli) CmdVersion(args ...string) error {
  277. cmd := Subcmd("version", "", "Show the docker version information.")
  278. fmt.Println(len(args))
  279. if err := cmd.Parse(args); err != nil {
  280. return nil
  281. }
  282. fmt.Println(cmd.NArg())
  283. if cmd.NArg() > 0 {
  284. cmd.Usage()
  285. return nil
  286. }
  287. body, _, err := cli.call("GET", "/version", nil)
  288. if err != nil {
  289. return err
  290. }
  291. var out ApiVersion
  292. err = json.Unmarshal(body, &out)
  293. if err != nil {
  294. utils.Debugf("Error unmarshal: body: %s, err: %s\n", body, err)
  295. return err
  296. }
  297. fmt.Println("Version:", out.Version)
  298. fmt.Println("Git Commit:", out.GitCommit)
  299. if !out.MemoryLimit {
  300. fmt.Println("WARNING: No memory limit support")
  301. }
  302. if !out.SwapLimit {
  303. fmt.Println("WARNING: No swap limit support")
  304. }
  305. return nil
  306. }
  307. // 'docker info': display system-wide information.
  308. func (cli *DockerCli) CmdInfo(args ...string) error {
  309. cmd := Subcmd("info", "", "Display system-wide information")
  310. if err := cmd.Parse(args); err != nil {
  311. return nil
  312. }
  313. if cmd.NArg() > 0 {
  314. cmd.Usage()
  315. return nil
  316. }
  317. body, _, err := cli.call("GET", "/info", nil)
  318. if err != nil {
  319. return err
  320. }
  321. var out ApiInfo
  322. err = json.Unmarshal(body, &out)
  323. if err != nil {
  324. return err
  325. }
  326. fmt.Printf("containers: %d\nversion: %s\nimages: %d\nGo version: %s\n", out.Containers, out.Version, out.Images, out.GoVersion)
  327. if out.Debug {
  328. fmt.Println("debug mode enabled")
  329. fmt.Printf("fds: %d\ngoroutines: %d\n", out.NFd, out.NGoroutines)
  330. }
  331. return nil
  332. }
  333. func (cli *DockerCli) CmdStop(args ...string) error {
  334. cmd := Subcmd("stop", "[OPTIONS] CONTAINER [CONTAINER...]", "Stop a running container")
  335. nSeconds := cmd.Int("t", 10, "wait t seconds before killing the container")
  336. if err := cmd.Parse(args); err != nil {
  337. return nil
  338. }
  339. if cmd.NArg() < 1 {
  340. cmd.Usage()
  341. return nil
  342. }
  343. v := url.Values{}
  344. v.Set("t", strconv.Itoa(*nSeconds))
  345. for _, name := range cmd.Args() {
  346. _, _, err := cli.call("POST", "/containers/"+name+"/stop?"+v.Encode(), nil)
  347. if err != nil {
  348. fmt.Printf("%s", err)
  349. } else {
  350. fmt.Println(name)
  351. }
  352. }
  353. return nil
  354. }
  355. func (cli *DockerCli) CmdRestart(args ...string) error {
  356. cmd := Subcmd("restart", "[OPTIONS] CONTAINER [CONTAINER...]", "Restart a running container")
  357. nSeconds := cmd.Int("t", 10, "wait t seconds before killing the container")
  358. if err := cmd.Parse(args); err != nil {
  359. return nil
  360. }
  361. if cmd.NArg() < 1 {
  362. cmd.Usage()
  363. return nil
  364. }
  365. v := url.Values{}
  366. v.Set("t", strconv.Itoa(*nSeconds))
  367. for _, name := range cmd.Args() {
  368. _, _, err := cli.call("POST", "/containers/"+name+"/restart?"+v.Encode(), nil)
  369. if err != nil {
  370. fmt.Printf("%s", err)
  371. } else {
  372. fmt.Println(name)
  373. }
  374. }
  375. return nil
  376. }
  377. func (cli *DockerCli) CmdStart(args ...string) error {
  378. cmd := Subcmd("start", "CONTAINER [CONTAINER...]", "Restart a stopped container")
  379. if err := cmd.Parse(args); err != nil {
  380. return nil
  381. }
  382. if cmd.NArg() < 1 {
  383. cmd.Usage()
  384. return nil
  385. }
  386. for _, name := range args {
  387. _, _, err := cli.call("POST", "/containers/"+name+"/start", nil)
  388. if err != nil {
  389. fmt.Printf("%s", err)
  390. } else {
  391. fmt.Println(name)
  392. }
  393. }
  394. return nil
  395. }
  396. func (cli *DockerCli) CmdInspect(args ...string) error {
  397. cmd := Subcmd("inspect", "CONTAINER|IMAGE", "Return low-level information on a container/image")
  398. if err := cmd.Parse(args); err != nil {
  399. return nil
  400. }
  401. if cmd.NArg() != 1 {
  402. cmd.Usage()
  403. return nil
  404. }
  405. obj, _, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/json", nil)
  406. if err != nil {
  407. obj, _, err = cli.call("GET", "/images/"+cmd.Arg(0)+"/json", nil)
  408. if err != nil {
  409. return err
  410. }
  411. }
  412. indented := new(bytes.Buffer)
  413. if err = json.Indent(indented, obj, "", " "); err != nil {
  414. return err
  415. }
  416. if _, err := io.Copy(os.Stdout, indented); err != nil {
  417. return err
  418. }
  419. return nil
  420. }
  421. func (cli *DockerCli) CmdPort(args ...string) error {
  422. cmd := Subcmd("port", "CONTAINER PRIVATE_PORT", "Lookup the public-facing port which is NAT-ed to PRIVATE_PORT")
  423. if err := cmd.Parse(args); err != nil {
  424. return nil
  425. }
  426. if cmd.NArg() != 2 {
  427. cmd.Usage()
  428. return nil
  429. }
  430. body, _, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/json", nil)
  431. if err != nil {
  432. return err
  433. }
  434. var out Container
  435. err = json.Unmarshal(body, &out)
  436. if err != nil {
  437. return err
  438. }
  439. if frontend, exists := out.NetworkSettings.PortMapping[cmd.Arg(1)]; exists {
  440. fmt.Println(frontend)
  441. } else {
  442. return fmt.Errorf("error: No private port '%s' allocated on %s", cmd.Arg(1), cmd.Arg(0))
  443. }
  444. return nil
  445. }
  446. // 'docker rmi IMAGE' removes all images with the name IMAGE
  447. func (cli *DockerCli) CmdRmi(args ...string) error {
  448. cmd := Subcmd("rmi", "IMAGE [IMAGE...]", "Remove an image")
  449. if err := cmd.Parse(args); err != nil {
  450. return nil
  451. }
  452. if cmd.NArg() < 1 {
  453. cmd.Usage()
  454. return nil
  455. }
  456. for _, name := range cmd.Args() {
  457. _, _, err := cli.call("DELETE", "/images/"+name, nil)
  458. if err != nil {
  459. fmt.Printf("%s", err)
  460. } else {
  461. fmt.Println(name)
  462. }
  463. }
  464. return nil
  465. }
  466. func (cli *DockerCli) CmdHistory(args ...string) error {
  467. cmd := Subcmd("history", "IMAGE", "Show the history of an image")
  468. if err := cmd.Parse(args); err != nil {
  469. return nil
  470. }
  471. if cmd.NArg() != 1 {
  472. cmd.Usage()
  473. return nil
  474. }
  475. body, _, err := cli.call("GET", "/images/"+cmd.Arg(0)+"/history", nil)
  476. if err != nil {
  477. return err
  478. }
  479. var outs []ApiHistory
  480. err = json.Unmarshal(body, &outs)
  481. if err != nil {
  482. return err
  483. }
  484. w := tabwriter.NewWriter(os.Stdout, 20, 1, 3, ' ', 0)
  485. fmt.Fprintln(w, "ID\tCREATED\tCREATED BY")
  486. for _, out := range outs {
  487. fmt.Fprintf(w, "%s\t%s ago\t%s\n", out.Id, utils.HumanDuration(time.Now().Sub(time.Unix(out.Created, 0))), out.CreatedBy)
  488. }
  489. w.Flush()
  490. return nil
  491. }
  492. func (cli *DockerCli) CmdRm(args ...string) error {
  493. cmd := Subcmd("rm", "[OPTIONS] CONTAINER [CONTAINER...]", "Remove a container")
  494. v := cmd.Bool("v", false, "Remove the volumes associated to the container")
  495. if err := cmd.Parse(args); err != nil {
  496. return nil
  497. }
  498. if cmd.NArg() < 1 {
  499. cmd.Usage()
  500. return nil
  501. }
  502. val := url.Values{}
  503. if *v {
  504. val.Set("v", "1")
  505. }
  506. for _, name := range cmd.Args() {
  507. _, _, err := cli.call("DELETE", "/containers/"+name+"?"+val.Encode(), nil)
  508. if err != nil {
  509. fmt.Printf("%s", err)
  510. } else {
  511. fmt.Println(name)
  512. }
  513. }
  514. return nil
  515. }
  516. // 'docker kill NAME' kills a running container
  517. func (cli *DockerCli) CmdKill(args ...string) error {
  518. cmd := Subcmd("kill", "CONTAINER [CONTAINER...]", "Kill a running container")
  519. if err := cmd.Parse(args); err != nil {
  520. return nil
  521. }
  522. if cmd.NArg() < 1 {
  523. cmd.Usage()
  524. return nil
  525. }
  526. for _, name := range args {
  527. _, _, err := cli.call("POST", "/containers/"+name+"/kill", nil)
  528. if err != nil {
  529. fmt.Printf("%s", err)
  530. } else {
  531. fmt.Println(name)
  532. }
  533. }
  534. return nil
  535. }
  536. func (cli *DockerCli) CmdImport(args ...string) error {
  537. cmd := Subcmd("import", "URL|- [REPOSITORY [TAG]]", "Create a new filesystem image from the contents of a tarball")
  538. if err := cmd.Parse(args); err != nil {
  539. return nil
  540. }
  541. if cmd.NArg() < 1 {
  542. cmd.Usage()
  543. return nil
  544. }
  545. src, repository, tag := cmd.Arg(0), cmd.Arg(1), cmd.Arg(2)
  546. v := url.Values{}
  547. v.Set("repo", repository)
  548. v.Set("tag", tag)
  549. v.Set("fromSrc", src)
  550. err := cli.stream("POST", "/images/create?"+v.Encode(), os.Stdin, os.Stdout)
  551. if err != nil {
  552. return err
  553. }
  554. return nil
  555. }
  556. func (cli *DockerCli) CmdPush(args ...string) error {
  557. cmd := Subcmd("push", "[OPTION] NAME", "Push an image or a repository to the registry")
  558. registry := cmd.String("registry", "", "Registry host to push the image to")
  559. if err := cmd.Parse(args); err != nil {
  560. return nil
  561. }
  562. name := cmd.Arg(0)
  563. if name == "" {
  564. cmd.Usage()
  565. return nil
  566. }
  567. username, err := cli.checkIfLogged(*registry == "", "push")
  568. if err != nil {
  569. return err
  570. }
  571. if len(strings.SplitN(name, "/", 2)) == 1 {
  572. return fmt.Errorf("Impossible to push a \"root\" repository. Please rename your repository in <user>/<repo> (ex: %s/%s)", username, name)
  573. }
  574. v := url.Values{}
  575. v.Set("registry", *registry)
  576. if err := cli.stream("POST", "/images/"+name+"/push?"+v.Encode(), nil, os.Stdout); err != nil {
  577. return err
  578. }
  579. return nil
  580. }
  581. func (cli *DockerCli) CmdPull(args ...string) error {
  582. cmd := Subcmd("pull", "NAME", "Pull an image or a repository from the registry")
  583. tag := cmd.String("t", "", "Download tagged image in repository")
  584. registry := cmd.String("registry", "", "Registry to download from. Necessary if image is pulled by ID")
  585. if err := cmd.Parse(args); err != nil {
  586. return nil
  587. }
  588. if cmd.NArg() != 1 {
  589. cmd.Usage()
  590. return nil
  591. }
  592. remote := cmd.Arg(0)
  593. if strings.Contains(remote, ":") {
  594. remoteParts := strings.Split(remote, ":")
  595. tag = &remoteParts[1]
  596. remote = remoteParts[0]
  597. }
  598. if strings.Contains(remote, "/") {
  599. if _, err := cli.checkIfLogged(true, "pull"); err != nil {
  600. return err
  601. }
  602. }
  603. v := url.Values{}
  604. v.Set("fromImage", remote)
  605. v.Set("tag", *tag)
  606. v.Set("registry", *registry)
  607. if err := cli.stream("POST", "/images/create?"+v.Encode(), nil, os.Stdout); err != nil {
  608. return err
  609. }
  610. return nil
  611. }
  612. func (cli *DockerCli) CmdImages(args ...string) error {
  613. cmd := Subcmd("images", "[OPTIONS] [NAME]", "List images")
  614. quiet := cmd.Bool("q", false, "only show numeric IDs")
  615. all := cmd.Bool("a", false, "show all images")
  616. noTrunc := cmd.Bool("notrunc", false, "Don't truncate output")
  617. flViz := cmd.Bool("viz", false, "output graph in graphviz format")
  618. if err := cmd.Parse(args); err != nil {
  619. return nil
  620. }
  621. if cmd.NArg() > 1 {
  622. cmd.Usage()
  623. return nil
  624. }
  625. if *flViz {
  626. body, _, err := cli.call("GET", "/images/viz", false)
  627. if err != nil {
  628. return err
  629. }
  630. fmt.Printf("%s", body)
  631. } else {
  632. v := url.Values{}
  633. if cmd.NArg() == 1 {
  634. v.Set("filter", cmd.Arg(0))
  635. }
  636. if *all {
  637. v.Set("all", "1")
  638. }
  639. body, _, err := cli.call("GET", "/images/json?"+v.Encode(), nil)
  640. if err != nil {
  641. return err
  642. }
  643. var outs []ApiImages
  644. err = json.Unmarshal(body, &outs)
  645. if err != nil {
  646. return err
  647. }
  648. w := tabwriter.NewWriter(os.Stdout, 20, 1, 3, ' ', 0)
  649. if !*quiet {
  650. fmt.Fprintln(w, "REPOSITORY\tTAG\tID\tCREATED")
  651. }
  652. for _, out := range outs {
  653. if out.Repository == "" {
  654. out.Repository = "<none>"
  655. }
  656. if out.Tag == "" {
  657. out.Tag = "<none>"
  658. }
  659. if !*quiet {
  660. fmt.Fprintf(w, "%s\t%s\t", out.Repository, out.Tag)
  661. if *noTrunc {
  662. fmt.Fprintf(w, "%s\t", out.Id)
  663. } else {
  664. fmt.Fprintf(w, "%s\t", utils.TruncateId(out.Id))
  665. }
  666. fmt.Fprintf(w, "%s ago\n", utils.HumanDuration(time.Now().Sub(time.Unix(out.Created, 0))))
  667. } else {
  668. if *noTrunc {
  669. fmt.Fprintln(w, out.Id)
  670. } else {
  671. fmt.Fprintln(w, utils.TruncateId(out.Id))
  672. }
  673. }
  674. }
  675. if !*quiet {
  676. w.Flush()
  677. }
  678. }
  679. return nil
  680. }
  681. func (cli *DockerCli) CmdPs(args ...string) error {
  682. cmd := Subcmd("ps", "[OPTIONS]", "List containers")
  683. quiet := cmd.Bool("q", false, "Only display numeric IDs")
  684. all := cmd.Bool("a", false, "Show all containers. Only running containers are shown by default.")
  685. noTrunc := cmd.Bool("notrunc", false, "Don't truncate output")
  686. nLatest := cmd.Bool("l", false, "Show only the latest created container, include non-running ones.")
  687. since := cmd.String("sinceId", "", "Show only containers created since Id, include non-running ones.")
  688. before := cmd.String("beforeId", "", "Show only container created before Id, include non-running ones.")
  689. last := cmd.Int("n", -1, "Show n last created containers, include non-running ones.")
  690. if err := cmd.Parse(args); err != nil {
  691. return nil
  692. }
  693. v := url.Values{}
  694. if *last == -1 && *nLatest {
  695. *last = 1
  696. }
  697. if *all {
  698. v.Set("all", "1")
  699. }
  700. if *last != -1 {
  701. v.Set("limit", strconv.Itoa(*last))
  702. }
  703. if *since != "" {
  704. v.Set("since", *since)
  705. }
  706. if *before != "" {
  707. v.Set("before", *before)
  708. }
  709. body, _, err := cli.call("GET", "/containers/ps?"+v.Encode(), nil)
  710. if err != nil {
  711. return err
  712. }
  713. var outs []ApiContainers
  714. err = json.Unmarshal(body, &outs)
  715. if err != nil {
  716. return err
  717. }
  718. w := tabwriter.NewWriter(os.Stdout, 20, 1, 3, ' ', 0)
  719. if !*quiet {
  720. fmt.Fprintln(w, "ID\tIMAGE\tCOMMAND\tCREATED\tSTATUS\tPORTS")
  721. }
  722. for _, out := range outs {
  723. if !*quiet {
  724. if *noTrunc {
  725. fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s ago\t%s\n", out.Id, out.Image, out.Command, out.Status, utils.HumanDuration(time.Now().Sub(time.Unix(out.Created, 0))), out.Ports)
  726. } else {
  727. fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s ago\t%s\n", utils.TruncateId(out.Id), out.Image, utils.Trunc(out.Command, 20), out.Status, utils.HumanDuration(time.Now().Sub(time.Unix(out.Created, 0))), out.Ports)
  728. }
  729. } else {
  730. if *noTrunc {
  731. fmt.Fprintln(w, out.Id)
  732. } else {
  733. fmt.Fprintln(w, utils.TruncateId(out.Id))
  734. }
  735. }
  736. }
  737. if !*quiet {
  738. w.Flush()
  739. }
  740. return nil
  741. }
  742. func (cli *DockerCli) CmdCommit(args ...string) error {
  743. cmd := Subcmd("commit", "[OPTIONS] CONTAINER [REPOSITORY [TAG]]", "Create a new image from a container's changes")
  744. flComment := cmd.String("m", "", "Commit message")
  745. flAuthor := cmd.String("author", "", "Author (eg. \"John Hannibal Smith <hannibal@a-team.com>\"")
  746. flConfig := cmd.String("run", "", "Config automatically applied when the image is run. "+`(ex: {"Cmd": ["cat", "/world"], "PortSpecs": ["22"]}')`)
  747. if err := cmd.Parse(args); err != nil {
  748. return nil
  749. }
  750. name, repository, tag := cmd.Arg(0), cmd.Arg(1), cmd.Arg(2)
  751. if name == "" {
  752. cmd.Usage()
  753. return nil
  754. }
  755. v := url.Values{}
  756. v.Set("container", name)
  757. v.Set("repo", repository)
  758. v.Set("tag", tag)
  759. v.Set("comment", *flComment)
  760. v.Set("author", *flAuthor)
  761. var config *Config
  762. if *flConfig != "" {
  763. config = &Config{}
  764. if err := json.Unmarshal([]byte(*flConfig), config); err != nil {
  765. return err
  766. }
  767. }
  768. body, _, err := cli.call("POST", "/commit?"+v.Encode(), config)
  769. if err != nil {
  770. return err
  771. }
  772. apiId := &ApiId{}
  773. err = json.Unmarshal(body, apiId)
  774. if err != nil {
  775. return err
  776. }
  777. fmt.Println(apiId.Id)
  778. return nil
  779. }
  780. func (cli *DockerCli) CmdExport(args ...string) error {
  781. cmd := Subcmd("export", "CONTAINER", "Export the contents of a filesystem as a tar archive")
  782. if err := cmd.Parse(args); err != nil {
  783. return nil
  784. }
  785. if cmd.NArg() != 1 {
  786. cmd.Usage()
  787. return nil
  788. }
  789. if err := cli.stream("GET", "/containers/"+cmd.Arg(0)+"/export", nil, os.Stdout); err != nil {
  790. return err
  791. }
  792. return nil
  793. }
  794. func (cli *DockerCli) CmdDiff(args ...string) error {
  795. cmd := Subcmd("diff", "CONTAINER", "Inspect changes on a container's filesystem")
  796. if err := cmd.Parse(args); err != nil {
  797. return nil
  798. }
  799. if cmd.NArg() != 1 {
  800. cmd.Usage()
  801. return nil
  802. }
  803. body, _, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/changes", nil)
  804. if err != nil {
  805. return err
  806. }
  807. changes := []Change{}
  808. err = json.Unmarshal(body, &changes)
  809. if err != nil {
  810. return err
  811. }
  812. for _, change := range changes {
  813. fmt.Println(change.String())
  814. }
  815. return nil
  816. }
  817. func (cli *DockerCli) CmdLogs(args ...string) error {
  818. cmd := Subcmd("logs", "CONTAINER", "Fetch the logs of a container")
  819. if err := cmd.Parse(args); err != nil {
  820. return nil
  821. }
  822. if cmd.NArg() != 1 {
  823. cmd.Usage()
  824. return nil
  825. }
  826. v := url.Values{}
  827. v.Set("logs", "1")
  828. v.Set("stdout", "1")
  829. v.Set("stderr", "1")
  830. if err := cli.hijack("POST", "/containers/"+cmd.Arg(0)+"/attach?"+v.Encode(), false, nil, os.Stdout); err != nil {
  831. return err
  832. }
  833. return nil
  834. }
  835. func (cli *DockerCli) CmdAttach(args ...string) error {
  836. cmd := Subcmd("attach", "CONTAINER", "Attach to a running container")
  837. if err := cmd.Parse(args); err != nil {
  838. return nil
  839. }
  840. if cmd.NArg() != 1 {
  841. cmd.Usage()
  842. return nil
  843. }
  844. body, _, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/json", nil)
  845. if err != nil {
  846. return err
  847. }
  848. container := &Container{}
  849. err = json.Unmarshal(body, container)
  850. if err != nil {
  851. return err
  852. }
  853. connections := 1
  854. if !container.Config.Tty {
  855. connections += 1
  856. }
  857. c := make(chan error, 2)
  858. cli.monitorTtySize(cmd.Arg(0))
  859. if !container.Config.Tty {
  860. go func() {
  861. c <- cli.hijack("POST", "/containers/"+cmd.Arg(0)+"/attach?stream=1&stderr=1", false, nil, os.Stderr)
  862. }()
  863. }
  864. v := url.Values{}
  865. v.Set("stream", "1")
  866. v.Set("stdin", "1")
  867. v.Set("stdout", "1")
  868. if container.Config.Tty {
  869. v.Set("stderr", "1")
  870. }
  871. go func() {
  872. c <- cli.hijack("POST", "/containers/"+cmd.Arg(0)+"/attach?"+v.Encode(), container.Config.Tty, os.Stdin, os.Stdout)
  873. }()
  874. for connections > 0 {
  875. err := <-c
  876. if err != nil {
  877. return err
  878. }
  879. connections -= 1
  880. }
  881. return nil
  882. }
  883. func (cli *DockerCli) CmdSearch(args ...string) error {
  884. cmd := Subcmd("search", "NAME", "Search the docker index for images")
  885. if err := cmd.Parse(args); err != nil {
  886. return nil
  887. }
  888. if cmd.NArg() != 1 {
  889. cmd.Usage()
  890. return nil
  891. }
  892. v := url.Values{}
  893. v.Set("term", cmd.Arg(0))
  894. body, _, err := cli.call("GET", "/images/search?"+v.Encode(), nil)
  895. if err != nil {
  896. return err
  897. }
  898. outs := []ApiSearch{}
  899. err = json.Unmarshal(body, &outs)
  900. if err != nil {
  901. return err
  902. }
  903. fmt.Printf("Found %d results matching your query (\"%s\")\n", len(outs), cmd.Arg(0))
  904. w := tabwriter.NewWriter(os.Stdout, 20, 1, 3, ' ', 0)
  905. fmt.Fprintf(w, "NAME\tDESCRIPTION\n")
  906. for _, out := range outs {
  907. fmt.Fprintf(w, "%s\t%s\n", out.Name, out.Description)
  908. }
  909. w.Flush()
  910. return nil
  911. }
  912. // Ports type - Used to parse multiple -p flags
  913. type ports []int
  914. // ListOpts type
  915. type ListOpts []string
  916. func (opts *ListOpts) String() string {
  917. return fmt.Sprint(*opts)
  918. }
  919. func (opts *ListOpts) Set(value string) error {
  920. *opts = append(*opts, value)
  921. return nil
  922. }
  923. // AttachOpts stores arguments to 'docker run -a', eg. which streams to attach to
  924. type AttachOpts map[string]bool
  925. func NewAttachOpts() AttachOpts {
  926. return make(AttachOpts)
  927. }
  928. func (opts AttachOpts) String() string {
  929. // Cast to underlying map type to avoid infinite recursion
  930. return fmt.Sprintf("%v", map[string]bool(opts))
  931. }
  932. func (opts AttachOpts) Set(val string) error {
  933. if val != "stdin" && val != "stdout" && val != "stderr" {
  934. return fmt.Errorf("Unsupported stream name: %s", val)
  935. }
  936. opts[val] = true
  937. return nil
  938. }
  939. func (opts AttachOpts) Get(val string) bool {
  940. if res, exists := opts[val]; exists {
  941. return res
  942. }
  943. return false
  944. }
  945. // PathOpts stores a unique set of absolute paths
  946. type PathOpts map[string]struct{}
  947. func NewPathOpts() PathOpts {
  948. return make(PathOpts)
  949. }
  950. func (opts PathOpts) String() string {
  951. return fmt.Sprintf("%v", map[string]struct{}(opts))
  952. }
  953. func (opts PathOpts) Set(val string) error {
  954. if !filepath.IsAbs(val) {
  955. return fmt.Errorf("%s is not an absolute path", val)
  956. }
  957. opts[filepath.Clean(val)] = struct{}{}
  958. return nil
  959. }
  960. func (cli *DockerCli) CmdTag(args ...string) error {
  961. cmd := Subcmd("tag", "[OPTIONS] IMAGE REPOSITORY [TAG]", "Tag an image into a repository")
  962. force := cmd.Bool("f", false, "Force")
  963. if err := cmd.Parse(args); err != nil {
  964. return nil
  965. }
  966. if cmd.NArg() != 2 && cmd.NArg() != 3 {
  967. cmd.Usage()
  968. return nil
  969. }
  970. v := url.Values{}
  971. v.Set("repo", cmd.Arg(1))
  972. if cmd.NArg() == 3 {
  973. v.Set("tag", cmd.Arg(2))
  974. }
  975. if *force {
  976. v.Set("force", "1")
  977. }
  978. if _, _, err := cli.call("POST", "/images/"+cmd.Arg(0)+"/tag?"+v.Encode(), nil); err != nil {
  979. return err
  980. }
  981. return nil
  982. }
  983. func (cli *DockerCli) CmdRun(args ...string) error {
  984. config, cmd, err := ParseRun(args, nil)
  985. if err != nil {
  986. return err
  987. }
  988. if config.Image == "" {
  989. cmd.Usage()
  990. return nil
  991. }
  992. //create the container
  993. body, statusCode, err := cli.call("POST", "/containers/create", config)
  994. //if image not found try to pull it
  995. if statusCode == 404 {
  996. v := url.Values{}
  997. v.Set("fromImage", config.Image)
  998. err = cli.stream("POST", "/images/create?"+v.Encode(), nil, os.Stderr)
  999. if err != nil {
  1000. return err
  1001. }
  1002. body, _, err = cli.call("POST", "/containers/create", config)
  1003. if err != nil {
  1004. return err
  1005. }
  1006. }
  1007. if err != nil {
  1008. return err
  1009. }
  1010. out := &ApiRun{}
  1011. err = json.Unmarshal(body, out)
  1012. if err != nil {
  1013. return err
  1014. }
  1015. for _, warning := range out.Warnings {
  1016. fmt.Fprintln(os.Stderr, "WARNING: ", warning)
  1017. }
  1018. connections := 0
  1019. if config.AttachStdin || config.AttachStdout {
  1020. connections += 1
  1021. }
  1022. if !config.Tty && config.AttachStderr {
  1023. connections += 1
  1024. }
  1025. //start the container
  1026. _, _, err = cli.call("POST", "/containers/"+out.Id+"/start", nil)
  1027. if err != nil {
  1028. return err
  1029. }
  1030. if connections > 0 {
  1031. c := make(chan error, connections)
  1032. cli.monitorTtySize(out.Id)
  1033. if !config.Tty && config.AttachStderr {
  1034. go func() {
  1035. c <- cli.hijack("POST", "/containers/"+out.Id+"/attach?logs=1&stream=1&stderr=1", config.Tty, nil, os.Stderr)
  1036. }()
  1037. }
  1038. v := url.Values{}
  1039. v.Set("logs", "1")
  1040. v.Set("stream", "1")
  1041. if config.AttachStdin {
  1042. v.Set("stdin", "1")
  1043. }
  1044. if config.AttachStdout {
  1045. v.Set("stdout", "1")
  1046. }
  1047. if config.Tty && config.AttachStderr {
  1048. v.Set("stderr", "1")
  1049. }
  1050. go func() {
  1051. c <- cli.hijack("POST", "/containers/"+out.Id+"/attach?"+v.Encode(), config.Tty, os.Stdin, os.Stdout)
  1052. }()
  1053. for connections > 0 {
  1054. err := <-c
  1055. if err != nil {
  1056. return err
  1057. }
  1058. connections -= 1
  1059. }
  1060. }
  1061. if !config.AttachStdout && !config.AttachStderr {
  1062. fmt.Println(out.Id)
  1063. }
  1064. return nil
  1065. }
  1066. func (cli *DockerCli) checkIfLogged(condition bool, action string) (string, error) {
  1067. body, _, err := cli.call("GET", "/auth", nil)
  1068. if err != nil {
  1069. return "", err
  1070. }
  1071. var out auth.AuthConfig
  1072. err = json.Unmarshal(body, &out)
  1073. if err != nil {
  1074. return "", err
  1075. }
  1076. // If condition AND the login failed
  1077. if condition && out.Username == "" {
  1078. if err := cli.CmdLogin(""); err != nil {
  1079. return "", err
  1080. }
  1081. body, _, err = cli.call("GET", "/auth", nil)
  1082. if err != nil {
  1083. return "", err
  1084. }
  1085. err = json.Unmarshal(body, &out)
  1086. if err != nil {
  1087. return "", err
  1088. }
  1089. if out.Username == "" {
  1090. return "", fmt.Errorf("Please login prior to %s. ('docker login')", action)
  1091. }
  1092. }
  1093. return out.Username, nil
  1094. }
  1095. func (cli *DockerCli) call(method, path string, data interface{}) ([]byte, int, error) {
  1096. var params io.Reader
  1097. if data != nil {
  1098. buf, err := json.Marshal(data)
  1099. if err != nil {
  1100. return nil, -1, err
  1101. }
  1102. params = bytes.NewBuffer(buf)
  1103. }
  1104. req, err := http.NewRequest(method, fmt.Sprintf("http://%s:%d/v%g%s", cli.host, cli.port, API_VERSION, path), params)
  1105. if err != nil {
  1106. return nil, -1, err
  1107. }
  1108. req.Header.Set("User-Agent", "Docker-Client/"+VERSION)
  1109. if data != nil {
  1110. req.Header.Set("Content-Type", "application/json")
  1111. } else if method == "POST" {
  1112. req.Header.Set("Content-Type", "plain/text")
  1113. }
  1114. resp, err := http.DefaultClient.Do(req)
  1115. if err != nil {
  1116. if strings.Contains(err.Error(), "connection refused") {
  1117. return nil, -1, fmt.Errorf("Can't connect to docker daemon. Is 'docker -d' running on this host?")
  1118. }
  1119. return nil, -1, err
  1120. }
  1121. defer resp.Body.Close()
  1122. body, err := ioutil.ReadAll(resp.Body)
  1123. if err != nil {
  1124. return nil, -1, err
  1125. }
  1126. if resp.StatusCode < 200 || resp.StatusCode >= 400 {
  1127. return nil, resp.StatusCode, fmt.Errorf("error: %s", body)
  1128. }
  1129. return body, resp.StatusCode, nil
  1130. }
  1131. func (cli *DockerCli) stream(method, path string, in io.Reader, out io.Writer) error {
  1132. if (method == "POST" || method == "PUT") && in == nil {
  1133. in = bytes.NewReader([]byte{})
  1134. }
  1135. req, err := http.NewRequest(method, fmt.Sprintf("http://%s:%d/v%g%s", cli.host, cli.port, API_VERSION, path), in)
  1136. if err != nil {
  1137. return err
  1138. }
  1139. req.Header.Set("User-Agent", "Docker-Client/"+VERSION)
  1140. if method == "POST" {
  1141. req.Header.Set("Content-Type", "plain/text")
  1142. }
  1143. resp, err := http.DefaultClient.Do(req)
  1144. if err != nil {
  1145. if strings.Contains(err.Error(), "connection refused") {
  1146. return fmt.Errorf("Can't connect to docker daemon. Is 'docker -d' running on this host?")
  1147. }
  1148. return err
  1149. }
  1150. defer resp.Body.Close()
  1151. if resp.StatusCode < 200 || resp.StatusCode >= 400 {
  1152. body, err := ioutil.ReadAll(resp.Body)
  1153. if err != nil {
  1154. return err
  1155. }
  1156. return fmt.Errorf("error: %s", body)
  1157. }
  1158. if resp.Header.Get("Content-Type") == "application/json" {
  1159. type Message struct {
  1160. Status string `json:"status,omitempty"`
  1161. Progress string `json:"progress,omitempty"`
  1162. }
  1163. dec := json.NewDecoder(resp.Body)
  1164. for {
  1165. var m Message
  1166. if err := dec.Decode(&m); err == io.EOF {
  1167. break
  1168. } else if err != nil {
  1169. return err
  1170. }
  1171. if m.Progress != "" {
  1172. fmt.Fprintf(out, "Downloading %s\r", m.Progress)
  1173. } else {
  1174. fmt.Fprintf(out, "%s\n", m.Status)
  1175. }
  1176. }
  1177. } else {
  1178. if _, err := io.Copy(out, resp.Body); err != nil {
  1179. return err
  1180. }
  1181. }
  1182. return nil
  1183. }
  1184. func (cli *DockerCli) hijack(method, path string, setRawTerminal bool, in *os.File, out io.Writer) error {
  1185. req, err := http.NewRequest(method, fmt.Sprintf("/v%g%s", API_VERSION, path), nil)
  1186. if err != nil {
  1187. return err
  1188. }
  1189. req.Header.Set("Content-Type", "plain/text")
  1190. dial, err := net.Dial("tcp", fmt.Sprintf("%s:%d", cli.host, cli.port))
  1191. if err != nil {
  1192. return err
  1193. }
  1194. clientconn := httputil.NewClientConn(dial, nil)
  1195. clientconn.Do(req)
  1196. defer clientconn.Close()
  1197. rwc, br := clientconn.Hijack()
  1198. defer rwc.Close()
  1199. receiveStdout := utils.Go(func() error {
  1200. _, err := io.Copy(out, br)
  1201. return err
  1202. })
  1203. if in != nil && setRawTerminal && term.IsTerminal(int(in.Fd())) && os.Getenv("NORAW") == "" {
  1204. if oldState, err := term.SetRawTerminal(); err != nil {
  1205. return err
  1206. } else {
  1207. defer term.RestoreTerminal(oldState)
  1208. }
  1209. }
  1210. sendStdin := utils.Go(func() error {
  1211. _, err := io.Copy(rwc, in)
  1212. if err := rwc.(*net.TCPConn).CloseWrite(); err != nil {
  1213. fmt.Fprintf(os.Stderr, "Couldn't send EOF: %s\n", err)
  1214. }
  1215. return err
  1216. })
  1217. if err := <-receiveStdout; err != nil {
  1218. return err
  1219. }
  1220. if !term.IsTerminal(int(os.Stdin.Fd())) {
  1221. if err := <-sendStdin; err != nil {
  1222. return err
  1223. }
  1224. }
  1225. return nil
  1226. }
  1227. func (cli *DockerCli) resizeTty(id string) {
  1228. ws, err := term.GetWinsize(os.Stdin.Fd())
  1229. if err != nil {
  1230. utils.Debugf("Error getting size: %s", err)
  1231. }
  1232. v := url.Values{}
  1233. v.Set("h", strconv.Itoa(int(ws.Height)))
  1234. v.Set("w", strconv.Itoa(int(ws.Width)))
  1235. if _, _, err := cli.call("POST", "/containers/"+id+"/resize?"+v.Encode(), nil); err != nil {
  1236. utils.Debugf("Error resize: %s", err)
  1237. }
  1238. }
  1239. func (cli *DockerCli) monitorTtySize(id string) {
  1240. cli.resizeTty(id)
  1241. c := make(chan os.Signal, 1)
  1242. signal.Notify(c, syscall.SIGWINCH)
  1243. go func() {
  1244. for sig := range c {
  1245. if sig == syscall.SIGWINCH {
  1246. cli.resizeTty(id)
  1247. }
  1248. }
  1249. }()
  1250. }
  1251. func Subcmd(name, signature, description string) *flag.FlagSet {
  1252. flags := flag.NewFlagSet(name, flag.ContinueOnError)
  1253. flags.Usage = func() {
  1254. fmt.Printf("\nUsage: docker %s %s\n\n%s\n\n", name, signature, description)
  1255. flags.PrintDefaults()
  1256. }
  1257. return flags
  1258. }
  1259. func NewDockerCli(addr string, port int) *DockerCli {
  1260. return &DockerCli{addr, port}
  1261. }
  1262. type DockerCli struct {
  1263. host string
  1264. port int
  1265. }