commands.go 37 KB

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