commands.go 36 KB

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