commands.go 36 KB

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