commands.go 42 KB

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