commands.go 39 KB

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