commands.go 47 KB

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