commands.go 66 KB

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