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. 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.Fprintf(os.Stderr, "%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.Fprintf(os.Stderr, "%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.Fprintf(os.Stderr, "%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 [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. fmt.Printf("[")
  474. for i, name := range args {
  475. if i > 0 {
  476. fmt.Printf(",")
  477. }
  478. obj, _, err := cli.call("GET", "/containers/"+name+"/json", nil)
  479. if err != nil {
  480. obj, _, err = cli.call("GET", "/images/"+name+"/json", nil)
  481. if err != nil {
  482. fmt.Fprintf(os.Stderr, "%s", err)
  483. continue
  484. }
  485. }
  486. indented := new(bytes.Buffer)
  487. if err = json.Indent(indented, obj, "", " "); err != nil {
  488. fmt.Fprintf(os.Stderr, "%s", err)
  489. continue
  490. }
  491. if _, err := io.Copy(os.Stdout, indented); err != nil {
  492. fmt.Fprintf(os.Stderr, "%s", err)
  493. }
  494. }
  495. fmt.Printf("]")
  496. return nil
  497. }
  498. func (cli *DockerCli) CmdPort(args ...string) error {
  499. cmd := Subcmd("port", "CONTAINER PRIVATE_PORT", "Lookup the public-facing port which is NAT-ed to PRIVATE_PORT")
  500. if err := cmd.Parse(args); err != nil {
  501. return nil
  502. }
  503. if cmd.NArg() != 2 {
  504. cmd.Usage()
  505. return nil
  506. }
  507. body, _, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/json", nil)
  508. if err != nil {
  509. return err
  510. }
  511. var out Container
  512. err = json.Unmarshal(body, &out)
  513. if err != nil {
  514. return err
  515. }
  516. if frontend, exists := out.NetworkSettings.PortMapping[cmd.Arg(1)]; exists {
  517. fmt.Println(frontend)
  518. } else {
  519. return fmt.Errorf("error: No private port '%s' allocated on %s", cmd.Arg(1), cmd.Arg(0))
  520. }
  521. return nil
  522. }
  523. // 'docker rmi IMAGE' removes all images with the name IMAGE
  524. func (cli *DockerCli) CmdRmi(args ...string) error {
  525. cmd := Subcmd("rmi", "IMAGE [IMAGE...]", "Remove an image")
  526. if err := cmd.Parse(args); err != nil {
  527. return nil
  528. }
  529. if cmd.NArg() < 1 {
  530. cmd.Usage()
  531. return nil
  532. }
  533. for _, name := range cmd.Args() {
  534. _, _, err := cli.call("DELETE", "/images/"+name, nil)
  535. if err != nil {
  536. fmt.Printf("%s", err)
  537. } else {
  538. fmt.Println(name)
  539. }
  540. }
  541. return nil
  542. }
  543. func (cli *DockerCli) CmdHistory(args ...string) error {
  544. cmd := Subcmd("history", "IMAGE", "Show the history of an image")
  545. if err := cmd.Parse(args); err != nil {
  546. return nil
  547. }
  548. if cmd.NArg() != 1 {
  549. cmd.Usage()
  550. return nil
  551. }
  552. body, _, err := cli.call("GET", "/images/"+cmd.Arg(0)+"/history", nil)
  553. if err != nil {
  554. return err
  555. }
  556. var outs []APIHistory
  557. err = json.Unmarshal(body, &outs)
  558. if err != nil {
  559. return err
  560. }
  561. w := tabwriter.NewWriter(os.Stdout, 20, 1, 3, ' ', 0)
  562. fmt.Fprintln(w, "ID\tCREATED\tCREATED BY")
  563. for _, out := range outs {
  564. fmt.Fprintf(w, "%s\t%s ago\t%s\n", out.ID, utils.HumanDuration(time.Now().Sub(time.Unix(out.Created, 0))), out.CreatedBy)
  565. }
  566. w.Flush()
  567. return nil
  568. }
  569. func (cli *DockerCli) CmdRm(args ...string) error {
  570. cmd := Subcmd("rm", "[OPTIONS] CONTAINER [CONTAINER...]", "Remove a container")
  571. v := cmd.Bool("v", false, "Remove the volumes associated to the container")
  572. if err := cmd.Parse(args); err != nil {
  573. return nil
  574. }
  575. if cmd.NArg() < 1 {
  576. cmd.Usage()
  577. return nil
  578. }
  579. val := url.Values{}
  580. if *v {
  581. val.Set("v", "1")
  582. }
  583. for _, name := range cmd.Args() {
  584. _, _, err := cli.call("DELETE", "/containers/"+name+"?"+val.Encode(), nil)
  585. if err != nil {
  586. fmt.Printf("%s", err)
  587. } else {
  588. fmt.Println(name)
  589. }
  590. }
  591. return nil
  592. }
  593. // 'docker kill NAME' kills a running container
  594. func (cli *DockerCli) CmdKill(args ...string) error {
  595. cmd := Subcmd("kill", "CONTAINER [CONTAINER...]", "Kill a running container")
  596. if err := cmd.Parse(args); err != nil {
  597. return nil
  598. }
  599. if cmd.NArg() < 1 {
  600. cmd.Usage()
  601. return nil
  602. }
  603. for _, name := range args {
  604. _, _, err := cli.call("POST", "/containers/"+name+"/kill", nil)
  605. if err != nil {
  606. fmt.Printf("%s", err)
  607. } else {
  608. fmt.Println(name)
  609. }
  610. }
  611. return nil
  612. }
  613. func (cli *DockerCli) CmdImport(args ...string) error {
  614. cmd := Subcmd("import", "URL|- [REPOSITORY [TAG]]", "Create a new filesystem image from the contents of a tarball")
  615. if err := cmd.Parse(args); err != nil {
  616. return nil
  617. }
  618. if cmd.NArg() < 1 {
  619. cmd.Usage()
  620. return nil
  621. }
  622. src, repository, tag := cmd.Arg(0), cmd.Arg(1), cmd.Arg(2)
  623. v := url.Values{}
  624. v.Set("repo", repository)
  625. v.Set("tag", tag)
  626. v.Set("fromSrc", src)
  627. err := cli.stream("POST", "/images/create?"+v.Encode(), os.Stdin, os.Stdout)
  628. if err != nil {
  629. return err
  630. }
  631. return nil
  632. }
  633. func (cli *DockerCli) CmdPush(args ...string) error {
  634. cmd := Subcmd("push", "[OPTION] NAME", "Push an image or a repository to the registry")
  635. registry := cmd.String("registry", "", "Registry host to push the image to")
  636. if err := cmd.Parse(args); err != nil {
  637. return nil
  638. }
  639. name := cmd.Arg(0)
  640. if name == "" {
  641. cmd.Usage()
  642. return nil
  643. }
  644. username, err := cli.checkIfLogged(*registry == "", "push")
  645. if err != nil {
  646. return err
  647. }
  648. if len(strings.SplitN(name, "/", 2)) == 1 {
  649. return fmt.Errorf("Impossible to push a \"root\" repository. Please rename your repository in <user>/<repo> (ex: %s/%s)", username, name)
  650. }
  651. v := url.Values{}
  652. v.Set("registry", *registry)
  653. if err := cli.stream("POST", "/images/"+name+"/push?"+v.Encode(), nil, os.Stdout); err != nil {
  654. return err
  655. }
  656. return nil
  657. }
  658. func (cli *DockerCli) CmdPull(args ...string) error {
  659. cmd := Subcmd("pull", "NAME", "Pull an image or a repository from the registry")
  660. tag := cmd.String("t", "", "Download tagged image in repository")
  661. registry := cmd.String("registry", "", "Registry to download from. Necessary if image is pulled by ID")
  662. if err := cmd.Parse(args); err != nil {
  663. return nil
  664. }
  665. if cmd.NArg() != 1 {
  666. cmd.Usage()
  667. return nil
  668. }
  669. remote := cmd.Arg(0)
  670. if strings.Contains(remote, ":") {
  671. remoteParts := strings.Split(remote, ":")
  672. tag = &remoteParts[1]
  673. remote = remoteParts[0]
  674. }
  675. v := url.Values{}
  676. v.Set("fromImage", remote)
  677. v.Set("tag", *tag)
  678. v.Set("registry", *registry)
  679. if err := cli.stream("POST", "/images/create?"+v.Encode(), nil, os.Stdout); err != nil {
  680. return err
  681. }
  682. return nil
  683. }
  684. func (cli *DockerCli) CmdImages(args ...string) error {
  685. cmd := Subcmd("images", "[OPTIONS] [NAME]", "List images")
  686. quiet := cmd.Bool("q", false, "only show numeric IDs")
  687. all := cmd.Bool("a", false, "show all images")
  688. noTrunc := cmd.Bool("notrunc", false, "Don't truncate output")
  689. flViz := cmd.Bool("viz", false, "output graph in graphviz format")
  690. if err := cmd.Parse(args); err != nil {
  691. return nil
  692. }
  693. if cmd.NArg() > 1 {
  694. cmd.Usage()
  695. return nil
  696. }
  697. if *flViz {
  698. body, _, err := cli.call("GET", "/images/viz", false)
  699. if err != nil {
  700. return err
  701. }
  702. fmt.Printf("%s", body)
  703. } else {
  704. v := url.Values{}
  705. if cmd.NArg() == 1 {
  706. v.Set("filter", cmd.Arg(0))
  707. }
  708. if *all {
  709. v.Set("all", "1")
  710. }
  711. body, _, err := cli.call("GET", "/images/json?"+v.Encode(), nil)
  712. if err != nil {
  713. return err
  714. }
  715. var outs []APIImages
  716. err = json.Unmarshal(body, &outs)
  717. if err != nil {
  718. return err
  719. }
  720. w := tabwriter.NewWriter(os.Stdout, 20, 1, 3, ' ', 0)
  721. if !*quiet {
  722. fmt.Fprintln(w, "REPOSITORY\tTAG\tID\tCREATED")
  723. }
  724. for _, out := range outs {
  725. if out.Repository == "" {
  726. out.Repository = "<none>"
  727. }
  728. if out.Tag == "" {
  729. out.Tag = "<none>"
  730. }
  731. if !*quiet {
  732. fmt.Fprintf(w, "%s\t%s\t", out.Repository, out.Tag)
  733. if *noTrunc {
  734. fmt.Fprintf(w, "%s\t", out.ID)
  735. } else {
  736. fmt.Fprintf(w, "%s\t", utils.TruncateID(out.ID))
  737. }
  738. fmt.Fprintf(w, "%s ago\n", utils.HumanDuration(time.Now().Sub(time.Unix(out.Created, 0))))
  739. } else {
  740. if *noTrunc {
  741. fmt.Fprintln(w, out.ID)
  742. } else {
  743. fmt.Fprintln(w, utils.TruncateID(out.ID))
  744. }
  745. }
  746. }
  747. if !*quiet {
  748. w.Flush()
  749. }
  750. }
  751. return nil
  752. }
  753. func (cli *DockerCli) CmdPs(args ...string) error {
  754. cmd := Subcmd("ps", "[OPTIONS]", "List containers")
  755. quiet := cmd.Bool("q", false, "Only display numeric IDs")
  756. all := cmd.Bool("a", false, "Show all containers. Only running containers are shown by default.")
  757. noTrunc := cmd.Bool("notrunc", false, "Don't truncate output")
  758. nLatest := cmd.Bool("l", false, "Show only the latest created container, include non-running ones.")
  759. since := cmd.String("sinceId", "", "Show only containers created since Id, include non-running ones.")
  760. before := cmd.String("beforeId", "", "Show only container created before Id, include non-running ones.")
  761. last := cmd.Int("n", -1, "Show n last created containers, include non-running ones.")
  762. if err := cmd.Parse(args); err != nil {
  763. return nil
  764. }
  765. v := url.Values{}
  766. if *last == -1 && *nLatest {
  767. *last = 1
  768. }
  769. if *all {
  770. v.Set("all", "1")
  771. }
  772. if *last != -1 {
  773. v.Set("limit", strconv.Itoa(*last))
  774. }
  775. if *since != "" {
  776. v.Set("since", *since)
  777. }
  778. if *before != "" {
  779. v.Set("before", *before)
  780. }
  781. body, _, err := cli.call("GET", "/containers/json?"+v.Encode(), nil)
  782. if err != nil {
  783. return err
  784. }
  785. var outs []APIContainers
  786. err = json.Unmarshal(body, &outs)
  787. if err != nil {
  788. return err
  789. }
  790. w := tabwriter.NewWriter(os.Stdout, 20, 1, 3, ' ', 0)
  791. if !*quiet {
  792. fmt.Fprintln(w, "ID\tIMAGE\tCOMMAND\tCREATED\tSTATUS\tPORTS")
  793. }
  794. for _, out := range outs {
  795. if !*quiet {
  796. if *noTrunc {
  797. 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)
  798. } else {
  799. 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)
  800. }
  801. } else {
  802. if *noTrunc {
  803. fmt.Fprintln(w, out.ID)
  804. } else {
  805. fmt.Fprintln(w, utils.TruncateID(out.ID))
  806. }
  807. }
  808. }
  809. if !*quiet {
  810. w.Flush()
  811. }
  812. return nil
  813. }
  814. func (cli *DockerCli) CmdCommit(args ...string) error {
  815. cmd := Subcmd("commit", "[OPTIONS] CONTAINER [REPOSITORY [TAG]]", "Create a new image from a container's changes")
  816. flComment := cmd.String("m", "", "Commit message")
  817. flAuthor := cmd.String("author", "", "Author (eg. \"John Hannibal Smith <hannibal@a-team.com>\"")
  818. flConfig := cmd.String("run", "", "Config automatically applied when the image is run. "+`(ex: {"Cmd": ["cat", "/world"], "PortSpecs": ["22"]}')`)
  819. if err := cmd.Parse(args); err != nil {
  820. return nil
  821. }
  822. name, repository, tag := cmd.Arg(0), cmd.Arg(1), cmd.Arg(2)
  823. if name == "" {
  824. cmd.Usage()
  825. return nil
  826. }
  827. v := url.Values{}
  828. v.Set("container", name)
  829. v.Set("repo", repository)
  830. v.Set("tag", tag)
  831. v.Set("comment", *flComment)
  832. v.Set("author", *flAuthor)
  833. var config *Config
  834. if *flConfig != "" {
  835. config = &Config{}
  836. if err := json.Unmarshal([]byte(*flConfig), config); err != nil {
  837. return err
  838. }
  839. }
  840. body, _, err := cli.call("POST", "/commit?"+v.Encode(), config)
  841. if err != nil {
  842. return err
  843. }
  844. apiID := &APIID{}
  845. err = json.Unmarshal(body, apiID)
  846. if err != nil {
  847. return err
  848. }
  849. fmt.Println(apiID.ID)
  850. return nil
  851. }
  852. func (cli *DockerCli) CmdExport(args ...string) error {
  853. cmd := Subcmd("export", "CONTAINER", "Export the contents of a filesystem as a tar archive")
  854. if err := cmd.Parse(args); err != nil {
  855. return nil
  856. }
  857. if cmd.NArg() != 1 {
  858. cmd.Usage()
  859. return nil
  860. }
  861. if err := cli.stream("GET", "/containers/"+cmd.Arg(0)+"/export", nil, os.Stdout); err != nil {
  862. return err
  863. }
  864. return nil
  865. }
  866. func (cli *DockerCli) CmdDiff(args ...string) error {
  867. cmd := Subcmd("diff", "CONTAINER", "Inspect changes on a container's filesystem")
  868. if err := cmd.Parse(args); err != nil {
  869. return nil
  870. }
  871. if cmd.NArg() != 1 {
  872. cmd.Usage()
  873. return nil
  874. }
  875. body, _, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/changes", nil)
  876. if err != nil {
  877. return err
  878. }
  879. changes := []Change{}
  880. err = json.Unmarshal(body, &changes)
  881. if err != nil {
  882. return err
  883. }
  884. for _, change := range changes {
  885. fmt.Println(change.String())
  886. }
  887. return nil
  888. }
  889. func (cli *DockerCli) CmdLogs(args ...string) error {
  890. cmd := Subcmd("logs", "CONTAINER", "Fetch the logs of a container")
  891. if err := cmd.Parse(args); err != nil {
  892. return nil
  893. }
  894. if cmd.NArg() != 1 {
  895. cmd.Usage()
  896. return nil
  897. }
  898. if err := cli.stream("POST", "/containers/"+cmd.Arg(0)+"/attach?logs=1&stdout=1", nil, os.Stdout); err != nil {
  899. return err
  900. }
  901. if err := cli.stream("POST", "/containers/"+cmd.Arg(0)+"/attach?logs=1&stderr=1", nil, os.Stderr); err != nil {
  902. return err
  903. }
  904. return nil
  905. }
  906. func (cli *DockerCli) CmdAttach(args ...string) error {
  907. cmd := Subcmd("attach", "CONTAINER", "Attach to a running container")
  908. if err := cmd.Parse(args); err != nil {
  909. return nil
  910. }
  911. if cmd.NArg() != 1 {
  912. cmd.Usage()
  913. return nil
  914. }
  915. body, _, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/json", nil)
  916. if err != nil {
  917. return err
  918. }
  919. container := &Container{}
  920. err = json.Unmarshal(body, container)
  921. if err != nil {
  922. return err
  923. }
  924. splitStderr := container.Config.Tty
  925. connections := 1
  926. if splitStderr {
  927. connections += 1
  928. }
  929. chErrors := make(chan error, connections)
  930. cli.monitorTtySize(cmd.Arg(0))
  931. if splitStderr {
  932. go func() {
  933. chErrors <- cli.hijack("POST", "/containers/"+cmd.Arg(0)+"/attach?stream=1&stderr=1", false, nil, os.Stderr)
  934. }()
  935. }
  936. v := url.Values{}
  937. v.Set("stream", "1")
  938. v.Set("stdin", "1")
  939. v.Set("stdout", "1")
  940. if !splitStderr {
  941. v.Set("stderr", "1")
  942. }
  943. go func() {
  944. chErrors <- cli.hijack("POST", "/containers/"+cmd.Arg(0)+"/attach?"+v.Encode(), container.Config.Tty, os.Stdin, os.Stdout)
  945. }()
  946. for connections > 0 {
  947. err := <-chErrors
  948. if err != nil {
  949. return err
  950. }
  951. connections -= 1
  952. }
  953. return nil
  954. }
  955. func (cli *DockerCli) CmdSearch(args ...string) error {
  956. cmd := Subcmd("search", "NAME", "Search the docker index for images")
  957. if err := cmd.Parse(args); err != nil {
  958. return nil
  959. }
  960. if cmd.NArg() != 1 {
  961. cmd.Usage()
  962. return nil
  963. }
  964. v := url.Values{}
  965. v.Set("term", cmd.Arg(0))
  966. body, _, err := cli.call("GET", "/images/search?"+v.Encode(), nil)
  967. if err != nil {
  968. return err
  969. }
  970. outs := []APISearch{}
  971. err = json.Unmarshal(body, &outs)
  972. if err != nil {
  973. return err
  974. }
  975. fmt.Printf("Found %d results matching your query (\"%s\")\n", len(outs), cmd.Arg(0))
  976. w := tabwriter.NewWriter(os.Stdout, 20, 1, 3, ' ', 0)
  977. fmt.Fprintf(w, "NAME\tDESCRIPTION\n")
  978. for _, out := range outs {
  979. fmt.Fprintf(w, "%s\t%s\n", out.Name, out.Description)
  980. }
  981. w.Flush()
  982. return nil
  983. }
  984. // Ports type - Used to parse multiple -p flags
  985. type ports []int
  986. // ListOpts type
  987. type ListOpts []string
  988. func (opts *ListOpts) String() string {
  989. return fmt.Sprint(*opts)
  990. }
  991. func (opts *ListOpts) Set(value string) error {
  992. *opts = append(*opts, value)
  993. return nil
  994. }
  995. // AttachOpts stores arguments to 'docker run -a', eg. which streams to attach to
  996. type AttachOpts map[string]bool
  997. func NewAttachOpts() AttachOpts {
  998. return make(AttachOpts)
  999. }
  1000. func (opts AttachOpts) String() string {
  1001. // Cast to underlying map type to avoid infinite recursion
  1002. return fmt.Sprintf("%v", map[string]bool(opts))
  1003. }
  1004. func (opts AttachOpts) Set(val string) error {
  1005. if val != "stdin" && val != "stdout" && val != "stderr" {
  1006. return fmt.Errorf("Unsupported stream name: %s", val)
  1007. }
  1008. opts[val] = true
  1009. return nil
  1010. }
  1011. func (opts AttachOpts) Get(val string) bool {
  1012. if res, exists := opts[val]; exists {
  1013. return res
  1014. }
  1015. return false
  1016. }
  1017. // PathOpts stores a unique set of absolute paths
  1018. type PathOpts map[string]struct{}
  1019. func NewPathOpts() PathOpts {
  1020. return make(PathOpts)
  1021. }
  1022. func (opts PathOpts) String() string {
  1023. return fmt.Sprintf("%v", map[string]struct{}(opts))
  1024. }
  1025. func (opts PathOpts) Set(val string) error {
  1026. if !filepath.IsAbs(val) {
  1027. return fmt.Errorf("%s is not an absolute path", val)
  1028. }
  1029. opts[filepath.Clean(val)] = struct{}{}
  1030. return nil
  1031. }
  1032. func (cli *DockerCli) CmdTag(args ...string) error {
  1033. cmd := Subcmd("tag", "[OPTIONS] IMAGE REPOSITORY [TAG]", "Tag an image into a repository")
  1034. force := cmd.Bool("f", false, "Force")
  1035. if err := cmd.Parse(args); err != nil {
  1036. return nil
  1037. }
  1038. if cmd.NArg() != 2 && cmd.NArg() != 3 {
  1039. cmd.Usage()
  1040. return nil
  1041. }
  1042. v := url.Values{}
  1043. v.Set("repo", cmd.Arg(1))
  1044. if cmd.NArg() == 3 {
  1045. v.Set("tag", cmd.Arg(2))
  1046. }
  1047. if *force {
  1048. v.Set("force", "1")
  1049. }
  1050. if _, _, err := cli.call("POST", "/images/"+cmd.Arg(0)+"/tag?"+v.Encode(), nil); err != nil {
  1051. return err
  1052. }
  1053. return nil
  1054. }
  1055. func (cli *DockerCli) CmdRun(args ...string) error {
  1056. config, cmd, err := ParseRun(args, nil)
  1057. if err != nil {
  1058. return err
  1059. }
  1060. if config.Image == "" {
  1061. cmd.Usage()
  1062. return nil
  1063. }
  1064. //create the container
  1065. body, statusCode, err := cli.call("POST", "/containers/create", config)
  1066. //if image not found try to pull it
  1067. if statusCode == 404 {
  1068. v := url.Values{}
  1069. v.Set("fromImage", config.Image)
  1070. err = cli.stream("POST", "/images/create?"+v.Encode(), nil, os.Stderr)
  1071. if err != nil {
  1072. return err
  1073. }
  1074. body, _, err = cli.call("POST", "/containers/create", config)
  1075. if err != nil {
  1076. return err
  1077. }
  1078. }
  1079. if err != nil {
  1080. return err
  1081. }
  1082. out := &APIRun{}
  1083. err = json.Unmarshal(body, out)
  1084. if err != nil {
  1085. return err
  1086. }
  1087. for _, warning := range out.Warnings {
  1088. fmt.Fprintln(os.Stderr, "WARNING: ", warning)
  1089. }
  1090. splitStderr := !config.Tty
  1091. connections := 0
  1092. if config.AttachStdin || config.AttachStdout || (!splitStderr && config.AttachStderr) {
  1093. connections += 1
  1094. }
  1095. if splitStderr && config.AttachStderr {
  1096. connections += 1
  1097. }
  1098. //start the container
  1099. _, _, err = cli.call("POST", "/containers/"+out.ID+"/start", nil)
  1100. if err != nil {
  1101. return err
  1102. }
  1103. if !config.AttachStdout && !config.AttachStderr {
  1104. fmt.Println(out.ID)
  1105. }
  1106. if connections > 0 {
  1107. chErrors := make(chan error, connections)
  1108. cli.monitorTtySize(out.ID)
  1109. if splitStderr && config.AttachStderr {
  1110. go func() {
  1111. chErrors <- cli.hijack("POST", "/containers/"+out.ID+"/attach?logs=1&stream=1&stderr=1", config.Tty, nil, os.Stderr)
  1112. }()
  1113. }
  1114. v := url.Values{}
  1115. v.Set("logs", "1")
  1116. v.Set("stream", "1")
  1117. if config.AttachStdin {
  1118. v.Set("stdin", "1")
  1119. }
  1120. if config.AttachStdout {
  1121. v.Set("stdout", "1")
  1122. }
  1123. if !splitStderr && config.AttachStderr {
  1124. v.Set("stderr", "1")
  1125. }
  1126. go func() {
  1127. chErrors <- cli.hijack("POST", "/containers/"+out.ID+"/attach?"+v.Encode(), config.Tty, os.Stdin, os.Stdout)
  1128. }()
  1129. for connections > 0 {
  1130. err := <-chErrors
  1131. if err != nil {
  1132. return err
  1133. }
  1134. connections -= 1
  1135. }
  1136. }
  1137. return nil
  1138. }
  1139. func (cli *DockerCli) checkIfLogged(condition bool, action string) (string, error) {
  1140. body, _, err := cli.call("GET", "/auth", nil)
  1141. if err != nil {
  1142. return "", err
  1143. }
  1144. var out auth.AuthConfig
  1145. err = json.Unmarshal(body, &out)
  1146. if err != nil {
  1147. return "", err
  1148. }
  1149. // If condition AND the login failed
  1150. if condition && out.Username == "" {
  1151. if err := cli.CmdLogin(""); err != nil {
  1152. return "", err
  1153. }
  1154. body, _, err = cli.call("GET", "/auth", nil)
  1155. if err != nil {
  1156. return "", err
  1157. }
  1158. err = json.Unmarshal(body, &out)
  1159. if err != nil {
  1160. return "", err
  1161. }
  1162. if out.Username == "" {
  1163. return "", fmt.Errorf("Please login prior to %s. ('docker login')", action)
  1164. }
  1165. }
  1166. return out.Username, nil
  1167. }
  1168. func (cli *DockerCli) call(method, path string, data interface{}) ([]byte, int, error) {
  1169. var params io.Reader
  1170. if data != nil {
  1171. buf, err := json.Marshal(data)
  1172. if err != nil {
  1173. return nil, -1, err
  1174. }
  1175. params = bytes.NewBuffer(buf)
  1176. }
  1177. req, err := http.NewRequest(method, fmt.Sprintf("http://%s:%d/v%g%s", cli.host, cli.port, APIVERSION, path), params)
  1178. if err != nil {
  1179. return nil, -1, err
  1180. }
  1181. req.Header.Set("User-Agent", "Docker-Client/"+VERSION)
  1182. if data != nil {
  1183. req.Header.Set("Content-Type", "application/json")
  1184. } else if method == "POST" {
  1185. req.Header.Set("Content-Type", "plain/text")
  1186. }
  1187. resp, err := http.DefaultClient.Do(req)
  1188. if err != nil {
  1189. if strings.Contains(err.Error(), "connection refused") {
  1190. return nil, -1, fmt.Errorf("Can't connect to docker daemon. Is 'docker -d' running on this host?")
  1191. }
  1192. return nil, -1, err
  1193. }
  1194. defer resp.Body.Close()
  1195. body, err := ioutil.ReadAll(resp.Body)
  1196. if err != nil {
  1197. return nil, -1, err
  1198. }
  1199. if resp.StatusCode < 200 || resp.StatusCode >= 400 {
  1200. return nil, resp.StatusCode, fmt.Errorf("error: %s", body)
  1201. }
  1202. return body, resp.StatusCode, nil
  1203. }
  1204. func (cli *DockerCli) stream(method, path string, in io.Reader, out io.Writer) error {
  1205. if (method == "POST" || method == "PUT") && in == nil {
  1206. in = bytes.NewReader([]byte{})
  1207. }
  1208. req, err := http.NewRequest(method, fmt.Sprintf("http://%s:%d/v%g%s", cli.host, cli.port, APIVERSION, path), in)
  1209. if err != nil {
  1210. return err
  1211. }
  1212. req.Header.Set("User-Agent", "Docker-Client/"+VERSION)
  1213. if method == "POST" {
  1214. req.Header.Set("Content-Type", "plain/text")
  1215. }
  1216. resp, err := http.DefaultClient.Do(req)
  1217. if err != nil {
  1218. if strings.Contains(err.Error(), "connection refused") {
  1219. return fmt.Errorf("Can't connect to docker daemon. Is 'docker -d' running on this host?")
  1220. }
  1221. return err
  1222. }
  1223. defer resp.Body.Close()
  1224. if resp.StatusCode < 200 || resp.StatusCode >= 400 {
  1225. body, err := ioutil.ReadAll(resp.Body)
  1226. if err != nil {
  1227. return err
  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(os.Stdin.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. }