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