commands.go 42 KB

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