commands.go 37 KB

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