commands.go 36 KB

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