commands.go 37 KB

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