client.go 65 KB

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