client.go 66 KB

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