client.go 65 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412
  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. 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 [REGISTRYHOST/][USERNAME/]NAME[: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 [REGISTRYHOST/][USERNAME/]NAME[: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 statusCode == 404 {
  1743. return fmt.Errorf("No such container: %v", info[0])
  1744. }
  1745. if err != nil {
  1746. return err
  1747. }
  1748. if statusCode == 200 {
  1749. if err := archive.Untar(stream, copyData.Get("HostPath"), nil); err != nil {
  1750. return err
  1751. }
  1752. }
  1753. return nil
  1754. }
  1755. func (cli *DockerCli) CmdSave(args ...string) error {
  1756. cmd := cli.Subcmd("save", "IMAGE", "Save an image to a tar archive (streamed to stdout)")
  1757. if err := cmd.Parse(args); err != nil {
  1758. return err
  1759. }
  1760. if cmd.NArg() != 1 {
  1761. cmd.Usage()
  1762. return nil
  1763. }
  1764. image := cmd.Arg(0)
  1765. if err := cli.stream("GET", "/images/"+image+"/get", nil, cli.out, nil); err != nil {
  1766. return err
  1767. }
  1768. return nil
  1769. }
  1770. func (cli *DockerCli) CmdLoad(args ...string) error {
  1771. cmd := cli.Subcmd("load", "", "Load an image from a tar archive on STDIN")
  1772. if err := cmd.Parse(args); err != nil {
  1773. return err
  1774. }
  1775. if cmd.NArg() != 0 {
  1776. cmd.Usage()
  1777. return nil
  1778. }
  1779. if err := cli.stream("POST", "/images/load", cli.in, cli.out, nil); err != nil {
  1780. return err
  1781. }
  1782. return nil
  1783. }
  1784. func (cli *DockerCli) call(method, path string, data interface{}, passAuthInfo bool) (io.ReadCloser, int, error) {
  1785. params := bytes.NewBuffer(nil)
  1786. if data != nil {
  1787. if env, ok := data.(engine.Env); ok {
  1788. if err := env.Encode(params); err != nil {
  1789. return nil, -1, err
  1790. }
  1791. } else {
  1792. buf, err := json.Marshal(data)
  1793. if err != nil {
  1794. return nil, -1, err
  1795. }
  1796. if _, err := params.Write(buf); err != nil {
  1797. return nil, -1, err
  1798. }
  1799. }
  1800. }
  1801. // fixme: refactor client to support redirect
  1802. re := regexp.MustCompile("/+")
  1803. path = re.ReplaceAllString(path, "/")
  1804. req, err := http.NewRequest(method, fmt.Sprintf("/v%g%s", APIVERSION, path), params)
  1805. if err != nil {
  1806. return nil, -1, err
  1807. }
  1808. if passAuthInfo {
  1809. cli.LoadConfigFile()
  1810. // Resolve the Auth config relevant for this server
  1811. authConfig := cli.configFile.ResolveAuthConfig(auth.IndexServerAddress())
  1812. getHeaders := func(authConfig auth.AuthConfig) (map[string][]string, error) {
  1813. buf, err := json.Marshal(authConfig)
  1814. if err != nil {
  1815. return nil, err
  1816. }
  1817. registryAuthHeader := []string{
  1818. base64.URLEncoding.EncodeToString(buf),
  1819. }
  1820. return map[string][]string{"X-Registry-Auth": registryAuthHeader}, nil
  1821. }
  1822. if headers, err := getHeaders(authConfig); err == nil && headers != nil {
  1823. for k, v := range headers {
  1824. req.Header[k] = v
  1825. }
  1826. }
  1827. }
  1828. req.Header.Set("User-Agent", "Docker-Client/"+dockerversion.VERSION)
  1829. req.Host = cli.addr
  1830. if data != nil {
  1831. req.Header.Set("Content-Type", "application/json")
  1832. } else if method == "POST" {
  1833. req.Header.Set("Content-Type", "plain/text")
  1834. }
  1835. dial, err := net.Dial(cli.proto, cli.addr)
  1836. if err != nil {
  1837. if strings.Contains(err.Error(), "connection refused") {
  1838. return nil, -1, ErrConnectionRefused
  1839. }
  1840. return nil, -1, err
  1841. }
  1842. clientconn := httputil.NewClientConn(dial, nil)
  1843. resp, err := clientconn.Do(req)
  1844. if err != nil {
  1845. clientconn.Close()
  1846. if strings.Contains(err.Error(), "connection refused") {
  1847. return nil, -1, ErrConnectionRefused
  1848. }
  1849. return nil, -1, err
  1850. }
  1851. if resp.StatusCode < 200 || resp.StatusCode >= 400 {
  1852. body, err := ioutil.ReadAll(resp.Body)
  1853. if err != nil {
  1854. return nil, -1, err
  1855. }
  1856. if len(body) == 0 {
  1857. 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)
  1858. }
  1859. return nil, resp.StatusCode, fmt.Errorf("Error: %s", bytes.TrimSpace(body))
  1860. }
  1861. wrapper := utils.NewReadCloserWrapper(resp.Body, func() error {
  1862. if resp != nil && resp.Body != nil {
  1863. resp.Body.Close()
  1864. }
  1865. return clientconn.Close()
  1866. })
  1867. return wrapper, resp.StatusCode, nil
  1868. }
  1869. func (cli *DockerCli) stream(method, path string, in io.Reader, out io.Writer, headers map[string][]string) error {
  1870. if (method == "POST" || method == "PUT") && in == nil {
  1871. in = bytes.NewReader([]byte{})
  1872. }
  1873. // fixme: refactor client to support redirect
  1874. re := regexp.MustCompile("/+")
  1875. path = re.ReplaceAllString(path, "/")
  1876. req, err := http.NewRequest(method, fmt.Sprintf("/v%g%s", APIVERSION, path), in)
  1877. if err != nil {
  1878. return err
  1879. }
  1880. req.Header.Set("User-Agent", "Docker-Client/"+dockerversion.VERSION)
  1881. req.Host = cli.addr
  1882. if method == "POST" {
  1883. req.Header.Set("Content-Type", "plain/text")
  1884. }
  1885. if headers != nil {
  1886. for k, v := range headers {
  1887. req.Header[k] = v
  1888. }
  1889. }
  1890. dial, err := net.Dial(cli.proto, cli.addr)
  1891. if err != nil {
  1892. if strings.Contains(err.Error(), "connection refused") {
  1893. return fmt.Errorf("Can't connect to docker daemon. Is 'docker -d' running on this host?")
  1894. }
  1895. return err
  1896. }
  1897. clientconn := httputil.NewClientConn(dial, nil)
  1898. resp, err := clientconn.Do(req)
  1899. defer clientconn.Close()
  1900. if err != nil {
  1901. if strings.Contains(err.Error(), "connection refused") {
  1902. return fmt.Errorf("Can't connect to docker daemon. Is 'docker -d' running on this host?")
  1903. }
  1904. return err
  1905. }
  1906. defer resp.Body.Close()
  1907. if resp.StatusCode < 200 || resp.StatusCode >= 400 {
  1908. body, err := ioutil.ReadAll(resp.Body)
  1909. if err != nil {
  1910. return err
  1911. }
  1912. if len(body) == 0 {
  1913. return fmt.Errorf("Error :%s", http.StatusText(resp.StatusCode))
  1914. }
  1915. return fmt.Errorf("Error: %s", bytes.TrimSpace(body))
  1916. }
  1917. if MatchesContentType(resp.Header.Get("Content-Type"), "application/json") {
  1918. return utils.DisplayJSONMessagesStream(resp.Body, out, cli.terminalFd, cli.isTerminal)
  1919. }
  1920. if _, err := io.Copy(out, resp.Body); err != nil {
  1921. return err
  1922. }
  1923. return nil
  1924. }
  1925. func (cli *DockerCli) hijack(method, path string, setRawTerminal bool, in io.ReadCloser, stdout, stderr io.Writer, started chan io.Closer) error {
  1926. defer func() {
  1927. if started != nil {
  1928. close(started)
  1929. }
  1930. }()
  1931. // fixme: refactor client to support redirect
  1932. re := regexp.MustCompile("/+")
  1933. path = re.ReplaceAllString(path, "/")
  1934. req, err := http.NewRequest(method, fmt.Sprintf("/v%g%s", APIVERSION, path), nil)
  1935. if err != nil {
  1936. return err
  1937. }
  1938. req.Header.Set("User-Agent", "Docker-Client/"+dockerversion.VERSION)
  1939. req.Header.Set("Content-Type", "plain/text")
  1940. req.Host = cli.addr
  1941. dial, err := net.Dial(cli.proto, cli.addr)
  1942. if err != nil {
  1943. if strings.Contains(err.Error(), "connection refused") {
  1944. return fmt.Errorf("Can't connect to docker daemon. Is 'docker -d' running on this host?")
  1945. }
  1946. return err
  1947. }
  1948. clientconn := httputil.NewClientConn(dial, nil)
  1949. defer clientconn.Close()
  1950. // Server hijacks the connection, error 'connection closed' expected
  1951. clientconn.Do(req)
  1952. rwc, br := clientconn.Hijack()
  1953. defer rwc.Close()
  1954. if started != nil {
  1955. started <- rwc
  1956. }
  1957. var receiveStdout chan error
  1958. var oldState *term.State
  1959. if in != nil && setRawTerminal && cli.isTerminal && os.Getenv("NORAW") == "" {
  1960. oldState, err = term.SetRawTerminal(cli.terminalFd)
  1961. if err != nil {
  1962. return err
  1963. }
  1964. defer term.RestoreTerminal(cli.terminalFd, oldState)
  1965. }
  1966. if stdout != nil || stderr != nil {
  1967. receiveStdout = utils.Go(func() (err error) {
  1968. defer func() {
  1969. if in != nil {
  1970. if setRawTerminal && cli.isTerminal {
  1971. term.RestoreTerminal(cli.terminalFd, oldState)
  1972. }
  1973. in.Close()
  1974. }
  1975. }()
  1976. // When TTY is ON, use regular copy
  1977. if setRawTerminal {
  1978. _, err = io.Copy(stdout, br)
  1979. } else {
  1980. _, err = utils.StdCopy(stdout, stderr, br)
  1981. }
  1982. utils.Debugf("[hijack] End of stdout")
  1983. return err
  1984. })
  1985. }
  1986. sendStdin := utils.Go(func() error {
  1987. if in != nil {
  1988. io.Copy(rwc, in)
  1989. utils.Debugf("[hijack] End of stdin")
  1990. }
  1991. if tcpc, ok := rwc.(*net.TCPConn); ok {
  1992. if err := tcpc.CloseWrite(); err != nil {
  1993. utils.Errorf("Couldn't send EOF: %s\n", err)
  1994. }
  1995. } else if unixc, ok := rwc.(*net.UnixConn); ok {
  1996. if err := unixc.CloseWrite(); err != nil {
  1997. utils.Errorf("Couldn't send EOF: %s\n", err)
  1998. }
  1999. }
  2000. // Discard errors due to pipe interruption
  2001. return nil
  2002. })
  2003. if stdout != nil || stderr != nil {
  2004. if err := <-receiveStdout; err != nil {
  2005. utils.Errorf("Error receiveStdout: %s", err)
  2006. return err
  2007. }
  2008. }
  2009. if !cli.isTerminal {
  2010. if err := <-sendStdin; err != nil {
  2011. utils.Errorf("Error sendStdin: %s", err)
  2012. return err
  2013. }
  2014. }
  2015. return nil
  2016. }
  2017. func (cli *DockerCli) getTtySize() (int, int) {
  2018. if !cli.isTerminal {
  2019. return 0, 0
  2020. }
  2021. ws, err := term.GetWinsize(cli.terminalFd)
  2022. if err != nil {
  2023. utils.Errorf("Error getting size: %s", err)
  2024. if ws == nil {
  2025. return 0, 0
  2026. }
  2027. }
  2028. return int(ws.Height), int(ws.Width)
  2029. }
  2030. func (cli *DockerCli) resizeTty(id string) {
  2031. height, width := cli.getTtySize()
  2032. if height == 0 && width == 0 {
  2033. return
  2034. }
  2035. v := url.Values{}
  2036. v.Set("h", strconv.Itoa(height))
  2037. v.Set("w", strconv.Itoa(width))
  2038. if _, _, err := readBody(cli.call("POST", "/containers/"+id+"/resize?"+v.Encode(), nil, false)); err != nil {
  2039. utils.Errorf("Error resize: %s", err)
  2040. }
  2041. }
  2042. func (cli *DockerCli) monitorTtySize(id string) error {
  2043. cli.resizeTty(id)
  2044. sigchan := make(chan os.Signal, 1)
  2045. signal.Notify(sigchan, syscall.SIGWINCH)
  2046. go func() {
  2047. for _ = range sigchan {
  2048. cli.resizeTty(id)
  2049. }
  2050. }()
  2051. return nil
  2052. }
  2053. func (cli *DockerCli) Subcmd(name, signature, description string) *flag.FlagSet {
  2054. flags := flag.NewFlagSet(name, flag.ContinueOnError)
  2055. flags.Usage = func() {
  2056. fmt.Fprintf(cli.err, "\nUsage: docker %s %s\n\n%s\n\n", name, signature, description)
  2057. flags.PrintDefaults()
  2058. os.Exit(2)
  2059. }
  2060. return flags
  2061. }
  2062. func (cli *DockerCli) LoadConfigFile() (err error) {
  2063. cli.configFile, err = auth.LoadConfig(os.Getenv("HOME"))
  2064. if err != nil {
  2065. fmt.Fprintf(cli.err, "WARNING: %s\n", err)
  2066. }
  2067. return err
  2068. }
  2069. func waitForExit(cli *DockerCli, containerId string) (int, error) {
  2070. stream, _, err := cli.call("POST", "/containers/"+containerId+"/wait", nil, false)
  2071. if err != nil {
  2072. return -1, err
  2073. }
  2074. var out engine.Env
  2075. if err := out.Decode(stream); err != nil {
  2076. return -1, err
  2077. }
  2078. return out.GetInt("StatusCode"), nil
  2079. }
  2080. // getExitCode perform an inspect on the container. It returns
  2081. // the running state and the exit code.
  2082. func getExitCode(cli *DockerCli, containerId string) (bool, int, error) {
  2083. body, _, err := readBody(cli.call("GET", "/containers/"+containerId+"/json", nil, false))
  2084. if err != nil {
  2085. // If we can't connect, then the daemon probably died.
  2086. if err != ErrConnectionRefused {
  2087. return false, -1, err
  2088. }
  2089. return false, -1, nil
  2090. }
  2091. c := &Container{}
  2092. if err := json.Unmarshal(body, c); err != nil {
  2093. return false, -1, err
  2094. }
  2095. return c.State.Running, c.State.ExitCode, nil
  2096. }
  2097. func readBody(stream io.ReadCloser, statusCode int, err error) ([]byte, int, error) {
  2098. if stream != nil {
  2099. defer stream.Close()
  2100. }
  2101. if err != nil {
  2102. return nil, statusCode, err
  2103. }
  2104. body, err := ioutil.ReadAll(stream)
  2105. if err != nil {
  2106. return nil, -1, err
  2107. }
  2108. return body, statusCode, nil
  2109. }
  2110. func NewDockerCli(in io.ReadCloser, out, err io.Writer, proto, addr string) *DockerCli {
  2111. var (
  2112. isTerminal = false
  2113. terminalFd uintptr
  2114. )
  2115. if in != nil {
  2116. if file, ok := in.(*os.File); ok {
  2117. terminalFd = file.Fd()
  2118. isTerminal = term.IsTerminal(terminalFd)
  2119. }
  2120. }
  2121. if err == nil {
  2122. err = out
  2123. }
  2124. return &DockerCli{
  2125. proto: proto,
  2126. addr: addr,
  2127. in: in,
  2128. out: out,
  2129. err: err,
  2130. isTerminal: isTerminal,
  2131. terminalFd: terminalFd,
  2132. }
  2133. }
  2134. type DockerCli struct {
  2135. proto string
  2136. addr string
  2137. configFile *auth.ConfigFile
  2138. in io.ReadCloser
  2139. out io.Writer
  2140. err io.Writer
  2141. isTerminal bool
  2142. terminalFd uintptr
  2143. }