commands.go 45 KB

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