commands.go 39 KB

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