commands.go 30 KB

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