commands.go 41 KB

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