commands.go 43 KB

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