commands.go 36 KB

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