commands.go 36 KB

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