commands.go 41 KB

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