client.go 65 KB

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