commands.go 29 KB

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