client.go 65 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420
  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 the verbose output generated by the containers")
  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. var (
  713. cmd = cli.Subcmd("rmi", "IMAGE [IMAGE...]", "Remove one or more images")
  714. force = cmd.Bool([]string{"f", "-force"}, false, "Force")
  715. )
  716. if err := cmd.Parse(args); err != nil {
  717. return nil
  718. }
  719. if cmd.NArg() < 1 {
  720. cmd.Usage()
  721. return nil
  722. }
  723. v := url.Values{}
  724. if *force {
  725. v.Set("force", "1")
  726. }
  727. var encounteredError error
  728. for _, name := range cmd.Args() {
  729. body, _, err := readBody(cli.call("DELETE", "/images/"+name+"?"+v.Encode(), nil, false))
  730. if err != nil {
  731. fmt.Fprintf(cli.err, "%s\n", err)
  732. encounteredError = fmt.Errorf("Error: failed to remove one or more images")
  733. } else {
  734. outs := engine.NewTable("Created", 0)
  735. if _, err := outs.ReadListFrom(body); err != nil {
  736. fmt.Fprintf(cli.err, "%s\n", err)
  737. encounteredError = fmt.Errorf("Error: failed to remove one or more images")
  738. continue
  739. }
  740. for _, out := range outs.Data {
  741. if out.Get("Deleted") != "" {
  742. fmt.Fprintf(cli.out, "Deleted: %s\n", out.Get("Deleted"))
  743. } else {
  744. fmt.Fprintf(cli.out, "Untagged: %s\n", out.Get("Untagged"))
  745. }
  746. }
  747. }
  748. }
  749. return encounteredError
  750. }
  751. func (cli *DockerCli) CmdHistory(args ...string) error {
  752. cmd := cli.Subcmd("history", "[OPTIONS] IMAGE", "Show the history of an image")
  753. quiet := cmd.Bool([]string{"q", "-quiet"}, false, "only show numeric IDs")
  754. noTrunc := cmd.Bool([]string{"#notrunc", "-no-trunc"}, false, "Don't truncate output")
  755. if err := cmd.Parse(args); err != nil {
  756. return nil
  757. }
  758. if cmd.NArg() != 1 {
  759. cmd.Usage()
  760. return nil
  761. }
  762. body, _, err := readBody(cli.call("GET", "/images/"+cmd.Arg(0)+"/history", nil, false))
  763. if err != nil {
  764. return err
  765. }
  766. outs := engine.NewTable("Created", 0)
  767. if _, err := outs.ReadListFrom(body); err != nil {
  768. return err
  769. }
  770. w := tabwriter.NewWriter(cli.out, 20, 1, 3, ' ', 0)
  771. if !*quiet {
  772. fmt.Fprintln(w, "IMAGE\tCREATED\tCREATED BY\tSIZE")
  773. }
  774. for _, out := range outs.Data {
  775. outID := out.Get("Id")
  776. if !*quiet {
  777. if *noTrunc {
  778. fmt.Fprintf(w, "%s\t", outID)
  779. } else {
  780. fmt.Fprintf(w, "%s\t", utils.TruncateID(outID))
  781. }
  782. fmt.Fprintf(w, "%s ago\t", utils.HumanDuration(time.Now().UTC().Sub(time.Unix(out.GetInt64("Created"), 0))))
  783. if *noTrunc {
  784. fmt.Fprintf(w, "%s\t", out.Get("CreatedBy"))
  785. } else {
  786. fmt.Fprintf(w, "%s\t", utils.Trunc(out.Get("CreatedBy"), 45))
  787. }
  788. fmt.Fprintf(w, "%s\n", utils.HumanSize(out.GetInt64("Size")))
  789. } else {
  790. if *noTrunc {
  791. fmt.Fprintln(w, outID)
  792. } else {
  793. fmt.Fprintln(w, utils.TruncateID(outID))
  794. }
  795. }
  796. }
  797. w.Flush()
  798. return nil
  799. }
  800. func (cli *DockerCli) CmdRm(args ...string) error {
  801. cmd := cli.Subcmd("rm", "[OPTIONS] CONTAINER [CONTAINER...]", "Remove one or more containers")
  802. v := cmd.Bool([]string{"v", "-volumes"}, false, "Remove the volumes associated to the container")
  803. link := cmd.Bool([]string{"l", "#link", "-link"}, false, "Remove the specified link and not the underlying container")
  804. if err := cmd.Parse(args); err != nil {
  805. return nil
  806. }
  807. if cmd.NArg() < 1 {
  808. cmd.Usage()
  809. return nil
  810. }
  811. val := url.Values{}
  812. if *v {
  813. val.Set("v", "1")
  814. }
  815. if *link {
  816. val.Set("link", "1")
  817. }
  818. var encounteredError error
  819. for _, name := range cmd.Args() {
  820. _, _, err := readBody(cli.call("DELETE", "/containers/"+name+"?"+val.Encode(), nil, false))
  821. if err != nil {
  822. fmt.Fprintf(cli.err, "%s\n", err)
  823. encounteredError = fmt.Errorf("Error: failed to remove one or more containers")
  824. } else {
  825. fmt.Fprintf(cli.out, "%s\n", name)
  826. }
  827. }
  828. return encounteredError
  829. }
  830. // 'docker kill NAME' kills a running container
  831. func (cli *DockerCli) CmdKill(args ...string) error {
  832. cmd := cli.Subcmd("kill", "[OPTIONS] CONTAINER [CONTAINER...]", "Kill a running container (send SIGKILL, or specified signal)")
  833. signal := cmd.String([]string{"s", "-signal"}, "KILL", "Signal to send to the container")
  834. if err := cmd.Parse(args); err != nil {
  835. return nil
  836. }
  837. if cmd.NArg() < 1 {
  838. cmd.Usage()
  839. return nil
  840. }
  841. var encounteredError error
  842. for _, name := range cmd.Args() {
  843. if _, _, err := readBody(cli.call("POST", fmt.Sprintf("/containers/%s/kill?signal=%s", name, *signal), nil, false)); err != nil {
  844. fmt.Fprintf(cli.err, "%s\n", err)
  845. encounteredError = fmt.Errorf("Error: failed to kill one or more containers")
  846. } else {
  847. fmt.Fprintf(cli.out, "%s\n", name)
  848. }
  849. }
  850. return encounteredError
  851. }
  852. func (cli *DockerCli) CmdImport(args ...string) error {
  853. 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.")
  854. if err := cmd.Parse(args); err != nil {
  855. return nil
  856. }
  857. if cmd.NArg() < 1 {
  858. cmd.Usage()
  859. return nil
  860. }
  861. var src, repository, tag string
  862. if cmd.NArg() == 3 {
  863. fmt.Fprintf(cli.err, "[DEPRECATED] The format 'URL|- [REPOSITORY [TAG]]' as been deprecated. Please use URL|- [REPOSITORY[:TAG]]\n")
  864. src, repository, tag = cmd.Arg(0), cmd.Arg(1), cmd.Arg(2)
  865. } else {
  866. src = cmd.Arg(0)
  867. repository, tag = utils.ParseRepositoryTag(cmd.Arg(1))
  868. }
  869. v := url.Values{}
  870. v.Set("repo", repository)
  871. v.Set("tag", tag)
  872. v.Set("fromSrc", src)
  873. var in io.Reader
  874. if src == "-" {
  875. in = cli.in
  876. }
  877. return cli.stream("POST", "/images/create?"+v.Encode(), in, cli.out, nil)
  878. }
  879. func (cli *DockerCli) CmdPush(args ...string) error {
  880. cmd := cli.Subcmd("push", "NAME", "Push an image or a repository to the registry")
  881. if err := cmd.Parse(args); err != nil {
  882. return nil
  883. }
  884. name := cmd.Arg(0)
  885. if name == "" {
  886. cmd.Usage()
  887. return nil
  888. }
  889. cli.LoadConfigFile()
  890. // Resolve the Repository name from fqn to endpoint + name
  891. endpoint, _, err := registry.ResolveRepositoryName(name)
  892. if err != nil {
  893. return err
  894. }
  895. // Resolve the Auth config relevant for this server
  896. authConfig := cli.configFile.ResolveAuthConfig(endpoint)
  897. // If we're not using a custom registry, we know the restrictions
  898. // applied to repository names and can warn the user in advance.
  899. // Custom repositories can have different rules, and we must also
  900. // allow pushing by image ID.
  901. if len(strings.SplitN(name, "/", 2)) == 1 {
  902. username := cli.configFile.Configs[auth.IndexServerAddress()].Username
  903. if username == "" {
  904. username = "<user>"
  905. }
  906. return fmt.Errorf("Impossible to push a \"root\" repository. Please rename your repository in <user>/<repo> (ex: %s/%s)", username, name)
  907. }
  908. v := url.Values{}
  909. push := func(authConfig auth.AuthConfig) error {
  910. buf, err := json.Marshal(authConfig)
  911. if err != nil {
  912. return err
  913. }
  914. registryAuthHeader := []string{
  915. base64.URLEncoding.EncodeToString(buf),
  916. }
  917. return cli.stream("POST", "/images/"+name+"/push?"+v.Encode(), nil, cli.out, map[string][]string{
  918. "X-Registry-Auth": registryAuthHeader,
  919. })
  920. }
  921. if err := push(authConfig); err != nil {
  922. if strings.Contains(err.Error(), "Status 401") {
  923. fmt.Fprintln(cli.out, "\nPlease login prior to push:")
  924. if err := cli.CmdLogin(endpoint); err != nil {
  925. return err
  926. }
  927. authConfig := cli.configFile.ResolveAuthConfig(endpoint)
  928. return push(authConfig)
  929. }
  930. return err
  931. }
  932. return nil
  933. }
  934. func (cli *DockerCli) CmdPull(args ...string) error {
  935. cmd := cli.Subcmd("pull", "NAME", "Pull an image or a repository from the registry")
  936. tag := cmd.String([]string{"t", "-tag"}, "", "Download tagged image in repository")
  937. if err := cmd.Parse(args); err != nil {
  938. return nil
  939. }
  940. if cmd.NArg() != 1 {
  941. cmd.Usage()
  942. return nil
  943. }
  944. remote, parsedTag := utils.ParseRepositoryTag(cmd.Arg(0))
  945. if *tag == "" {
  946. *tag = parsedTag
  947. }
  948. // Resolve the Repository name from fqn to endpoint + name
  949. endpoint, _, err := registry.ResolveRepositoryName(remote)
  950. if err != nil {
  951. return err
  952. }
  953. cli.LoadConfigFile()
  954. // Resolve the Auth config relevant for this server
  955. authConfig := cli.configFile.ResolveAuthConfig(endpoint)
  956. v := url.Values{}
  957. v.Set("fromImage", remote)
  958. v.Set("tag", *tag)
  959. pull := func(authConfig auth.AuthConfig) error {
  960. buf, err := json.Marshal(authConfig)
  961. if err != nil {
  962. return err
  963. }
  964. registryAuthHeader := []string{
  965. base64.URLEncoding.EncodeToString(buf),
  966. }
  967. return cli.stream("POST", "/images/create?"+v.Encode(), nil, cli.out, map[string][]string{
  968. "X-Registry-Auth": registryAuthHeader,
  969. })
  970. }
  971. if err := pull(authConfig); err != nil {
  972. if strings.Contains(err.Error(), "Status 401") {
  973. fmt.Fprintln(cli.out, "\nPlease login prior to pull:")
  974. if err := cli.CmdLogin(endpoint); err != nil {
  975. return err
  976. }
  977. authConfig := cli.configFile.ResolveAuthConfig(endpoint)
  978. return pull(authConfig)
  979. }
  980. return err
  981. }
  982. return nil
  983. }
  984. func (cli *DockerCli) CmdImages(args ...string) error {
  985. cmd := cli.Subcmd("images", "[OPTIONS] [NAME]", "List images")
  986. quiet := cmd.Bool([]string{"q", "-quiet"}, false, "only show numeric IDs")
  987. all := cmd.Bool([]string{"a", "-all"}, false, "show all images (by default filter out the intermediate images used to build)")
  988. noTrunc := cmd.Bool([]string{"#notrunc", "-no-trunc"}, false, "Don't truncate output")
  989. flViz := cmd.Bool([]string{"v", "#viz", "-viz"}, false, "output graph in graphviz format")
  990. flTree := cmd.Bool([]string{"t", "#tree", "-tree"}, false, "output graph in tree format")
  991. if err := cmd.Parse(args); err != nil {
  992. return nil
  993. }
  994. if cmd.NArg() > 1 {
  995. cmd.Usage()
  996. return nil
  997. }
  998. filter := cmd.Arg(0)
  999. if *flViz || *flTree {
  1000. body, _, err := readBody(cli.call("GET", "/images/json?all=1", nil, false))
  1001. if err != nil {
  1002. return err
  1003. }
  1004. outs := engine.NewTable("Created", 0)
  1005. if _, err := outs.ReadListFrom(body); err != nil {
  1006. return err
  1007. }
  1008. var (
  1009. printNode func(cli *DockerCli, noTrunc bool, image *engine.Env, prefix string)
  1010. startImage *engine.Env
  1011. roots = engine.NewTable("Created", outs.Len())
  1012. byParent = make(map[string]*engine.Table)
  1013. )
  1014. for _, image := range outs.Data {
  1015. if image.Get("ParentId") == "" {
  1016. roots.Add(image)
  1017. } else {
  1018. if children, exists := byParent[image.Get("ParentId")]; exists {
  1019. children.Add(image)
  1020. } else {
  1021. byParent[image.Get("ParentId")] = engine.NewTable("Created", 1)
  1022. byParent[image.Get("ParentId")].Add(image)
  1023. }
  1024. }
  1025. if filter != "" {
  1026. if filter == image.Get("Id") || filter == utils.TruncateID(image.Get("Id")) {
  1027. startImage = image
  1028. }
  1029. for _, repotag := range image.GetList("RepoTags") {
  1030. if repotag == filter {
  1031. startImage = image
  1032. }
  1033. }
  1034. }
  1035. }
  1036. if *flViz {
  1037. fmt.Fprintf(cli.out, "digraph docker {\n")
  1038. printNode = (*DockerCli).printVizNode
  1039. } else {
  1040. printNode = (*DockerCli).printTreeNode
  1041. }
  1042. if startImage != nil {
  1043. root := engine.NewTable("Created", 1)
  1044. root.Add(startImage)
  1045. cli.WalkTree(*noTrunc, root, byParent, "", printNode)
  1046. } else if filter == "" {
  1047. cli.WalkTree(*noTrunc, roots, byParent, "", printNode)
  1048. }
  1049. if *flViz {
  1050. fmt.Fprintf(cli.out, " base [style=invisible]\n}\n")
  1051. }
  1052. } else {
  1053. v := url.Values{}
  1054. if cmd.NArg() == 1 {
  1055. v.Set("filter", filter)
  1056. }
  1057. if *all {
  1058. v.Set("all", "1")
  1059. }
  1060. body, _, err := readBody(cli.call("GET", "/images/json?"+v.Encode(), nil, false))
  1061. if err != nil {
  1062. return err
  1063. }
  1064. outs := engine.NewTable("Created", 0)
  1065. if _, err := outs.ReadListFrom(body); err != nil {
  1066. return err
  1067. }
  1068. w := tabwriter.NewWriter(cli.out, 20, 1, 3, ' ', 0)
  1069. if !*quiet {
  1070. fmt.Fprintln(w, "REPOSITORY\tTAG\tIMAGE ID\tCREATED\tVIRTUAL SIZE")
  1071. }
  1072. for _, out := range outs.Data {
  1073. for _, repotag := range out.GetList("RepoTags") {
  1074. repo, tag := utils.ParseRepositoryTag(repotag)
  1075. outID := out.Get("Id")
  1076. if !*noTrunc {
  1077. outID = utils.TruncateID(outID)
  1078. }
  1079. if !*quiet {
  1080. 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")))
  1081. } else {
  1082. fmt.Fprintln(w, outID)
  1083. }
  1084. }
  1085. }
  1086. if !*quiet {
  1087. w.Flush()
  1088. }
  1089. }
  1090. return nil
  1091. }
  1092. 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)) {
  1093. length := images.Len()
  1094. if length > 1 {
  1095. for index, image := range images.Data {
  1096. if index+1 == length {
  1097. printNode(cli, noTrunc, image, prefix+"└─")
  1098. if subimages, exists := byParent[image.Get("Id")]; exists {
  1099. cli.WalkTree(noTrunc, subimages, byParent, prefix+" ", printNode)
  1100. }
  1101. } else {
  1102. printNode(cli, noTrunc, image, prefix+"\u251C─")
  1103. if subimages, exists := byParent[image.Get("Id")]; exists {
  1104. cli.WalkTree(noTrunc, subimages, byParent, prefix+"\u2502 ", printNode)
  1105. }
  1106. }
  1107. }
  1108. } else {
  1109. for _, image := range images.Data {
  1110. printNode(cli, noTrunc, image, prefix+"└─")
  1111. if subimages, exists := byParent[image.Get("Id")]; exists {
  1112. cli.WalkTree(noTrunc, subimages, byParent, prefix+" ", printNode)
  1113. }
  1114. }
  1115. }
  1116. }
  1117. func (cli *DockerCli) printVizNode(noTrunc bool, image *engine.Env, prefix string) {
  1118. var (
  1119. imageID string
  1120. parentID string
  1121. )
  1122. if noTrunc {
  1123. imageID = image.Get("Id")
  1124. parentID = image.Get("ParentId")
  1125. } else {
  1126. imageID = utils.TruncateID(image.Get("Id"))
  1127. parentID = utils.TruncateID(image.Get("ParentId"))
  1128. }
  1129. if parentID == "" {
  1130. fmt.Fprintf(cli.out, " base -> \"%s\" [style=invis]\n", imageID)
  1131. } else {
  1132. fmt.Fprintf(cli.out, " \"%s\" -> \"%s\"\n", parentID, imageID)
  1133. }
  1134. if image.GetList("RepoTags")[0] != "<none>:<none>" {
  1135. fmt.Fprintf(cli.out, " \"%s\" [label=\"%s\\n%s\",shape=box,fillcolor=\"paleturquoise\",style=\"filled,rounded\"];\n",
  1136. imageID, imageID, strings.Join(image.GetList("RepoTags"), "\\n"))
  1137. }
  1138. }
  1139. func (cli *DockerCli) printTreeNode(noTrunc bool, image *engine.Env, prefix string) {
  1140. var imageID string
  1141. if noTrunc {
  1142. imageID = image.Get("Id")
  1143. } else {
  1144. imageID = utils.TruncateID(image.Get("Id"))
  1145. }
  1146. fmt.Fprintf(cli.out, "%s%s Virtual Size: %s", prefix, imageID, utils.HumanSize(image.GetInt64("VirtualSize")))
  1147. if image.GetList("RepoTags")[0] != "<none>:<none>" {
  1148. fmt.Fprintf(cli.out, " Tags: %s\n", strings.Join(image.GetList("RepoTags"), ", "))
  1149. } else {
  1150. fmt.Fprint(cli.out, "\n")
  1151. }
  1152. }
  1153. func (cli *DockerCli) CmdPs(args ...string) error {
  1154. cmd := cli.Subcmd("ps", "[OPTIONS]", "List containers")
  1155. quiet := cmd.Bool([]string{"q", "-quiet"}, false, "Only display numeric IDs")
  1156. size := cmd.Bool([]string{"s", "-size"}, false, "Display sizes")
  1157. all := cmd.Bool([]string{"a", "-all"}, false, "Show all containers. Only running containers are shown by default.")
  1158. noTrunc := cmd.Bool([]string{"#notrunc", "-no-trunc"}, false, "Don't truncate output")
  1159. nLatest := cmd.Bool([]string{"l", "-latest"}, false, "Show only the latest created container, include non-running ones.")
  1160. since := cmd.String([]string{"#sinceId", "-since-id"}, "", "Show only containers created since Id, include non-running ones.")
  1161. before := cmd.String([]string{"#beforeId", "-before-id"}, "", "Show only container created before Id, include non-running ones.")
  1162. last := cmd.Int([]string{"n"}, -1, "Show n last created containers, include non-running ones.")
  1163. if err := cmd.Parse(args); err != nil {
  1164. return nil
  1165. }
  1166. v := url.Values{}
  1167. if *last == -1 && *nLatest {
  1168. *last = 1
  1169. }
  1170. if *all {
  1171. v.Set("all", "1")
  1172. }
  1173. if *last != -1 {
  1174. v.Set("limit", strconv.Itoa(*last))
  1175. }
  1176. if *since != "" {
  1177. v.Set("since", *since)
  1178. }
  1179. if *before != "" {
  1180. v.Set("before", *before)
  1181. }
  1182. if *size {
  1183. v.Set("size", "1")
  1184. }
  1185. body, _, err := readBody(cli.call("GET", "/containers/json?"+v.Encode(), nil, false))
  1186. if err != nil {
  1187. return err
  1188. }
  1189. outs := engine.NewTable("Created", 0)
  1190. if _, err := outs.ReadListFrom(body); err != nil {
  1191. return err
  1192. }
  1193. w := tabwriter.NewWriter(cli.out, 20, 1, 3, ' ', 0)
  1194. if !*quiet {
  1195. fmt.Fprint(w, "CONTAINER ID\tIMAGE\tCOMMAND\tCREATED\tSTATUS\tPORTS\tNAMES")
  1196. if *size {
  1197. fmt.Fprintln(w, "\tSIZE")
  1198. } else {
  1199. fmt.Fprint(w, "\n")
  1200. }
  1201. }
  1202. for _, out := range outs.Data {
  1203. var (
  1204. outID = out.Get("Id")
  1205. outNames = out.GetList("Names")
  1206. )
  1207. if !*noTrunc {
  1208. outID = utils.TruncateID(outID)
  1209. }
  1210. // Remove the leading / from the names
  1211. for i := 0; i < len(outNames); i++ {
  1212. outNames[i] = outNames[i][1:]
  1213. }
  1214. if !*quiet {
  1215. var (
  1216. outCommand = out.Get("Command")
  1217. ports = engine.NewTable("", 0)
  1218. )
  1219. if !*noTrunc {
  1220. outCommand = utils.Trunc(outCommand, 20)
  1221. }
  1222. ports.ReadListFrom([]byte(out.Get("Ports")))
  1223. 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, ","))
  1224. if *size {
  1225. if out.GetInt("SizeRootFs") > 0 {
  1226. fmt.Fprintf(w, "%s (virtual %s)\n", utils.HumanSize(out.GetInt64("SizeRw")), utils.HumanSize(out.GetInt64("SizeRootFs")))
  1227. } else {
  1228. fmt.Fprintf(w, "%s\n", utils.HumanSize(out.GetInt64("SizeRw")))
  1229. }
  1230. } else {
  1231. fmt.Fprint(w, "\n")
  1232. }
  1233. } else {
  1234. fmt.Fprintln(w, outID)
  1235. }
  1236. }
  1237. if !*quiet {
  1238. w.Flush()
  1239. }
  1240. return nil
  1241. }
  1242. func (cli *DockerCli) CmdCommit(args ...string) error {
  1243. cmd := cli.Subcmd("commit", "[OPTIONS] CONTAINER [REPOSITORY[:TAG]]", "Create a new image from a container's changes")
  1244. flComment := cmd.String([]string{"m", "-message"}, "", "Commit message")
  1245. flAuthor := cmd.String([]string{"a", "#author", "-author"}, "", "Author (eg. \"John Hannibal Smith <hannibal@a-team.com>\"")
  1246. flConfig := cmd.String([]string{"#run", "-run"}, "", "Config automatically applied when the image is run. "+`(ex: -run='{"Cmd": ["cat", "/world"], "PortSpecs": ["22"]}')`)
  1247. if err := cmd.Parse(args); err != nil {
  1248. return nil
  1249. }
  1250. var name, repository, tag string
  1251. if cmd.NArg() == 3 {
  1252. fmt.Fprintf(cli.err, "[DEPRECATED] The format 'CONTAINER [REPOSITORY [TAG]]' as been deprecated. Please use CONTAINER [REPOSITORY[:TAG]]\n")
  1253. name, repository, tag = cmd.Arg(0), cmd.Arg(1), cmd.Arg(2)
  1254. } else {
  1255. name = cmd.Arg(0)
  1256. repository, tag = utils.ParseRepositoryTag(cmd.Arg(1))
  1257. }
  1258. if name == "" {
  1259. cmd.Usage()
  1260. return nil
  1261. }
  1262. v := url.Values{}
  1263. v.Set("container", name)
  1264. v.Set("repo", repository)
  1265. v.Set("tag", tag)
  1266. v.Set("comment", *flComment)
  1267. v.Set("author", *flAuthor)
  1268. var (
  1269. config *runconfig.Config
  1270. env engine.Env
  1271. )
  1272. if *flConfig != "" {
  1273. config = &runconfig.Config{}
  1274. if err := json.Unmarshal([]byte(*flConfig), config); err != nil {
  1275. return err
  1276. }
  1277. }
  1278. stream, _, err := cli.call("POST", "/commit?"+v.Encode(), config, false)
  1279. if err != nil {
  1280. return err
  1281. }
  1282. if err := env.Decode(stream); err != nil {
  1283. return err
  1284. }
  1285. fmt.Fprintf(cli.out, "%s\n", env.Get("Id"))
  1286. return nil
  1287. }
  1288. func (cli *DockerCli) CmdEvents(args ...string) error {
  1289. cmd := cli.Subcmd("events", "[OPTIONS]", "Get real time events from the server")
  1290. since := cmd.String([]string{"#since", "-since"}, "", "Show previously created events and then stream.")
  1291. if err := cmd.Parse(args); err != nil {
  1292. return nil
  1293. }
  1294. if cmd.NArg() != 0 {
  1295. cmd.Usage()
  1296. return nil
  1297. }
  1298. v := url.Values{}
  1299. if *since != "" {
  1300. loc := time.FixedZone(time.Now().Zone())
  1301. format := "2006-01-02 15:04:05 -0700 MST"
  1302. if len(*since) < len(format) {
  1303. format = format[:len(*since)]
  1304. }
  1305. if t, err := time.ParseInLocation(format, *since, loc); err == nil {
  1306. v.Set("since", strconv.FormatInt(t.Unix(), 10))
  1307. } else {
  1308. v.Set("since", *since)
  1309. }
  1310. }
  1311. if err := cli.stream("GET", "/events?"+v.Encode(), nil, cli.out, nil); err != nil {
  1312. return err
  1313. }
  1314. return nil
  1315. }
  1316. func (cli *DockerCli) CmdExport(args ...string) error {
  1317. cmd := cli.Subcmd("export", "CONTAINER", "Export the contents of a filesystem as a tar archive to STDOUT")
  1318. if err := cmd.Parse(args); err != nil {
  1319. return nil
  1320. }
  1321. if cmd.NArg() != 1 {
  1322. cmd.Usage()
  1323. return nil
  1324. }
  1325. if err := cli.stream("GET", "/containers/"+cmd.Arg(0)+"/export", nil, cli.out, nil); err != nil {
  1326. return err
  1327. }
  1328. return nil
  1329. }
  1330. func (cli *DockerCli) CmdDiff(args ...string) error {
  1331. cmd := cli.Subcmd("diff", "CONTAINER", "Inspect changes on a container's filesystem")
  1332. if err := cmd.Parse(args); err != nil {
  1333. return nil
  1334. }
  1335. if cmd.NArg() != 1 {
  1336. cmd.Usage()
  1337. return nil
  1338. }
  1339. body, _, err := readBody(cli.call("GET", "/containers/"+cmd.Arg(0)+"/changes", nil, false))
  1340. if err != nil {
  1341. return err
  1342. }
  1343. outs := engine.NewTable("", 0)
  1344. if _, err := outs.ReadListFrom(body); err != nil {
  1345. return err
  1346. }
  1347. for _, change := range outs.Data {
  1348. var kind string
  1349. switch change.GetInt("Kind") {
  1350. case archive.ChangeModify:
  1351. kind = "C"
  1352. case archive.ChangeAdd:
  1353. kind = "A"
  1354. case archive.ChangeDelete:
  1355. kind = "D"
  1356. }
  1357. fmt.Fprintf(cli.out, "%s %s\n", kind, change.Get("Path"))
  1358. }
  1359. return nil
  1360. }
  1361. func (cli *DockerCli) CmdLogs(args ...string) error {
  1362. cmd := cli.Subcmd("logs", "CONTAINER", "Fetch the logs of a container")
  1363. follow := cmd.Bool([]string{"f", "-follow"}, false, "Follow log output")
  1364. if err := cmd.Parse(args); err != nil {
  1365. return nil
  1366. }
  1367. if cmd.NArg() != 1 {
  1368. cmd.Usage()
  1369. return nil
  1370. }
  1371. name := cmd.Arg(0)
  1372. body, _, err := readBody(cli.call("GET", "/containers/"+name+"/json", nil, false))
  1373. if err != nil {
  1374. return err
  1375. }
  1376. container := &Container{}
  1377. err = json.Unmarshal(body, container)
  1378. if err != nil {
  1379. return err
  1380. }
  1381. v := url.Values{}
  1382. v.Set("logs", "1")
  1383. v.Set("stdout", "1")
  1384. v.Set("stderr", "1")
  1385. if *follow && container.State.Running {
  1386. v.Set("stream", "1")
  1387. }
  1388. if err := cli.hijack("POST", "/containers/"+name+"/attach?"+v.Encode(), container.Config.Tty, nil, cli.out, cli.err, nil); err != nil {
  1389. return err
  1390. }
  1391. return nil
  1392. }
  1393. func (cli *DockerCli) CmdAttach(args ...string) error {
  1394. cmd := cli.Subcmd("attach", "[OPTIONS] CONTAINER", "Attach to a running container")
  1395. noStdin := cmd.Bool([]string{"#nostdin", "-no-stdin"}, false, "Do not attach stdin")
  1396. proxy := cmd.Bool([]string{"#sig-proxy", "-sig-proxy"}, true, "Proxify all received signal to the process (even in non-tty mode)")
  1397. if err := cmd.Parse(args); err != nil {
  1398. return nil
  1399. }
  1400. if cmd.NArg() != 1 {
  1401. cmd.Usage()
  1402. return nil
  1403. }
  1404. name := cmd.Arg(0)
  1405. body, _, err := readBody(cli.call("GET", "/containers/"+name+"/json", nil, false))
  1406. if err != nil {
  1407. return err
  1408. }
  1409. container := &Container{}
  1410. err = json.Unmarshal(body, container)
  1411. if err != nil {
  1412. return err
  1413. }
  1414. if !container.State.Running {
  1415. return fmt.Errorf("Impossible to attach to a stopped container, start it first")
  1416. }
  1417. if container.Config.Tty && cli.isTerminal {
  1418. if err := cli.monitorTtySize(cmd.Arg(0)); err != nil {
  1419. utils.Debugf("Error monitoring TTY size: %s", err)
  1420. }
  1421. }
  1422. var in io.ReadCloser
  1423. v := url.Values{}
  1424. v.Set("stream", "1")
  1425. if !*noStdin && container.Config.OpenStdin {
  1426. v.Set("stdin", "1")
  1427. in = cli.in
  1428. }
  1429. v.Set("stdout", "1")
  1430. v.Set("stderr", "1")
  1431. if *proxy && !container.Config.Tty {
  1432. sigc := cli.forwardAllSignals(cmd.Arg(0))
  1433. defer utils.StopCatch(sigc)
  1434. }
  1435. if err := cli.hijack("POST", "/containers/"+cmd.Arg(0)+"/attach?"+v.Encode(), container.Config.Tty, in, cli.out, cli.err, nil); err != nil {
  1436. return err
  1437. }
  1438. _, status, err := getExitCode(cli, cmd.Arg(0))
  1439. if err != nil {
  1440. return err
  1441. }
  1442. if status != 0 {
  1443. return &utils.StatusError{StatusCode: status}
  1444. }
  1445. return nil
  1446. }
  1447. func (cli *DockerCli) CmdSearch(args ...string) error {
  1448. cmd := cli.Subcmd("search", "TERM", "Search the docker index for images")
  1449. noTrunc := cmd.Bool([]string{"#notrunc", "-no-trunc"}, false, "Don't truncate output")
  1450. trusted := cmd.Bool([]string{"t", "#trusted", "-trusted"}, false, "Only show trusted builds")
  1451. stars := cmd.Int([]string{"s", "#stars", "-stars"}, 0, "Only displays with at least xxx stars")
  1452. if err := cmd.Parse(args); err != nil {
  1453. return nil
  1454. }
  1455. if cmd.NArg() != 1 {
  1456. cmd.Usage()
  1457. return nil
  1458. }
  1459. v := url.Values{}
  1460. v.Set("term", cmd.Arg(0))
  1461. body, _, err := readBody(cli.call("GET", "/images/search?"+v.Encode(), nil, true))
  1462. if err != nil {
  1463. return err
  1464. }
  1465. outs := engine.NewTable("star_count", 0)
  1466. if _, err := outs.ReadListFrom(body); err != nil {
  1467. return err
  1468. }
  1469. w := tabwriter.NewWriter(cli.out, 10, 1, 3, ' ', 0)
  1470. fmt.Fprintf(w, "NAME\tDESCRIPTION\tSTARS\tOFFICIAL\tTRUSTED\n")
  1471. for _, out := range outs.Data {
  1472. if (*trusted && !out.GetBool("is_trusted")) || (*stars > out.GetInt("star_count")) {
  1473. continue
  1474. }
  1475. desc := strings.Replace(out.Get("description"), "\n", " ", -1)
  1476. desc = strings.Replace(desc, "\r", " ", -1)
  1477. if !*noTrunc && len(desc) > 45 {
  1478. desc = utils.Trunc(desc, 42) + "..."
  1479. }
  1480. fmt.Fprintf(w, "%s\t%s\t%d\t", out.Get("name"), desc, out.GetInt("star_count"))
  1481. if out.GetBool("is_official") {
  1482. fmt.Fprint(w, "[OK]")
  1483. }
  1484. fmt.Fprint(w, "\t")
  1485. if out.GetBool("is_trusted") {
  1486. fmt.Fprint(w, "[OK]")
  1487. }
  1488. fmt.Fprint(w, "\n")
  1489. }
  1490. w.Flush()
  1491. return nil
  1492. }
  1493. // Ports type - Used to parse multiple -p flags
  1494. type ports []int
  1495. func (cli *DockerCli) CmdTag(args ...string) error {
  1496. cmd := cli.Subcmd("tag", "[OPTIONS] IMAGE [REGISTRYHOST/][USERNAME/]NAME[:TAG]", "Tag an image into a repository")
  1497. force := cmd.Bool([]string{"f", "#force", "-force"}, false, "Force")
  1498. if err := cmd.Parse(args); err != nil {
  1499. return nil
  1500. }
  1501. if cmd.NArg() != 2 && cmd.NArg() != 3 {
  1502. cmd.Usage()
  1503. return nil
  1504. }
  1505. var repository, tag string
  1506. if cmd.NArg() == 3 {
  1507. fmt.Fprintf(cli.err, "[DEPRECATED] The format 'IMAGE [REPOSITORY [TAG]]' as been deprecated. Please use IMAGE [REGISTRYHOST/][USERNAME/]NAME[:TAG]]\n")
  1508. repository, tag = cmd.Arg(1), cmd.Arg(2)
  1509. } else {
  1510. repository, tag = utils.ParseRepositoryTag(cmd.Arg(1))
  1511. }
  1512. v := url.Values{}
  1513. v.Set("repo", repository)
  1514. v.Set("tag", tag)
  1515. if *force {
  1516. v.Set("force", "1")
  1517. }
  1518. if _, _, err := readBody(cli.call("POST", "/images/"+cmd.Arg(0)+"/tag?"+v.Encode(), nil, false)); err != nil {
  1519. return err
  1520. }
  1521. return nil
  1522. }
  1523. func (cli *DockerCli) CmdRun(args ...string) error {
  1524. // FIXME: just use runconfig.Parse already
  1525. config, hostConfig, cmd, err := runconfig.ParseSubcommand(cli.Subcmd("run", "[OPTIONS] IMAGE [COMMAND] [ARG...]", "Run a command in a new container"), args, nil)
  1526. if err != nil {
  1527. return err
  1528. }
  1529. if config.Image == "" {
  1530. cmd.Usage()
  1531. return nil
  1532. }
  1533. // Retrieve relevant client-side config
  1534. var (
  1535. flName = cmd.Lookup("name")
  1536. flRm = cmd.Lookup("rm")
  1537. flSigProxy = cmd.Lookup("sig-proxy")
  1538. autoRemove, _ = strconv.ParseBool(flRm.Value.String())
  1539. sigProxy, _ = strconv.ParseBool(flSigProxy.Value.String())
  1540. )
  1541. // Disable sigProxy in case on TTY
  1542. if config.Tty {
  1543. sigProxy = false
  1544. }
  1545. var containerIDFile io.WriteCloser
  1546. if len(hostConfig.ContainerIDFile) > 0 {
  1547. if _, err := os.Stat(hostConfig.ContainerIDFile); err == nil {
  1548. return fmt.Errorf("cid file found, make sure the other container isn't running or delete %s", hostConfig.ContainerIDFile)
  1549. }
  1550. if containerIDFile, err = os.Create(hostConfig.ContainerIDFile); err != nil {
  1551. return fmt.Errorf("failed to create the container ID file: %s", err)
  1552. }
  1553. defer containerIDFile.Close()
  1554. }
  1555. containerValues := url.Values{}
  1556. if name := flName.Value.String(); name != "" {
  1557. containerValues.Set("name", name)
  1558. }
  1559. //create the container
  1560. stream, statusCode, err := cli.call("POST", "/containers/create?"+containerValues.Encode(), config, false)
  1561. //if image not found try to pull it
  1562. if statusCode == 404 {
  1563. fmt.Fprintf(cli.err, "Unable to find image '%s' locally\n", config.Image)
  1564. v := url.Values{}
  1565. repos, tag := utils.ParseRepositoryTag(config.Image)
  1566. v.Set("fromImage", repos)
  1567. v.Set("tag", tag)
  1568. // Resolve the Repository name from fqn to endpoint + name
  1569. endpoint, _, err := registry.ResolveRepositoryName(repos)
  1570. if err != nil {
  1571. return err
  1572. }
  1573. // Load the auth config file, to be able to pull the image
  1574. cli.LoadConfigFile()
  1575. // Resolve the Auth config relevant for this server
  1576. authConfig := cli.configFile.ResolveAuthConfig(endpoint)
  1577. buf, err := json.Marshal(authConfig)
  1578. if err != nil {
  1579. return err
  1580. }
  1581. registryAuthHeader := []string{
  1582. base64.URLEncoding.EncodeToString(buf),
  1583. }
  1584. if err = cli.stream("POST", "/images/create?"+v.Encode(), nil, cli.err, map[string][]string{"X-Registry-Auth": registryAuthHeader}); err != nil {
  1585. return err
  1586. }
  1587. if stream, _, err = cli.call("POST", "/containers/create?"+containerValues.Encode(), config, false); err != nil {
  1588. return err
  1589. }
  1590. } else if err != nil {
  1591. return err
  1592. }
  1593. var runResult engine.Env
  1594. if err := runResult.Decode(stream); err != nil {
  1595. return err
  1596. }
  1597. for _, warning := range runResult.GetList("Warnings") {
  1598. fmt.Fprintf(cli.err, "WARNING: %s\n", warning)
  1599. }
  1600. if len(hostConfig.ContainerIDFile) > 0 {
  1601. if _, err = containerIDFile.Write([]byte(runResult.Get("Id"))); err != nil {
  1602. return fmt.Errorf("failed to write the container ID to the file: %s", err)
  1603. }
  1604. }
  1605. if sigProxy {
  1606. sigc := cli.forwardAllSignals(runResult.Get("Id"))
  1607. defer utils.StopCatch(sigc)
  1608. }
  1609. var (
  1610. waitDisplayId chan struct{}
  1611. errCh chan error
  1612. )
  1613. if !config.AttachStdout && !config.AttachStderr {
  1614. // Make this asynchrone in order to let the client write to stdin before having to read the ID
  1615. waitDisplayId = make(chan struct{})
  1616. go func() {
  1617. defer close(waitDisplayId)
  1618. fmt.Fprintf(cli.out, "%s\n", runResult.Get("Id"))
  1619. }()
  1620. }
  1621. // We need to instanciate the chan because the select needs it. It can
  1622. // be closed but can't be uninitialized.
  1623. hijacked := make(chan io.Closer)
  1624. // Block the return until the chan gets closed
  1625. defer func() {
  1626. utils.Debugf("End of CmdRun(), Waiting for hijack to finish.")
  1627. if _, ok := <-hijacked; ok {
  1628. utils.Errorf("Hijack did not finish (chan still open)")
  1629. }
  1630. }()
  1631. if config.AttachStdin || config.AttachStdout || config.AttachStderr {
  1632. var (
  1633. out, stderr io.Writer
  1634. in io.ReadCloser
  1635. v = url.Values{}
  1636. )
  1637. v.Set("stream", "1")
  1638. if config.AttachStdin {
  1639. v.Set("stdin", "1")
  1640. in = cli.in
  1641. }
  1642. if config.AttachStdout {
  1643. v.Set("stdout", "1")
  1644. out = cli.out
  1645. }
  1646. if config.AttachStderr {
  1647. v.Set("stderr", "1")
  1648. if config.Tty {
  1649. stderr = cli.out
  1650. } else {
  1651. stderr = cli.err
  1652. }
  1653. }
  1654. errCh = utils.Go(func() error {
  1655. return cli.hijack("POST", "/containers/"+runResult.Get("Id")+"/attach?"+v.Encode(), config.Tty, in, out, stderr, hijacked)
  1656. })
  1657. } else {
  1658. close(hijacked)
  1659. }
  1660. // Acknowledge the hijack before starting
  1661. select {
  1662. case closer := <-hijacked:
  1663. // Make sure that hijack gets closed when returning. (result
  1664. // in closing hijack chan and freeing server's goroutines.
  1665. if closer != nil {
  1666. defer closer.Close()
  1667. }
  1668. case err := <-errCh:
  1669. if err != nil {
  1670. utils.Debugf("Error hijack: %s", err)
  1671. return err
  1672. }
  1673. }
  1674. //start the container
  1675. if _, _, err = readBody(cli.call("POST", "/containers/"+runResult.Get("Id")+"/start", hostConfig, false)); err != nil {
  1676. return err
  1677. }
  1678. if (config.AttachStdin || config.AttachStdout || config.AttachStderr) && config.Tty && cli.isTerminal {
  1679. if err := cli.monitorTtySize(runResult.Get("Id")); err != nil {
  1680. utils.Errorf("Error monitoring TTY size: %s\n", err)
  1681. }
  1682. }
  1683. if errCh != nil {
  1684. if err := <-errCh; err != nil {
  1685. utils.Debugf("Error hijack: %s", err)
  1686. return err
  1687. }
  1688. }
  1689. // Detached mode: wait for the id to be displayed and return.
  1690. if !config.AttachStdout && !config.AttachStderr {
  1691. // Detached mode
  1692. <-waitDisplayId
  1693. return nil
  1694. }
  1695. var status int
  1696. // Attached mode
  1697. if autoRemove {
  1698. // Autoremove: wait for the container to finish, retrieve
  1699. // the exit code and remove the container
  1700. if _, _, err := readBody(cli.call("POST", "/containers/"+runResult.Get("Id")+"/wait", nil, false)); err != nil {
  1701. return err
  1702. }
  1703. if _, status, err = getExitCode(cli, runResult.Get("Id")); err != nil {
  1704. return err
  1705. }
  1706. if _, _, err := readBody(cli.call("DELETE", "/containers/"+runResult.Get("Id")+"?v=1", nil, false)); err != nil {
  1707. return err
  1708. }
  1709. } else {
  1710. if !config.Tty {
  1711. // In non-tty mode, we can't dettach, so we know we need to wait.
  1712. if status, err = waitForExit(cli, runResult.Get("Id")); err != nil {
  1713. return err
  1714. }
  1715. } else {
  1716. // In TTY mode, there is a race. If the process dies too slowly, the state can be update after the getExitCode call
  1717. // and result in a wrong exit code.
  1718. // No Autoremove: Simply retrieve the exit code
  1719. if _, status, err = getExitCode(cli, runResult.Get("Id")); err != nil {
  1720. return err
  1721. }
  1722. }
  1723. }
  1724. if status != 0 {
  1725. return &utils.StatusError{StatusCode: status}
  1726. }
  1727. return nil
  1728. }
  1729. func (cli *DockerCli) CmdCp(args ...string) error {
  1730. cmd := cli.Subcmd("cp", "CONTAINER:PATH HOSTPATH", "Copy files/folders from the PATH to the HOSTPATH")
  1731. if err := cmd.Parse(args); err != nil {
  1732. return nil
  1733. }
  1734. if cmd.NArg() != 2 {
  1735. cmd.Usage()
  1736. return nil
  1737. }
  1738. var copyData engine.Env
  1739. info := strings.Split(cmd.Arg(0), ":")
  1740. if len(info) != 2 {
  1741. return fmt.Errorf("Error: Path not specified")
  1742. }
  1743. copyData.Set("Resource", info[1])
  1744. copyData.Set("HostPath", cmd.Arg(1))
  1745. stream, statusCode, err := cli.call("POST", "/containers/"+info[0]+"/copy", copyData, false)
  1746. if stream != nil {
  1747. defer stream.Close()
  1748. }
  1749. if statusCode == 404 {
  1750. return fmt.Errorf("No such container: %v", info[0])
  1751. }
  1752. if err != nil {
  1753. return err
  1754. }
  1755. if statusCode == 200 {
  1756. if err := archive.Untar(stream, copyData.Get("HostPath"), nil); err != nil {
  1757. return err
  1758. }
  1759. }
  1760. return nil
  1761. }
  1762. func (cli *DockerCli) CmdSave(args ...string) error {
  1763. cmd := cli.Subcmd("save", "IMAGE", "Save an image to a tar archive (streamed to stdout)")
  1764. if err := cmd.Parse(args); err != nil {
  1765. return err
  1766. }
  1767. if cmd.NArg() != 1 {
  1768. cmd.Usage()
  1769. return nil
  1770. }
  1771. image := cmd.Arg(0)
  1772. if err := cli.stream("GET", "/images/"+image+"/get", nil, cli.out, nil); err != nil {
  1773. return err
  1774. }
  1775. return nil
  1776. }
  1777. func (cli *DockerCli) CmdLoad(args ...string) error {
  1778. cmd := cli.Subcmd("load", "", "Load an image from a tar archive on STDIN")
  1779. if err := cmd.Parse(args); err != nil {
  1780. return err
  1781. }
  1782. if cmd.NArg() != 0 {
  1783. cmd.Usage()
  1784. return nil
  1785. }
  1786. if err := cli.stream("POST", "/images/load", cli.in, cli.out, nil); err != nil {
  1787. return err
  1788. }
  1789. return nil
  1790. }
  1791. func (cli *DockerCli) call(method, path string, data interface{}, passAuthInfo bool) (io.ReadCloser, int, error) {
  1792. params := bytes.NewBuffer(nil)
  1793. if data != nil {
  1794. if env, ok := data.(engine.Env); ok {
  1795. if err := env.Encode(params); err != nil {
  1796. return nil, -1, err
  1797. }
  1798. } else {
  1799. buf, err := json.Marshal(data)
  1800. if err != nil {
  1801. return nil, -1, err
  1802. }
  1803. if _, err := params.Write(buf); err != nil {
  1804. return nil, -1, err
  1805. }
  1806. }
  1807. }
  1808. // fixme: refactor client to support redirect
  1809. re := regexp.MustCompile("/+")
  1810. path = re.ReplaceAllString(path, "/")
  1811. req, err := http.NewRequest(method, fmt.Sprintf("/v%s%s", APIVERSION, path), params)
  1812. if err != nil {
  1813. return nil, -1, err
  1814. }
  1815. if passAuthInfo {
  1816. cli.LoadConfigFile()
  1817. // Resolve the Auth config relevant for this server
  1818. authConfig := cli.configFile.ResolveAuthConfig(auth.IndexServerAddress())
  1819. getHeaders := func(authConfig auth.AuthConfig) (map[string][]string, error) {
  1820. buf, err := json.Marshal(authConfig)
  1821. if err != nil {
  1822. return nil, err
  1823. }
  1824. registryAuthHeader := []string{
  1825. base64.URLEncoding.EncodeToString(buf),
  1826. }
  1827. return map[string][]string{"X-Registry-Auth": registryAuthHeader}, nil
  1828. }
  1829. if headers, err := getHeaders(authConfig); err == nil && headers != nil {
  1830. for k, v := range headers {
  1831. req.Header[k] = v
  1832. }
  1833. }
  1834. }
  1835. req.Header.Set("User-Agent", "Docker-Client/"+dockerversion.VERSION)
  1836. req.Host = cli.addr
  1837. if data != nil {
  1838. req.Header.Set("Content-Type", "application/json")
  1839. } else if method == "POST" {
  1840. req.Header.Set("Content-Type", "plain/text")
  1841. }
  1842. dial, err := net.Dial(cli.proto, cli.addr)
  1843. if err != nil {
  1844. if strings.Contains(err.Error(), "connection refused") {
  1845. return nil, -1, ErrConnectionRefused
  1846. }
  1847. return nil, -1, err
  1848. }
  1849. clientconn := httputil.NewClientConn(dial, nil)
  1850. resp, err := clientconn.Do(req)
  1851. if err != nil {
  1852. clientconn.Close()
  1853. if strings.Contains(err.Error(), "connection refused") {
  1854. return nil, -1, ErrConnectionRefused
  1855. }
  1856. return nil, -1, err
  1857. }
  1858. if resp.StatusCode < 200 || resp.StatusCode >= 400 {
  1859. body, err := ioutil.ReadAll(resp.Body)
  1860. if err != nil {
  1861. return nil, -1, err
  1862. }
  1863. if len(body) == 0 {
  1864. return nil, resp.StatusCode, fmt.Errorf("Error: request returned %s for api route and version %s, check if the server supports the requested api version", http.StatusText(resp.StatusCode), req.URL)
  1865. }
  1866. return nil, resp.StatusCode, fmt.Errorf("Error: %s", bytes.TrimSpace(body))
  1867. }
  1868. wrapper := utils.NewReadCloserWrapper(resp.Body, func() error {
  1869. if resp != nil && resp.Body != nil {
  1870. resp.Body.Close()
  1871. }
  1872. return clientconn.Close()
  1873. })
  1874. return wrapper, resp.StatusCode, nil
  1875. }
  1876. func (cli *DockerCli) stream(method, path string, in io.Reader, out io.Writer, headers map[string][]string) error {
  1877. if (method == "POST" || method == "PUT") && in == nil {
  1878. in = bytes.NewReader([]byte{})
  1879. }
  1880. // fixme: refactor client to support redirect
  1881. re := regexp.MustCompile("/+")
  1882. path = re.ReplaceAllString(path, "/")
  1883. req, err := http.NewRequest(method, fmt.Sprintf("/v%s%s", APIVERSION, path), in)
  1884. if err != nil {
  1885. return err
  1886. }
  1887. req.Header.Set("User-Agent", "Docker-Client/"+dockerversion.VERSION)
  1888. req.Host = cli.addr
  1889. if method == "POST" {
  1890. req.Header.Set("Content-Type", "plain/text")
  1891. }
  1892. if headers != nil {
  1893. for k, v := range headers {
  1894. req.Header[k] = v
  1895. }
  1896. }
  1897. dial, err := net.Dial(cli.proto, cli.addr)
  1898. if err != nil {
  1899. if strings.Contains(err.Error(), "connection refused") {
  1900. return fmt.Errorf("Can't connect to docker daemon. Is 'docker -d' running on this host?")
  1901. }
  1902. return err
  1903. }
  1904. clientconn := httputil.NewClientConn(dial, nil)
  1905. resp, err := clientconn.Do(req)
  1906. defer clientconn.Close()
  1907. if err != nil {
  1908. if strings.Contains(err.Error(), "connection refused") {
  1909. return fmt.Errorf("Can't connect to docker daemon. Is 'docker -d' running on this host?")
  1910. }
  1911. return err
  1912. }
  1913. defer resp.Body.Close()
  1914. if resp.StatusCode < 200 || resp.StatusCode >= 400 {
  1915. body, err := ioutil.ReadAll(resp.Body)
  1916. if err != nil {
  1917. return err
  1918. }
  1919. if len(body) == 0 {
  1920. return fmt.Errorf("Error :%s", http.StatusText(resp.StatusCode))
  1921. }
  1922. return fmt.Errorf("Error: %s", bytes.TrimSpace(body))
  1923. }
  1924. if MatchesContentType(resp.Header.Get("Content-Type"), "application/json") {
  1925. return utils.DisplayJSONMessagesStream(resp.Body, out, cli.terminalFd, cli.isTerminal)
  1926. }
  1927. if _, err := io.Copy(out, resp.Body); err != nil {
  1928. return err
  1929. }
  1930. return nil
  1931. }
  1932. func (cli *DockerCli) hijack(method, path string, setRawTerminal bool, in io.ReadCloser, stdout, stderr io.Writer, started chan io.Closer) error {
  1933. defer func() {
  1934. if started != nil {
  1935. close(started)
  1936. }
  1937. }()
  1938. // fixme: refactor client to support redirect
  1939. re := regexp.MustCompile("/+")
  1940. path = re.ReplaceAllString(path, "/")
  1941. req, err := http.NewRequest(method, fmt.Sprintf("/v%s%s", APIVERSION, path), nil)
  1942. if err != nil {
  1943. return err
  1944. }
  1945. req.Header.Set("User-Agent", "Docker-Client/"+dockerversion.VERSION)
  1946. req.Header.Set("Content-Type", "plain/text")
  1947. req.Host = cli.addr
  1948. dial, err := net.Dial(cli.proto, cli.addr)
  1949. if err != nil {
  1950. if strings.Contains(err.Error(), "connection refused") {
  1951. return fmt.Errorf("Can't connect to docker daemon. Is 'docker -d' running on this host?")
  1952. }
  1953. return err
  1954. }
  1955. clientconn := httputil.NewClientConn(dial, nil)
  1956. defer clientconn.Close()
  1957. // Server hijacks the connection, error 'connection closed' expected
  1958. clientconn.Do(req)
  1959. rwc, br := clientconn.Hijack()
  1960. defer rwc.Close()
  1961. if started != nil {
  1962. started <- rwc
  1963. }
  1964. var receiveStdout chan error
  1965. var oldState *term.State
  1966. if in != nil && setRawTerminal && cli.isTerminal && os.Getenv("NORAW") == "" {
  1967. oldState, err = term.SetRawTerminal(cli.terminalFd)
  1968. if err != nil {
  1969. return err
  1970. }
  1971. defer term.RestoreTerminal(cli.terminalFd, oldState)
  1972. }
  1973. if stdout != nil || stderr != nil {
  1974. receiveStdout = utils.Go(func() (err error) {
  1975. defer func() {
  1976. if in != nil {
  1977. if setRawTerminal && cli.isTerminal {
  1978. term.RestoreTerminal(cli.terminalFd, oldState)
  1979. }
  1980. in.Close()
  1981. }
  1982. }()
  1983. // When TTY is ON, use regular copy
  1984. if setRawTerminal {
  1985. _, err = io.Copy(stdout, br)
  1986. } else {
  1987. _, err = utils.StdCopy(stdout, stderr, br)
  1988. }
  1989. utils.Debugf("[hijack] End of stdout")
  1990. return err
  1991. })
  1992. }
  1993. sendStdin := utils.Go(func() error {
  1994. if in != nil {
  1995. io.Copy(rwc, in)
  1996. utils.Debugf("[hijack] End of stdin")
  1997. }
  1998. if tcpc, ok := rwc.(*net.TCPConn); ok {
  1999. if err := tcpc.CloseWrite(); err != nil {
  2000. utils.Errorf("Couldn't send EOF: %s\n", err)
  2001. }
  2002. } else if unixc, ok := rwc.(*net.UnixConn); ok {
  2003. if err := unixc.CloseWrite(); err != nil {
  2004. utils.Errorf("Couldn't send EOF: %s\n", err)
  2005. }
  2006. }
  2007. // Discard errors due to pipe interruption
  2008. return nil
  2009. })
  2010. if stdout != nil || stderr != nil {
  2011. if err := <-receiveStdout; err != nil {
  2012. utils.Errorf("Error receiveStdout: %s", err)
  2013. return err
  2014. }
  2015. }
  2016. if !cli.isTerminal {
  2017. if err := <-sendStdin; err != nil {
  2018. utils.Errorf("Error sendStdin: %s", err)
  2019. return err
  2020. }
  2021. }
  2022. return nil
  2023. }
  2024. func (cli *DockerCli) getTtySize() (int, int) {
  2025. if !cli.isTerminal {
  2026. return 0, 0
  2027. }
  2028. ws, err := term.GetWinsize(cli.terminalFd)
  2029. if err != nil {
  2030. utils.Errorf("Error getting size: %s", err)
  2031. if ws == nil {
  2032. return 0, 0
  2033. }
  2034. }
  2035. return int(ws.Height), int(ws.Width)
  2036. }
  2037. func (cli *DockerCli) resizeTty(id string) {
  2038. height, width := cli.getTtySize()
  2039. if height == 0 && width == 0 {
  2040. return
  2041. }
  2042. v := url.Values{}
  2043. v.Set("h", strconv.Itoa(height))
  2044. v.Set("w", strconv.Itoa(width))
  2045. if _, _, err := readBody(cli.call("POST", "/containers/"+id+"/resize?"+v.Encode(), nil, false)); err != nil {
  2046. utils.Errorf("Error resize: %s", err)
  2047. }
  2048. }
  2049. func (cli *DockerCli) monitorTtySize(id string) error {
  2050. cli.resizeTty(id)
  2051. sigchan := make(chan os.Signal, 1)
  2052. signal.Notify(sigchan, syscall.SIGWINCH)
  2053. go func() {
  2054. for _ = range sigchan {
  2055. cli.resizeTty(id)
  2056. }
  2057. }()
  2058. return nil
  2059. }
  2060. func (cli *DockerCli) Subcmd(name, signature, description string) *flag.FlagSet {
  2061. flags := flag.NewFlagSet(name, flag.ContinueOnError)
  2062. flags.Usage = func() {
  2063. fmt.Fprintf(cli.err, "\nUsage: docker %s %s\n\n%s\n\n", name, signature, description)
  2064. flags.PrintDefaults()
  2065. os.Exit(2)
  2066. }
  2067. return flags
  2068. }
  2069. func (cli *DockerCli) LoadConfigFile() (err error) {
  2070. cli.configFile, err = auth.LoadConfig(os.Getenv("HOME"))
  2071. if err != nil {
  2072. fmt.Fprintf(cli.err, "WARNING: %s\n", err)
  2073. }
  2074. return err
  2075. }
  2076. func waitForExit(cli *DockerCli, containerId string) (int, error) {
  2077. stream, _, err := cli.call("POST", "/containers/"+containerId+"/wait", nil, false)
  2078. if err != nil {
  2079. return -1, err
  2080. }
  2081. var out engine.Env
  2082. if err := out.Decode(stream); err != nil {
  2083. return -1, err
  2084. }
  2085. return out.GetInt("StatusCode"), nil
  2086. }
  2087. // getExitCode perform an inspect on the container. It returns
  2088. // the running state and the exit code.
  2089. func getExitCode(cli *DockerCli, containerId string) (bool, int, error) {
  2090. body, _, err := readBody(cli.call("GET", "/containers/"+containerId+"/json", nil, false))
  2091. if err != nil {
  2092. // If we can't connect, then the daemon probably died.
  2093. if err != ErrConnectionRefused {
  2094. return false, -1, err
  2095. }
  2096. return false, -1, nil
  2097. }
  2098. c := &Container{}
  2099. if err := json.Unmarshal(body, c); err != nil {
  2100. return false, -1, err
  2101. }
  2102. return c.State.Running, c.State.ExitCode, nil
  2103. }
  2104. func readBody(stream io.ReadCloser, statusCode int, err error) ([]byte, int, error) {
  2105. if stream != nil {
  2106. defer stream.Close()
  2107. }
  2108. if err != nil {
  2109. return nil, statusCode, err
  2110. }
  2111. body, err := ioutil.ReadAll(stream)
  2112. if err != nil {
  2113. return nil, -1, err
  2114. }
  2115. return body, statusCode, nil
  2116. }
  2117. func NewDockerCli(in io.ReadCloser, out, err io.Writer, proto, addr string) *DockerCli {
  2118. var (
  2119. isTerminal = false
  2120. terminalFd uintptr
  2121. )
  2122. if in != nil {
  2123. if file, ok := in.(*os.File); ok {
  2124. terminalFd = file.Fd()
  2125. isTerminal = term.IsTerminal(terminalFd)
  2126. }
  2127. }
  2128. if err == nil {
  2129. err = out
  2130. }
  2131. return &DockerCli{
  2132. proto: proto,
  2133. addr: addr,
  2134. in: in,
  2135. out: out,
  2136. err: err,
  2137. isTerminal: isTerminal,
  2138. terminalFd: terminalFd,
  2139. }
  2140. }
  2141. type DockerCli struct {
  2142. proto string
  2143. addr string
  2144. configFile *auth.ConfigFile
  2145. in io.ReadCloser
  2146. out io.Writer
  2147. err io.Writer
  2148. isTerminal bool
  2149. terminalFd uintptr
  2150. }