commands.go 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322
  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, description := range map[string]string{
  52. "attach": "Attach to a running container",
  53. "build": "Build a container from Dockerfile or 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, description)
  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)+"/insert?"+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", "-|Dockerfile", "Build an image from Dockerfile or via stdin")
  106. if err := cmd.Parse(args); err != nil {
  107. return nil
  108. }
  109. var (
  110. file io.ReadCloser
  111. err error
  112. )
  113. if cmd.NArg() == 0 {
  114. file, err = os.Open("Dockerfile")
  115. if err != nil {
  116. return err
  117. }
  118. } else if cmd.Arg(0) == "-" {
  119. file = os.Stdin
  120. } else {
  121. file, err = os.Open(cmd.Arg(0))
  122. if err != nil {
  123. return err
  124. }
  125. }
  126. if _, err := NewBuilderClient("0.0.0.0", 4243).Build(file); err != nil {
  127. return err
  128. }
  129. return nil
  130. }
  131. // 'docker login': login / register a user to registry service.
  132. func (cli *DockerCli) CmdLogin(args ...string) error {
  133. var readStringOnRawTerminal = func(stdin io.Reader, stdout io.Writer, echo bool) string {
  134. char := make([]byte, 1)
  135. buffer := make([]byte, 64)
  136. var i = 0
  137. for i < len(buffer) {
  138. n, err := stdin.Read(char)
  139. if n > 0 {
  140. if char[0] == '\r' || char[0] == '\n' {
  141. stdout.Write([]byte{'\r', '\n'})
  142. break
  143. } else if char[0] == 127 || char[0] == '\b' {
  144. if i > 0 {
  145. if echo {
  146. stdout.Write([]byte{'\b', ' ', '\b'})
  147. }
  148. i--
  149. }
  150. } else if !unicode.IsSpace(rune(char[0])) &&
  151. !unicode.IsControl(rune(char[0])) {
  152. if echo {
  153. stdout.Write(char)
  154. }
  155. buffer[i] = char[0]
  156. i++
  157. }
  158. }
  159. if err != nil {
  160. if err != io.EOF {
  161. fmt.Fprintf(stdout, "Read error: %v\r\n", err)
  162. }
  163. break
  164. }
  165. }
  166. return string(buffer[:i])
  167. }
  168. var readAndEchoString = func(stdin io.Reader, stdout io.Writer) string {
  169. return readStringOnRawTerminal(stdin, stdout, true)
  170. }
  171. var readString = func(stdin io.Reader, stdout io.Writer) string {
  172. return readStringOnRawTerminal(stdin, stdout, false)
  173. }
  174. oldState, err := term.SetRawTerminal()
  175. if err != nil {
  176. return err
  177. } else {
  178. defer term.RestoreTerminal(oldState)
  179. }
  180. cmd := Subcmd("login", "", "Register or Login to the docker registry server")
  181. if err := cmd.Parse(args); err != nil {
  182. return nil
  183. }
  184. body, _, err := cli.call("GET", "/auth", nil)
  185. if err != nil {
  186. return err
  187. }
  188. var out auth.AuthConfig
  189. err = json.Unmarshal(body, &out)
  190. if err != nil {
  191. return err
  192. }
  193. var username string
  194. var password string
  195. var email string
  196. fmt.Print("Username (", out.Username, "): ")
  197. username = readAndEchoString(os.Stdin, os.Stdout)
  198. if username == "" {
  199. username = out.Username
  200. }
  201. if username != out.Username {
  202. fmt.Print("Password: ")
  203. password = readString(os.Stdin, os.Stdout)
  204. if password == "" {
  205. return fmt.Errorf("Error : Password Required")
  206. }
  207. fmt.Print("Email (", out.Email, "): ")
  208. email = readAndEchoString(os.Stdin, os.Stdout)
  209. if email == "" {
  210. email = out.Email
  211. }
  212. } else {
  213. email = out.Email
  214. }
  215. out.Username = username
  216. out.Password = password
  217. out.Email = email
  218. body, _, err = cli.call("POST", "/auth", out)
  219. if err != nil {
  220. return err
  221. }
  222. var out2 ApiAuth
  223. err = json.Unmarshal(body, &out2)
  224. if err != nil {
  225. return err
  226. }
  227. if out2.Status != "" {
  228. term.RestoreTerminal(oldState)
  229. fmt.Print(out2.Status)
  230. }
  231. return nil
  232. }
  233. // 'docker wait': block until a container stops
  234. func (cli *DockerCli) CmdWait(args ...string) error {
  235. cmd := Subcmd("wait", "CONTAINER [CONTAINER...]", "Block until a container stops, then print its exit code.")
  236. if err := cmd.Parse(args); err != nil {
  237. return nil
  238. }
  239. if cmd.NArg() < 1 {
  240. cmd.Usage()
  241. return nil
  242. }
  243. for _, name := range cmd.Args() {
  244. body, _, err := cli.call("POST", "/containers/"+name+"/wait", nil)
  245. if err != nil {
  246. fmt.Printf("%s", err)
  247. } else {
  248. var out ApiWait
  249. err = json.Unmarshal(body, &out)
  250. if err != nil {
  251. return err
  252. }
  253. fmt.Println(out.StatusCode)
  254. }
  255. }
  256. return nil
  257. }
  258. // 'docker version': show version information
  259. func (cli *DockerCli) CmdVersion(args ...string) error {
  260. cmd := Subcmd("version", "", "Show the docker version information.")
  261. fmt.Println(len(args))
  262. if err := cmd.Parse(args); err != nil {
  263. return nil
  264. }
  265. fmt.Println(cmd.NArg())
  266. if cmd.NArg() > 0 {
  267. cmd.Usage()
  268. return nil
  269. }
  270. body, _, err := cli.call("GET", "/version", nil)
  271. if err != nil {
  272. return err
  273. }
  274. var out ApiVersion
  275. err = json.Unmarshal(body, &out)
  276. if err != nil {
  277. utils.Debugf("Error unmarshal: body: %s, err: %s\n", body, err)
  278. return err
  279. }
  280. fmt.Println("Version:", out.Version)
  281. fmt.Println("Git Commit:", out.GitCommit)
  282. if !out.MemoryLimit {
  283. fmt.Println("WARNING: No memory limit support")
  284. }
  285. if !out.SwapLimit {
  286. fmt.Println("WARNING: No swap limit support")
  287. }
  288. return nil
  289. }
  290. // 'docker info': display system-wide information.
  291. func (cli *DockerCli) CmdInfo(args ...string) error {
  292. cmd := Subcmd("info", "", "Display system-wide information")
  293. if err := cmd.Parse(args); err != nil {
  294. return nil
  295. }
  296. if cmd.NArg() > 0 {
  297. cmd.Usage()
  298. return nil
  299. }
  300. body, _, err := cli.call("GET", "/info", nil)
  301. if err != nil {
  302. return err
  303. }
  304. var out ApiInfo
  305. err = json.Unmarshal(body, &out)
  306. if err != nil {
  307. return err
  308. }
  309. fmt.Printf("containers: %d\nversion: %s\nimages: %d\nGo version: %s\n", out.Containers, out.Version, out.Images, out.GoVersion)
  310. if out.Debug {
  311. fmt.Println("debug mode enabled")
  312. fmt.Printf("fds: %d\ngoroutines: %d\n", out.NFd, out.NGoroutines)
  313. }
  314. return nil
  315. }
  316. func (cli *DockerCli) CmdStop(args ...string) error {
  317. cmd := Subcmd("stop", "[OPTIONS] CONTAINER [CONTAINER...]", "Stop a running container")
  318. nSeconds := cmd.Int("t", 10, "wait t seconds before killing the container")
  319. if err := cmd.Parse(args); err != nil {
  320. return nil
  321. }
  322. if cmd.NArg() < 1 {
  323. cmd.Usage()
  324. return nil
  325. }
  326. v := url.Values{}
  327. v.Set("t", strconv.Itoa(*nSeconds))
  328. for _, name := range cmd.Args() {
  329. _, _, err := cli.call("POST", "/containers/"+name+"/stop?"+v.Encode(), nil)
  330. if err != nil {
  331. fmt.Printf("%s", err)
  332. } else {
  333. fmt.Println(name)
  334. }
  335. }
  336. return nil
  337. }
  338. func (cli *DockerCli) CmdRestart(args ...string) error {
  339. cmd := Subcmd("restart", "[OPTIONS] CONTAINER [CONTAINER...]", "Restart a running container")
  340. nSeconds := cmd.Int("t", 10, "wait t seconds before killing the container")
  341. if err := cmd.Parse(args); err != nil {
  342. return nil
  343. }
  344. if cmd.NArg() < 1 {
  345. cmd.Usage()
  346. return nil
  347. }
  348. v := url.Values{}
  349. v.Set("t", strconv.Itoa(*nSeconds))
  350. for _, name := range cmd.Args() {
  351. _, _, err := cli.call("POST", "/containers/"+name+"/restart?"+v.Encode(), nil)
  352. if err != nil {
  353. fmt.Printf("%s", err)
  354. } else {
  355. fmt.Println(name)
  356. }
  357. }
  358. return nil
  359. }
  360. func (cli *DockerCli) CmdStart(args ...string) error {
  361. cmd := Subcmd("start", "CONTAINER [CONTAINER...]", "Restart a stopped container")
  362. if err := cmd.Parse(args); err != nil {
  363. return nil
  364. }
  365. if cmd.NArg() < 1 {
  366. cmd.Usage()
  367. return nil
  368. }
  369. for _, name := range args {
  370. _, _, err := cli.call("POST", "/containers/"+name+"/start", nil)
  371. if err != nil {
  372. fmt.Printf("%s", err)
  373. } else {
  374. fmt.Println(name)
  375. }
  376. }
  377. return nil
  378. }
  379. func (cli *DockerCli) CmdInspect(args ...string) error {
  380. cmd := Subcmd("inspect", "CONTAINER|IMAGE", "Return low-level information on a container/image")
  381. if err := cmd.Parse(args); err != nil {
  382. return nil
  383. }
  384. if cmd.NArg() != 1 {
  385. cmd.Usage()
  386. return nil
  387. }
  388. obj, _, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/json", nil)
  389. if err != nil {
  390. obj, _, err = cli.call("GET", "/images/"+cmd.Arg(0)+"/json", nil)
  391. if err != nil {
  392. return err
  393. }
  394. }
  395. indented := new(bytes.Buffer)
  396. if err = json.Indent(indented, obj, "", " "); err != nil {
  397. return err
  398. }
  399. if _, err := io.Copy(os.Stdout, indented); err != nil {
  400. return err
  401. }
  402. return nil
  403. }
  404. func (cli *DockerCli) CmdPort(args ...string) error {
  405. cmd := Subcmd("port", "CONTAINER PRIVATE_PORT", "Lookup the public-facing port which is NAT-ed to PRIVATE_PORT")
  406. if err := cmd.Parse(args); err != nil {
  407. return nil
  408. }
  409. if cmd.NArg() != 2 {
  410. cmd.Usage()
  411. return nil
  412. }
  413. body, _, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/json", nil)
  414. if err != nil {
  415. return err
  416. }
  417. var out Container
  418. err = json.Unmarshal(body, &out)
  419. if err != nil {
  420. return err
  421. }
  422. if frontend, exists := out.NetworkSettings.PortMapping[cmd.Arg(1)]; exists {
  423. fmt.Println(frontend)
  424. } else {
  425. return fmt.Errorf("error: No private port '%s' allocated on %s", cmd.Arg(1), cmd.Arg(0))
  426. }
  427. return nil
  428. }
  429. // 'docker rmi IMAGE' removes all images with the name IMAGE
  430. func (cli *DockerCli) CmdRmi(args ...string) error {
  431. cmd := Subcmd("rmi", "IMAGE [IMAGE...]", "Remove an image")
  432. if err := cmd.Parse(args); err != nil {
  433. return nil
  434. }
  435. if cmd.NArg() < 1 {
  436. cmd.Usage()
  437. return nil
  438. }
  439. for _, name := range cmd.Args() {
  440. _, _, err := cli.call("DELETE", "/images/"+name, nil)
  441. if err != nil {
  442. fmt.Printf("%s", err)
  443. } else {
  444. fmt.Println(name)
  445. }
  446. }
  447. return nil
  448. }
  449. func (cli *DockerCli) CmdHistory(args ...string) error {
  450. cmd := Subcmd("history", "IMAGE", "Show the history of an image")
  451. if err := cmd.Parse(args); err != nil {
  452. return nil
  453. }
  454. if cmd.NArg() != 1 {
  455. cmd.Usage()
  456. return nil
  457. }
  458. body, _, err := cli.call("GET", "/images/"+cmd.Arg(0)+"/history", nil)
  459. if err != nil {
  460. return err
  461. }
  462. var outs []ApiHistory
  463. err = json.Unmarshal(body, &outs)
  464. if err != nil {
  465. return err
  466. }
  467. w := tabwriter.NewWriter(os.Stdout, 20, 1, 3, ' ', 0)
  468. fmt.Fprintln(w, "ID\tCREATED\tCREATED BY")
  469. for _, out := range outs {
  470. fmt.Fprintf(w, "%s\t%s ago\t%s\n", out.Id, utils.HumanDuration(time.Now().Sub(time.Unix(out.Created, 0))), out.CreatedBy)
  471. }
  472. w.Flush()
  473. return nil
  474. }
  475. func (cli *DockerCli) CmdRm(args ...string) error {
  476. cmd := Subcmd("rm", "[OPTIONS] CONTAINER [CONTAINER...]", "Remove a container")
  477. v := cmd.Bool("v", false, "Remove the volumes associated to the container")
  478. if err := cmd.Parse(args); err != nil {
  479. return nil
  480. }
  481. if cmd.NArg() < 1 {
  482. cmd.Usage()
  483. return nil
  484. }
  485. val := url.Values{}
  486. if *v {
  487. val.Set("v", "1")
  488. }
  489. for _, name := range cmd.Args() {
  490. _, _, err := cli.call("DELETE", "/containers/"+name+"?"+val.Encode(), nil)
  491. if err != nil {
  492. fmt.Printf("%s", err)
  493. } else {
  494. fmt.Println(name)
  495. }
  496. }
  497. return nil
  498. }
  499. // 'docker kill NAME' kills a running container
  500. func (cli *DockerCli) CmdKill(args ...string) error {
  501. cmd := Subcmd("kill", "CONTAINER [CONTAINER...]", "Kill a running container")
  502. if err := cmd.Parse(args); err != nil {
  503. return nil
  504. }
  505. if cmd.NArg() < 1 {
  506. cmd.Usage()
  507. return nil
  508. }
  509. for _, name := range args {
  510. _, _, err := cli.call("POST", "/containers/"+name+"/kill", nil)
  511. if err != nil {
  512. fmt.Printf("%s", err)
  513. } else {
  514. fmt.Println(name)
  515. }
  516. }
  517. return nil
  518. }
  519. func (cli *DockerCli) CmdImport(args ...string) error {
  520. cmd := Subcmd("import", "URL|- [REPOSITORY [TAG]]", "Create a new filesystem image from the contents of a tarball")
  521. if err := cmd.Parse(args); err != nil {
  522. return nil
  523. }
  524. if cmd.NArg() < 1 {
  525. cmd.Usage()
  526. return nil
  527. }
  528. src, repository, tag := cmd.Arg(0), cmd.Arg(1), cmd.Arg(2)
  529. v := url.Values{}
  530. v.Set("repo", repository)
  531. v.Set("tag", tag)
  532. v.Set("fromSrc", src)
  533. err := cli.stream("POST", "/images/create?"+v.Encode(), os.Stdin, os.Stdout)
  534. if err != nil {
  535. return err
  536. }
  537. return nil
  538. }
  539. func (cli *DockerCli) CmdPush(args ...string) error {
  540. cmd := Subcmd("push", "[OPTION] NAME", "Push an image or a repository to the registry")
  541. registry := cmd.String("registry", "", "Registry host to push the image to")
  542. if err := cmd.Parse(args); err != nil {
  543. return nil
  544. }
  545. name := cmd.Arg(0)
  546. if name == "" {
  547. cmd.Usage()
  548. return nil
  549. }
  550. body, _, err := cli.call("GET", "/auth", nil)
  551. if err != nil {
  552. return err
  553. }
  554. var out auth.AuthConfig
  555. err = json.Unmarshal(body, &out)
  556. if err != nil {
  557. return err
  558. }
  559. // If the login failed AND we're using the index, abort
  560. if *registry == "" && out.Username == "" {
  561. if err := cli.CmdLogin(args...); err != nil {
  562. return err
  563. }
  564. body, _, err = cli.call("GET", "/auth", nil)
  565. if err != nil {
  566. return err
  567. }
  568. err = json.Unmarshal(body, &out)
  569. if err != nil {
  570. return err
  571. }
  572. if out.Username == "" {
  573. return fmt.Errorf("Please login prior to push. ('docker login')")
  574. }
  575. }
  576. if len(strings.SplitN(name, "/", 2)) == 1 {
  577. return fmt.Errorf("Impossible to push a \"root\" repository. Please rename your repository in <user>/<repo> (ex: %s/%s)", out.Username, name)
  578. }
  579. v := url.Values{}
  580. v.Set("registry", *registry)
  581. if err := cli.stream("POST", "/images/"+name+"/push?"+v.Encode(), nil, os.Stdout); err != nil {
  582. return err
  583. }
  584. return nil
  585. }
  586. func (cli *DockerCli) CmdPull(args ...string) error {
  587. cmd := Subcmd("pull", "NAME", "Pull an image or a repository from the registry")
  588. tag := cmd.String("t", "", "Download tagged image in repository")
  589. registry := cmd.String("registry", "", "Registry to download from. Necessary if image is pulled by ID")
  590. if err := cmd.Parse(args); err != nil {
  591. return nil
  592. }
  593. if cmd.NArg() != 1 {
  594. cmd.Usage()
  595. return nil
  596. }
  597. remote := cmd.Arg(0)
  598. if strings.Contains(remote, ":") {
  599. remoteParts := strings.Split(remote, ":")
  600. tag = &remoteParts[1]
  601. remote = remoteParts[0]
  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); 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. v := url.Values{}
  854. v.Set("stream", "1")
  855. v.Set("stdout", "1")
  856. v.Set("stderr", "1")
  857. v.Set("stdin", "1")
  858. if err := cli.hijack("POST", "/containers/"+cmd.Arg(0)+"/attach?"+v.Encode(), container.Config.Tty); err != nil {
  859. return err
  860. }
  861. return nil
  862. }
  863. func (cli *DockerCli) CmdSearch(args ...string) error {
  864. cmd := Subcmd("search", "NAME", "Search the docker index for images")
  865. if err := cmd.Parse(args); err != nil {
  866. return nil
  867. }
  868. if cmd.NArg() != 1 {
  869. cmd.Usage()
  870. return nil
  871. }
  872. v := url.Values{}
  873. v.Set("term", cmd.Arg(0))
  874. body, _, err := cli.call("GET", "/images/search?"+v.Encode(), nil)
  875. if err != nil {
  876. return err
  877. }
  878. outs := []ApiSearch{}
  879. err = json.Unmarshal(body, &outs)
  880. if err != nil {
  881. return err
  882. }
  883. fmt.Printf("Found %d results matching your query (\"%s\")\n", len(outs), cmd.Arg(0))
  884. w := tabwriter.NewWriter(os.Stdout, 20, 1, 3, ' ', 0)
  885. fmt.Fprintf(w, "NAME\tDESCRIPTION\n")
  886. for _, out := range outs {
  887. fmt.Fprintf(w, "%s\t%s\n", out.Name, out.Description)
  888. }
  889. w.Flush()
  890. return nil
  891. }
  892. // Ports type - Used to parse multiple -p flags
  893. type ports []int
  894. // ListOpts type
  895. type ListOpts []string
  896. func (opts *ListOpts) String() string {
  897. return fmt.Sprint(*opts)
  898. }
  899. func (opts *ListOpts) Set(value string) error {
  900. *opts = append(*opts, value)
  901. return nil
  902. }
  903. // AttachOpts stores arguments to 'docker run -a', eg. which streams to attach to
  904. type AttachOpts map[string]bool
  905. func NewAttachOpts() AttachOpts {
  906. return make(AttachOpts)
  907. }
  908. func (opts AttachOpts) String() string {
  909. // Cast to underlying map type to avoid infinite recursion
  910. return fmt.Sprintf("%v", map[string]bool(opts))
  911. }
  912. func (opts AttachOpts) Set(val string) error {
  913. if val != "stdin" && val != "stdout" && val != "stderr" {
  914. return fmt.Errorf("Unsupported stream name: %s", val)
  915. }
  916. opts[val] = true
  917. return nil
  918. }
  919. func (opts AttachOpts) Get(val string) bool {
  920. if res, exists := opts[val]; exists {
  921. return res
  922. }
  923. return false
  924. }
  925. // PathOpts stores a unique set of absolute paths
  926. type PathOpts map[string]struct{}
  927. func NewPathOpts() PathOpts {
  928. return make(PathOpts)
  929. }
  930. func (opts PathOpts) String() string {
  931. return fmt.Sprintf("%v", map[string]struct{}(opts))
  932. }
  933. func (opts PathOpts) Set(val string) error {
  934. if !filepath.IsAbs(val) {
  935. return fmt.Errorf("%s is not an absolute path", val)
  936. }
  937. opts[filepath.Clean(val)] = struct{}{}
  938. return nil
  939. }
  940. func (cli *DockerCli) CmdTag(args ...string) error {
  941. cmd := Subcmd("tag", "[OPTIONS] IMAGE REPOSITORY [TAG]", "Tag an image into a repository")
  942. force := cmd.Bool("f", false, "Force")
  943. if err := cmd.Parse(args); err != nil {
  944. return nil
  945. }
  946. if cmd.NArg() != 2 && cmd.NArg() != 3 {
  947. cmd.Usage()
  948. return nil
  949. }
  950. v := url.Values{}
  951. v.Set("repo", cmd.Arg(1))
  952. if cmd.NArg() == 3 {
  953. v.Set("tag", cmd.Arg(2))
  954. }
  955. if *force {
  956. v.Set("force", "1")
  957. }
  958. if _, _, err := cli.call("POST", "/images/"+cmd.Arg(0)+"/tag?"+v.Encode(), nil); err != nil {
  959. return err
  960. }
  961. return nil
  962. }
  963. func (cli *DockerCli) CmdRun(args ...string) error {
  964. config, cmd, err := ParseRun(args, nil)
  965. if err != nil {
  966. return err
  967. }
  968. if config.Image == "" {
  969. cmd.Usage()
  970. return nil
  971. }
  972. //create the container
  973. body, statusCode, err := cli.call("POST", "/containers/create", config)
  974. //if image not found try to pull it
  975. if statusCode == 404 {
  976. v := url.Values{}
  977. v.Set("fromImage", config.Image)
  978. err = cli.stream("POST", "/images/create?"+v.Encode(), nil, os.Stderr)
  979. if err != nil {
  980. return err
  981. }
  982. body, _, err = cli.call("POST", "/containers/create", config)
  983. if err != nil {
  984. return err
  985. }
  986. }
  987. if err != nil {
  988. return err
  989. }
  990. out := &ApiRun{}
  991. err = json.Unmarshal(body, out)
  992. if err != nil {
  993. return err
  994. }
  995. for _, warning := range out.Warnings {
  996. fmt.Fprintln(os.Stderr, "WARNING: ", warning)
  997. }
  998. v := url.Values{}
  999. v.Set("logs", "1")
  1000. v.Set("stream", "1")
  1001. if config.AttachStdin {
  1002. v.Set("stdin", "1")
  1003. }
  1004. if config.AttachStdout {
  1005. v.Set("stdout", "1")
  1006. }
  1007. if config.AttachStderr {
  1008. v.Set("stderr", "1")
  1009. }
  1010. //start the container
  1011. _, _, err = cli.call("POST", "/containers/"+out.Id+"/start", nil)
  1012. if err != nil {
  1013. return err
  1014. }
  1015. if config.AttachStdin || config.AttachStdout || config.AttachStderr {
  1016. if err := cli.hijack("POST", "/containers/"+out.Id+"/attach?"+v.Encode(), config.Tty); err != nil {
  1017. return err
  1018. }
  1019. }
  1020. if !config.AttachStdout && !config.AttachStderr {
  1021. fmt.Println(out.Id)
  1022. }
  1023. return nil
  1024. }
  1025. func (cli *DockerCli) call(method, path string, data interface{}) ([]byte, int, error) {
  1026. var params io.Reader
  1027. if data != nil {
  1028. buf, err := json.Marshal(data)
  1029. if err != nil {
  1030. return nil, -1, err
  1031. }
  1032. params = bytes.NewBuffer(buf)
  1033. }
  1034. req, err := http.NewRequest(method, fmt.Sprintf("http://%s:%d", cli.host, cli.port)+path, params)
  1035. if err != nil {
  1036. return nil, -1, err
  1037. }
  1038. req.Header.Set("User-Agent", "Docker-Client/"+VERSION)
  1039. if data != nil {
  1040. req.Header.Set("Content-Type", "application/json")
  1041. } else if method == "POST" {
  1042. req.Header.Set("Content-Type", "plain/text")
  1043. }
  1044. resp, err := http.DefaultClient.Do(req)
  1045. if err != nil {
  1046. if strings.Contains(err.Error(), "connection refused") {
  1047. return nil, -1, fmt.Errorf("Can't connect to docker daemon. Is 'docker -d' running on this host?")
  1048. }
  1049. return nil, -1, err
  1050. }
  1051. defer resp.Body.Close()
  1052. body, err := ioutil.ReadAll(resp.Body)
  1053. if err != nil {
  1054. return nil, -1, err
  1055. }
  1056. if resp.StatusCode < 200 || resp.StatusCode >= 400 {
  1057. return nil, resp.StatusCode, fmt.Errorf("error: %s", body)
  1058. }
  1059. return body, resp.StatusCode, nil
  1060. }
  1061. func (cli *DockerCli) stream(method, path string, in io.Reader, out io.Writer) error {
  1062. if (method == "POST" || method == "PUT") && in == nil {
  1063. in = bytes.NewReader([]byte{})
  1064. }
  1065. req, err := http.NewRequest(method, fmt.Sprintf("http://%s:%d%s", cli.host, cli.port, path), in)
  1066. if err != nil {
  1067. return err
  1068. }
  1069. req.Header.Set("User-Agent", "Docker-Client/"+VERSION)
  1070. if method == "POST" {
  1071. req.Header.Set("Content-Type", "plain/text")
  1072. }
  1073. resp, err := http.DefaultClient.Do(req)
  1074. if err != nil {
  1075. if strings.Contains(err.Error(), "connection refused") {
  1076. return fmt.Errorf("Can't connect to docker daemon. Is 'docker -d' running on this host?")
  1077. }
  1078. return err
  1079. }
  1080. defer resp.Body.Close()
  1081. if resp.StatusCode < 200 || resp.StatusCode >= 400 {
  1082. body, err := ioutil.ReadAll(resp.Body)
  1083. if err != nil {
  1084. return err
  1085. }
  1086. return fmt.Errorf("error: %s", body)
  1087. }
  1088. if resp.Header.Get("Content-Type") == "application/json" {
  1089. type Message struct {
  1090. Status string `json:"status,omitempty"`
  1091. Progress string `json:"progress,omitempty"`
  1092. }
  1093. dec := json.NewDecoder(resp.Body)
  1094. for {
  1095. var m Message
  1096. if err := dec.Decode(&m); err == io.EOF {
  1097. break
  1098. } else if err != nil {
  1099. return err
  1100. }
  1101. if m.Status != "" {
  1102. fmt.Fprintf(out, "%s\n", m.Status)
  1103. } else if m.Progress != "" {
  1104. fmt.Fprintf(out, "Downloading... %s\r", m.Progress)
  1105. }
  1106. }
  1107. fmt.Fprintf(out, "\n")
  1108. } else {
  1109. if _, err := io.Copy(out, resp.Body); err != nil {
  1110. return err
  1111. }
  1112. }
  1113. return nil
  1114. }
  1115. func (cli *DockerCli) hijack(method, path string, setRawTerminal bool) error {
  1116. req, err := http.NewRequest(method, path, nil)
  1117. if err != nil {
  1118. return err
  1119. }
  1120. req.Header.Set("Content-Type", "plain/text")
  1121. dial, err := net.Dial("tcp", fmt.Sprintf("%s:%d", cli.host, cli.port))
  1122. if err != nil {
  1123. return err
  1124. }
  1125. clientconn := httputil.NewClientConn(dial, nil)
  1126. clientconn.Do(req)
  1127. defer clientconn.Close()
  1128. rwc, br := clientconn.Hijack()
  1129. defer rwc.Close()
  1130. receiveStdout := utils.Go(func() error {
  1131. _, err := io.Copy(os.Stdout, br)
  1132. return err
  1133. })
  1134. if setRawTerminal && term.IsTerminal(int(os.Stdin.Fd())) && os.Getenv("NORAW") == "" {
  1135. if oldState, err := term.SetRawTerminal(); err != nil {
  1136. return err
  1137. } else {
  1138. defer term.RestoreTerminal(oldState)
  1139. }
  1140. }
  1141. sendStdin := utils.Go(func() error {
  1142. _, err := io.Copy(rwc, os.Stdin)
  1143. if err := rwc.(*net.TCPConn).CloseWrite(); err != nil {
  1144. fmt.Fprintf(os.Stderr, "Couldn't send EOF: %s\n", err)
  1145. }
  1146. return err
  1147. })
  1148. if err := <-receiveStdout; err != nil {
  1149. return err
  1150. }
  1151. if !term.IsTerminal(int(os.Stdin.Fd())) {
  1152. if err := <-sendStdin; err != nil {
  1153. return err
  1154. }
  1155. }
  1156. return nil
  1157. }
  1158. func Subcmd(name, signature, description string) *flag.FlagSet {
  1159. flags := flag.NewFlagSet(name, flag.ContinueOnError)
  1160. flags.Usage = func() {
  1161. fmt.Printf("\nUsage: docker %s %s\n\n%s\n\n", name, signature, description)
  1162. flags.PrintDefaults()
  1163. }
  1164. return flags
  1165. }
  1166. func NewDockerCli(host string, port int) *DockerCli {
  1167. return &DockerCli{host, port}
  1168. }
  1169. type DockerCli struct {
  1170. host string
  1171. port int
  1172. }