client.go 67 KB

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