commands.go 68 KB

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