commands.go 45 KB

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