commands.go 31 KB

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