commands.go 26 KB

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