commands.go 37 KB

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