commands.go 37 KB

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