commands.go 54 KB

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