commands.go 36 KB

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