commands.go 46 KB

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