commands.go 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604
  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", "", "Repository name 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, parsedTag := utils.ParseRepositoryTag(cmd.Arg(0))
  701. *tag = parsedTag
  702. v := url.Values{}
  703. v.Set("fromImage", remote)
  704. v.Set("tag", *tag)
  705. if err := cli.stream("POST", "/images/create?"+v.Encode(), nil, cli.out); err != nil {
  706. return err
  707. }
  708. return nil
  709. }
  710. func (cli *DockerCli) CmdImages(args ...string) error {
  711. cmd := Subcmd("images", "[OPTIONS] [NAME]", "List images")
  712. quiet := cmd.Bool("q", false, "only show numeric IDs")
  713. all := cmd.Bool("a", false, "show all images")
  714. noTrunc := cmd.Bool("notrunc", false, "Don't truncate output")
  715. flViz := cmd.Bool("viz", false, "output graph in graphviz format")
  716. if err := cmd.Parse(args); err != nil {
  717. return nil
  718. }
  719. if cmd.NArg() > 1 {
  720. cmd.Usage()
  721. return nil
  722. }
  723. if *flViz {
  724. body, _, err := cli.call("GET", "/images/viz", false)
  725. if err != nil {
  726. return err
  727. }
  728. fmt.Fprintf(cli.out, "%s", body)
  729. } else {
  730. v := url.Values{}
  731. if cmd.NArg() == 1 {
  732. v.Set("filter", cmd.Arg(0))
  733. }
  734. if *all {
  735. v.Set("all", "1")
  736. }
  737. body, _, err := cli.call("GET", "/images/json?"+v.Encode(), nil)
  738. if err != nil {
  739. return err
  740. }
  741. var outs []APIImages
  742. err = json.Unmarshal(body, &outs)
  743. if err != nil {
  744. return err
  745. }
  746. w := tabwriter.NewWriter(cli.out, 20, 1, 3, ' ', 0)
  747. if !*quiet {
  748. fmt.Fprintln(w, "REPOSITORY\tTAG\tID\tCREATED\tSIZE")
  749. }
  750. for _, out := range outs {
  751. if out.Repository == "" {
  752. out.Repository = "<none>"
  753. }
  754. if out.Tag == "" {
  755. out.Tag = "<none>"
  756. }
  757. if !*quiet {
  758. fmt.Fprintf(w, "%s\t%s\t", out.Repository, out.Tag)
  759. if *noTrunc {
  760. fmt.Fprintf(w, "%s\t", out.ID)
  761. } else {
  762. fmt.Fprintf(w, "%s\t", utils.TruncateID(out.ID))
  763. }
  764. fmt.Fprintf(w, "%s ago\t", utils.HumanDuration(time.Now().Sub(time.Unix(out.Created, 0))))
  765. if out.VirtualSize > 0 {
  766. fmt.Fprintf(w, "%s (virtual %s)\n", utils.HumanSize(out.Size), utils.HumanSize(out.VirtualSize))
  767. } else {
  768. fmt.Fprintf(w, "%s\n", utils.HumanSize(out.Size))
  769. }
  770. } else {
  771. if *noTrunc {
  772. fmt.Fprintln(w, out.ID)
  773. } else {
  774. fmt.Fprintln(w, utils.TruncateID(out.ID))
  775. }
  776. }
  777. }
  778. if !*quiet {
  779. w.Flush()
  780. }
  781. }
  782. return nil
  783. }
  784. func (cli *DockerCli) CmdPs(args ...string) error {
  785. cmd := Subcmd("ps", "[OPTIONS]", "List containers")
  786. quiet := cmd.Bool("q", false, "Only display numeric IDs")
  787. size := cmd.Bool("s", false, "Display sizes")
  788. all := cmd.Bool("a", false, "Show all containers. Only running containers are shown by default.")
  789. noTrunc := cmd.Bool("notrunc", false, "Don't truncate output")
  790. nLatest := cmd.Bool("l", false, "Show only the latest created container, include non-running ones.")
  791. since := cmd.String("sinceId", "", "Show only containers created since Id, include non-running ones.")
  792. before := cmd.String("beforeId", "", "Show only container created before Id, include non-running ones.")
  793. last := cmd.Int("n", -1, "Show n last created containers, include non-running ones.")
  794. if err := cmd.Parse(args); err != nil {
  795. return nil
  796. }
  797. v := url.Values{}
  798. if *last == -1 && *nLatest {
  799. *last = 1
  800. }
  801. if *all {
  802. v.Set("all", "1")
  803. }
  804. if *last != -1 {
  805. v.Set("limit", strconv.Itoa(*last))
  806. }
  807. if *since != "" {
  808. v.Set("since", *since)
  809. }
  810. if *before != "" {
  811. v.Set("before", *before)
  812. }
  813. if *size {
  814. v.Set("size", "1")
  815. }
  816. body, _, err := cli.call("GET", "/containers/json?"+v.Encode(), nil)
  817. if err != nil {
  818. return err
  819. }
  820. var outs []APIContainers
  821. err = json.Unmarshal(body, &outs)
  822. if err != nil {
  823. return err
  824. }
  825. w := tabwriter.NewWriter(cli.out, 20, 1, 3, ' ', 0)
  826. if !*quiet {
  827. fmt.Fprint(w, "ID\tIMAGE\tCOMMAND\tCREATED\tSTATUS\tPORTS")
  828. if *size {
  829. fmt.Fprintln(w, "\tSIZE")
  830. } else {
  831. fmt.Fprint(w, "\n")
  832. }
  833. }
  834. for _, out := range outs {
  835. if !*quiet {
  836. if *noTrunc {
  837. 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)
  838. } else {
  839. 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)
  840. }
  841. if *size {
  842. if out.SizeRootFs > 0 {
  843. fmt.Fprintf(w, "%s (virtual %s)\n", utils.HumanSize(out.SizeRw), utils.HumanSize(out.SizeRootFs))
  844. } else {
  845. fmt.Fprintf(w, "%s\n", utils.HumanSize(out.SizeRw))
  846. }
  847. } else {
  848. fmt.Fprint(w, "\n")
  849. }
  850. } else {
  851. if *noTrunc {
  852. fmt.Fprintln(w, out.ID)
  853. } else {
  854. fmt.Fprintln(w, utils.TruncateID(out.ID))
  855. }
  856. }
  857. }
  858. if !*quiet {
  859. w.Flush()
  860. }
  861. return nil
  862. }
  863. func (cli *DockerCli) CmdCommit(args ...string) error {
  864. cmd := Subcmd("commit", "[OPTIONS] CONTAINER [REPOSITORY [TAG]]", "Create a new image from a container's changes")
  865. flComment := cmd.String("m", "", "Commit message")
  866. flAuthor := cmd.String("author", "", "Author (eg. \"John Hannibal Smith <hannibal@a-team.com>\"")
  867. flConfig := cmd.String("run", "", "Config automatically applied when the image is run. "+`(ex: {"Cmd": ["cat", "/world"], "PortSpecs": ["22"]}')`)
  868. if err := cmd.Parse(args); err != nil {
  869. return nil
  870. }
  871. name, repository, tag := cmd.Arg(0), cmd.Arg(1), cmd.Arg(2)
  872. if name == "" {
  873. cmd.Usage()
  874. return nil
  875. }
  876. v := url.Values{}
  877. v.Set("container", name)
  878. v.Set("repo", repository)
  879. v.Set("tag", tag)
  880. v.Set("comment", *flComment)
  881. v.Set("author", *flAuthor)
  882. var config *Config
  883. if *flConfig != "" {
  884. config = &Config{}
  885. if err := json.Unmarshal([]byte(*flConfig), config); err != nil {
  886. return err
  887. }
  888. }
  889. body, _, err := cli.call("POST", "/commit?"+v.Encode(), config)
  890. if err != nil {
  891. return err
  892. }
  893. apiID := &APIID{}
  894. err = json.Unmarshal(body, apiID)
  895. if err != nil {
  896. return err
  897. }
  898. fmt.Fprintf(cli.out, "%s\n", apiID.ID)
  899. return nil
  900. }
  901. func (cli *DockerCli) CmdExport(args ...string) error {
  902. cmd := Subcmd("export", "CONTAINER", "Export the contents of a filesystem as a tar archive")
  903. if err := cmd.Parse(args); err != nil {
  904. return nil
  905. }
  906. if cmd.NArg() != 1 {
  907. cmd.Usage()
  908. return nil
  909. }
  910. if err := cli.stream("GET", "/containers/"+cmd.Arg(0)+"/export", nil, cli.out); err != nil {
  911. return err
  912. }
  913. return nil
  914. }
  915. func (cli *DockerCli) CmdDiff(args ...string) error {
  916. cmd := Subcmd("diff", "CONTAINER", "Inspect changes on a container's filesystem")
  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. body, _, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/changes", nil)
  925. if err != nil {
  926. return err
  927. }
  928. changes := []Change{}
  929. err = json.Unmarshal(body, &changes)
  930. if err != nil {
  931. return err
  932. }
  933. for _, change := range changes {
  934. fmt.Fprintf(cli.out, "%s\n", change.String())
  935. }
  936. return nil
  937. }
  938. func (cli *DockerCli) CmdLogs(args ...string) error {
  939. cmd := Subcmd("logs", "CONTAINER", "Fetch the logs of a container")
  940. if err := cmd.Parse(args); err != nil {
  941. return nil
  942. }
  943. if cmd.NArg() != 1 {
  944. cmd.Usage()
  945. return nil
  946. }
  947. if err := cli.hijack("POST", "/containers/"+cmd.Arg(0)+"/attach?logs=1&stdout=1", false, nil, cli.out); err != nil {
  948. return err
  949. }
  950. if err := cli.hijack("POST", "/containers/"+cmd.Arg(0)+"/attach?logs=1&stderr=1", false, nil, cli.err); err != nil {
  951. return err
  952. }
  953. return nil
  954. }
  955. func (cli *DockerCli) CmdAttach(args ...string) error {
  956. cmd := Subcmd("attach", "CONTAINER", "Attach to a running container")
  957. if err := cmd.Parse(args); err != nil {
  958. return nil
  959. }
  960. if cmd.NArg() != 1 {
  961. cmd.Usage()
  962. return nil
  963. }
  964. body, _, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/json", nil)
  965. if err != nil {
  966. return err
  967. }
  968. container := &Container{}
  969. err = json.Unmarshal(body, container)
  970. if err != nil {
  971. return err
  972. }
  973. if !container.State.Running {
  974. return fmt.Errorf("Impossible to attach to a stopped container, start it first")
  975. }
  976. if container.Config.Tty {
  977. if err := cli.monitorTtySize(cmd.Arg(0)); err != nil {
  978. return err
  979. }
  980. }
  981. v := url.Values{}
  982. v.Set("stream", "1")
  983. v.Set("stdin", "1")
  984. v.Set("stdout", "1")
  985. v.Set("stderr", "1")
  986. if err := cli.hijack("POST", "/containers/"+cmd.Arg(0)+"/attach?"+v.Encode(), container.Config.Tty, cli.in, cli.out); err != nil {
  987. return err
  988. }
  989. return nil
  990. }
  991. func (cli *DockerCli) CmdSearch(args ...string) error {
  992. cmd := Subcmd("search", "NAME", "Search the docker index for images")
  993. noTrunc := cmd.Bool("notrunc", false, "Don't truncate output")
  994. if err := cmd.Parse(args); err != nil {
  995. return nil
  996. }
  997. if cmd.NArg() != 1 {
  998. cmd.Usage()
  999. return nil
  1000. }
  1001. v := url.Values{}
  1002. v.Set("term", cmd.Arg(0))
  1003. body, _, err := cli.call("GET", "/images/search?"+v.Encode(), nil)
  1004. if err != nil {
  1005. return err
  1006. }
  1007. outs := []APISearch{}
  1008. err = json.Unmarshal(body, &outs)
  1009. if err != nil {
  1010. return err
  1011. }
  1012. fmt.Fprintf(cli.out, "Found %d results matching your query (\"%s\")\n", len(outs), cmd.Arg(0))
  1013. w := tabwriter.NewWriter(cli.out, 33, 1, 3, ' ', 0)
  1014. fmt.Fprintf(w, "NAME\tDESCRIPTION\n")
  1015. _, width := cli.getTtySize()
  1016. if width == 0 {
  1017. width = 45
  1018. } else {
  1019. width = width - 33 //remote the first column
  1020. }
  1021. for _, out := range outs {
  1022. desc := strings.Replace(out.Description, "\n", " ", -1)
  1023. desc = strings.Replace(desc, "\r", " ", -1)
  1024. if !*noTrunc && len(desc) > width {
  1025. desc = utils.Trunc(desc, width-3) + "..."
  1026. }
  1027. fmt.Fprintf(w, "%s\t%s\n", out.Name, desc)
  1028. }
  1029. w.Flush()
  1030. return nil
  1031. }
  1032. // Ports type - Used to parse multiple -p flags
  1033. type ports []int
  1034. // ListOpts type
  1035. type ListOpts []string
  1036. func (opts *ListOpts) String() string {
  1037. return fmt.Sprint(*opts)
  1038. }
  1039. func (opts *ListOpts) Set(value string) error {
  1040. *opts = append(*opts, value)
  1041. return nil
  1042. }
  1043. // AttachOpts stores arguments to 'docker run -a', eg. which streams to attach to
  1044. type AttachOpts map[string]bool
  1045. func NewAttachOpts() AttachOpts {
  1046. return make(AttachOpts)
  1047. }
  1048. func (opts AttachOpts) String() string {
  1049. // Cast to underlying map type to avoid infinite recursion
  1050. return fmt.Sprintf("%v", map[string]bool(opts))
  1051. }
  1052. func (opts AttachOpts) Set(val string) error {
  1053. if val != "stdin" && val != "stdout" && val != "stderr" {
  1054. return fmt.Errorf("Unsupported stream name: %s", val)
  1055. }
  1056. opts[val] = true
  1057. return nil
  1058. }
  1059. func (opts AttachOpts) Get(val string) bool {
  1060. if res, exists := opts[val]; exists {
  1061. return res
  1062. }
  1063. return false
  1064. }
  1065. // PathOpts stores a unique set of absolute paths
  1066. type PathOpts map[string]struct{}
  1067. func NewPathOpts() PathOpts {
  1068. return make(PathOpts)
  1069. }
  1070. func (opts PathOpts) String() string {
  1071. return fmt.Sprintf("%v", map[string]struct{}(opts))
  1072. }
  1073. func (opts PathOpts) Set(val string) error {
  1074. if !filepath.IsAbs(val) {
  1075. return fmt.Errorf("%s is not an absolute path", val)
  1076. }
  1077. opts[filepath.Clean(val)] = struct{}{}
  1078. return nil
  1079. }
  1080. func (cli *DockerCli) CmdTag(args ...string) error {
  1081. cmd := Subcmd("tag", "[OPTIONS] IMAGE REPOSITORY [TAG]", "Tag an image into a repository")
  1082. force := cmd.Bool("f", false, "Force")
  1083. if err := cmd.Parse(args); err != nil {
  1084. return nil
  1085. }
  1086. if cmd.NArg() != 2 && cmd.NArg() != 3 {
  1087. cmd.Usage()
  1088. return nil
  1089. }
  1090. v := url.Values{}
  1091. v.Set("repo", cmd.Arg(1))
  1092. if cmd.NArg() == 3 {
  1093. v.Set("tag", cmd.Arg(2))
  1094. }
  1095. if *force {
  1096. v.Set("force", "1")
  1097. }
  1098. if _, _, err := cli.call("POST", "/images/"+cmd.Arg(0)+"/tag?"+v.Encode(), nil); err != nil {
  1099. return err
  1100. }
  1101. return nil
  1102. }
  1103. func (cli *DockerCli) CmdRun(args ...string) error {
  1104. config, hostConfig, cmd, err := ParseRun(args, nil)
  1105. if err != nil {
  1106. return err
  1107. }
  1108. if config.Image == "" {
  1109. cmd.Usage()
  1110. return nil
  1111. }
  1112. //create the container
  1113. body, statusCode, err := cli.call("POST", "/containers/create", config)
  1114. //if image not found try to pull it
  1115. if statusCode == 404 {
  1116. v := url.Values{}
  1117. repos, tag := utils.ParseRepositoryTag(config.Image)
  1118. v.Set("fromImage", repos)
  1119. v.Set("tag", tag)
  1120. err = cli.stream("POST", "/images/create?"+v.Encode(), nil, cli.err)
  1121. if err != nil {
  1122. return err
  1123. }
  1124. body, _, err = cli.call("POST", "/containers/create", config)
  1125. if err != nil {
  1126. return err
  1127. }
  1128. }
  1129. if err != nil {
  1130. return err
  1131. }
  1132. runResult := &APIRun{}
  1133. err = json.Unmarshal(body, runResult)
  1134. if err != nil {
  1135. return err
  1136. }
  1137. for _, warning := range runResult.Warnings {
  1138. fmt.Fprintf(cli.err, "WARNING: %s\n", warning)
  1139. }
  1140. //start the container
  1141. if _, _, err = cli.call("POST", "/containers/"+runResult.ID+"/start", hostConfig); err != nil {
  1142. return err
  1143. }
  1144. var wait chan struct{}
  1145. if !config.AttachStdout && !config.AttachStderr {
  1146. // Make this asynchrone in order to let the client write to stdin before having to read the ID
  1147. wait = make(chan struct{})
  1148. go func() {
  1149. defer close(wait)
  1150. fmt.Fprintf(cli.out, "%s\n", runResult.ID)
  1151. }()
  1152. }
  1153. if config.AttachStdin || config.AttachStdout || config.AttachStderr {
  1154. if config.Tty {
  1155. if err := cli.monitorTtySize(runResult.ID); err != nil {
  1156. return err
  1157. }
  1158. }
  1159. v := url.Values{}
  1160. v.Set("logs", "1")
  1161. v.Set("stream", "1")
  1162. if config.AttachStdin {
  1163. v.Set("stdin", "1")
  1164. }
  1165. if config.AttachStdout {
  1166. v.Set("stdout", "1")
  1167. }
  1168. if config.AttachStderr {
  1169. v.Set("stderr", "1")
  1170. }
  1171. if err := cli.hijack("POST", "/containers/"+runResult.ID+"/attach?"+v.Encode(), config.Tty, cli.in, cli.out); err != nil {
  1172. utils.Debugf("Error hijack: %s", err)
  1173. return err
  1174. }
  1175. }
  1176. if !config.AttachStdout && !config.AttachStderr {
  1177. <-wait
  1178. }
  1179. return nil
  1180. }
  1181. func (cli *DockerCli) checkIfLogged(action string) error {
  1182. // If condition AND the login failed
  1183. if cli.authConfig.Username == "" {
  1184. if err := cli.CmdLogin(""); err != nil {
  1185. return err
  1186. }
  1187. if cli.authConfig.Username == "" {
  1188. return fmt.Errorf("Please login prior to %s. ('docker login')", action)
  1189. }
  1190. }
  1191. return nil
  1192. }
  1193. func (cli *DockerCli) call(method, path string, data interface{}) ([]byte, int, error) {
  1194. var params io.Reader
  1195. if data != nil {
  1196. buf, err := json.Marshal(data)
  1197. if err != nil {
  1198. return nil, -1, err
  1199. }
  1200. params = bytes.NewBuffer(buf)
  1201. }
  1202. req, err := http.NewRequest(method, fmt.Sprintf("/v%g%s", APIVERSION, path), params)
  1203. if err != nil {
  1204. return nil, -1, err
  1205. }
  1206. req.Header.Set("User-Agent", "Docker-Client/"+VERSION)
  1207. if data != nil {
  1208. req.Header.Set("Content-Type", "application/json")
  1209. } else if method == "POST" {
  1210. req.Header.Set("Content-Type", "plain/text")
  1211. }
  1212. dial, err := net.Dial(cli.proto, cli.addr)
  1213. if err != nil {
  1214. return nil, -1, err
  1215. }
  1216. clientconn := httputil.NewClientConn(dial, nil)
  1217. resp, err := clientconn.Do(req)
  1218. defer clientconn.Close()
  1219. if err != nil {
  1220. if strings.Contains(err.Error(), "connection refused") {
  1221. return nil, -1, fmt.Errorf("Can't connect to docker daemon. Is 'docker -d' running on this host?")
  1222. }
  1223. return nil, -1, err
  1224. }
  1225. defer resp.Body.Close()
  1226. body, err := ioutil.ReadAll(resp.Body)
  1227. if err != nil {
  1228. return nil, -1, err
  1229. }
  1230. if resp.StatusCode < 200 || resp.StatusCode >= 400 {
  1231. if len(body) == 0 {
  1232. return nil, resp.StatusCode, fmt.Errorf("Error: %s", http.StatusText(resp.StatusCode))
  1233. }
  1234. return nil, resp.StatusCode, fmt.Errorf("Error: %s", body)
  1235. }
  1236. return body, resp.StatusCode, nil
  1237. }
  1238. func (cli *DockerCli) stream(method, path string, in io.Reader, out io.Writer) error {
  1239. if (method == "POST" || method == "PUT") && in == nil {
  1240. in = bytes.NewReader([]byte{})
  1241. }
  1242. req, err := http.NewRequest(method, fmt.Sprintf("/v%g%s", APIVERSION, path), in)
  1243. if err != nil {
  1244. return err
  1245. }
  1246. req.Header.Set("User-Agent", "Docker-Client/"+VERSION)
  1247. if method == "POST" {
  1248. req.Header.Set("Content-Type", "plain/text")
  1249. }
  1250. dial, err := net.Dial(cli.proto, cli.addr)
  1251. if err != nil {
  1252. return err
  1253. }
  1254. clientconn := httputil.NewClientConn(dial, nil)
  1255. resp, err := clientconn.Do(req)
  1256. defer clientconn.Close()
  1257. if err != nil {
  1258. if strings.Contains(err.Error(), "connection refused") {
  1259. return fmt.Errorf("Can't connect to docker daemon. Is 'docker -d' running on this host?")
  1260. }
  1261. return err
  1262. }
  1263. defer resp.Body.Close()
  1264. if resp.StatusCode < 200 || resp.StatusCode >= 400 {
  1265. body, err := ioutil.ReadAll(resp.Body)
  1266. if err != nil {
  1267. return err
  1268. }
  1269. if len(body) == 0 {
  1270. return fmt.Errorf("Error :%s", http.StatusText(resp.StatusCode))
  1271. }
  1272. return fmt.Errorf("Error: %s", body)
  1273. }
  1274. if resp.Header.Get("Content-Type") == "application/json" {
  1275. dec := json.NewDecoder(resp.Body)
  1276. for {
  1277. var m utils.JSONMessage
  1278. if err := dec.Decode(&m); err == io.EOF {
  1279. break
  1280. } else if err != nil {
  1281. return err
  1282. }
  1283. if m.Progress != "" {
  1284. fmt.Fprintf(out, "%s %s\r", m.Status, m.Progress)
  1285. } else if m.Error != "" {
  1286. return fmt.Errorf(m.Error)
  1287. } else {
  1288. fmt.Fprintf(out, "%s\n", m.Status)
  1289. }
  1290. }
  1291. } else {
  1292. if _, err := io.Copy(out, resp.Body); err != nil {
  1293. return err
  1294. }
  1295. }
  1296. return nil
  1297. }
  1298. func (cli *DockerCli) hijack(method, path string, setRawTerminal bool, in io.ReadCloser, out io.Writer) error {
  1299. req, err := http.NewRequest(method, fmt.Sprintf("/v%g%s", APIVERSION, path), nil)
  1300. if err != nil {
  1301. return err
  1302. }
  1303. req.Header.Set("User-Agent", "Docker-Client/"+VERSION)
  1304. req.Header.Set("Content-Type", "plain/text")
  1305. dial, err := net.Dial(cli.proto, cli.addr)
  1306. if err != nil {
  1307. return err
  1308. }
  1309. clientconn := httputil.NewClientConn(dial, nil)
  1310. defer clientconn.Close()
  1311. // Server hijacks the connection, error 'connection closed' expected
  1312. clientconn.Do(req)
  1313. rwc, br := clientconn.Hijack()
  1314. defer rwc.Close()
  1315. receiveStdout := utils.Go(func() error {
  1316. _, err := io.Copy(out, br)
  1317. return err
  1318. })
  1319. if in != nil && setRawTerminal && cli.isTerminal && os.Getenv("NORAW") == "" {
  1320. oldState, err := term.SetRawTerminal(cli.terminalFd)
  1321. if err != nil {
  1322. return err
  1323. }
  1324. defer term.RestoreTerminal(cli.terminalFd, oldState)
  1325. }
  1326. sendStdin := utils.Go(func() error {
  1327. if in != nil {
  1328. io.Copy(rwc, in)
  1329. }
  1330. if tcpc, ok := rwc.(*net.TCPConn); ok {
  1331. if err := tcpc.CloseWrite(); err != nil {
  1332. utils.Debugf("Couldn't send EOF: %s\n", err)
  1333. }
  1334. } else if unixc, ok := rwc.(*net.UnixConn); ok {
  1335. if err := unixc.CloseWrite(); err != nil {
  1336. utils.Debugf("Couldn't send EOF: %s\n", err)
  1337. }
  1338. }
  1339. // Discard errors due to pipe interruption
  1340. return nil
  1341. })
  1342. if err := <-receiveStdout; err != nil {
  1343. utils.Debugf("Error receiveStdout: %s", err)
  1344. return err
  1345. }
  1346. if !cli.isTerminal {
  1347. if err := <-sendStdin; err != nil {
  1348. utils.Debugf("Error sendStdin: %s", err)
  1349. return err
  1350. }
  1351. }
  1352. return nil
  1353. }
  1354. func (cli *DockerCli) getTtySize() (int, int) {
  1355. if !cli.isTerminal {
  1356. return 0, 0
  1357. }
  1358. ws, err := term.GetWinsize(cli.terminalFd)
  1359. if err != nil {
  1360. utils.Debugf("Error getting size: %s", err)
  1361. if ws == nil {
  1362. return 0, 0
  1363. }
  1364. }
  1365. return int(ws.Height), int(ws.Width)
  1366. }
  1367. func (cli *DockerCli) resizeTty(id string) {
  1368. height, width := cli.getTtySize()
  1369. if height == 0 && width == 0 {
  1370. return
  1371. }
  1372. v := url.Values{}
  1373. v.Set("h", strconv.Itoa(height))
  1374. v.Set("w", strconv.Itoa(width))
  1375. if _, _, err := cli.call("POST", "/containers/"+id+"/resize?"+v.Encode(), nil); err != nil {
  1376. utils.Debugf("Error resize: %s", err)
  1377. }
  1378. }
  1379. func (cli *DockerCli) monitorTtySize(id string) error {
  1380. if !cli.isTerminal {
  1381. return fmt.Errorf("Impossible to monitor size on non-tty")
  1382. }
  1383. cli.resizeTty(id)
  1384. c := make(chan os.Signal, 1)
  1385. signal.Notify(c, syscall.SIGWINCH)
  1386. go func() {
  1387. for sig := range c {
  1388. if sig == syscall.SIGWINCH {
  1389. cli.resizeTty(id)
  1390. }
  1391. }
  1392. }()
  1393. return nil
  1394. }
  1395. func Subcmd(name, signature, description string) *flag.FlagSet {
  1396. flags := flag.NewFlagSet(name, flag.ContinueOnError)
  1397. flags.Usage = func() {
  1398. // FIXME: use custom stdout or return error
  1399. fmt.Fprintf(os.Stdout, "\nUsage: docker %s %s\n\n%s\n\n", name, signature, description)
  1400. flags.PrintDefaults()
  1401. }
  1402. return flags
  1403. }
  1404. func NewDockerCli(in io.ReadCloser, out, err io.Writer, proto, addr string) *DockerCli {
  1405. var (
  1406. isTerminal = false
  1407. terminalFd uintptr
  1408. )
  1409. if in != nil {
  1410. if file, ok := in.(*os.File); ok {
  1411. terminalFd = file.Fd()
  1412. isTerminal = term.IsTerminal(terminalFd)
  1413. }
  1414. }
  1415. if err == nil {
  1416. err = out
  1417. }
  1418. authConfig, _ := auth.LoadConfig(os.Getenv("HOME"))
  1419. return &DockerCli{
  1420. proto: proto,
  1421. addr: addr,
  1422. authConfig: authConfig,
  1423. in: in,
  1424. out: out,
  1425. err: err,
  1426. isTerminal: isTerminal,
  1427. terminalFd: terminalFd,
  1428. }
  1429. }
  1430. type DockerCli struct {
  1431. proto string
  1432. addr string
  1433. authConfig *auth.AuthConfig
  1434. in io.ReadCloser
  1435. out io.Writer
  1436. err io.Writer
  1437. isTerminal bool
  1438. terminalFd uintptr
  1439. }