commands.go 39 KB

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