commands.go 43 KB

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