commands.go 45 KB

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