commands.go 42 KB

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