client.go 66 KB

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