commands.go 36 KB

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