commands.go 66 KB

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