commands.go 42 KB

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