commands.go 68 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573
  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. if *attach || *openStdin {
  573. if cmd.NArg() > 1 {
  574. return fmt.Errorf("You cannot start and attach multiple containers at once.")
  575. }
  576. stream, _, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/json", nil, false)
  577. if err != nil {
  578. return err
  579. }
  580. env := engine.Env{}
  581. if err := env.Decode(stream); err != nil {
  582. return err
  583. }
  584. config := env.GetSubEnv("Config")
  585. tty = config.GetBool("Tty")
  586. if !tty {
  587. sigc := cli.forwardAllSignals(cmd.Arg(0))
  588. defer signal.StopCatch(sigc)
  589. }
  590. var in io.ReadCloser
  591. v := url.Values{}
  592. v.Set("stream", "1")
  593. if *openStdin && config.GetBool("OpenStdin") {
  594. v.Set("stdin", "1")
  595. in = cli.in
  596. }
  597. v.Set("stdout", "1")
  598. v.Set("stderr", "1")
  599. cErr = promise.Go(func() error {
  600. return cli.hijack("POST", "/containers/"+cmd.Arg(0)+"/attach?"+v.Encode(), tty, in, cli.out, cli.err, nil, nil)
  601. })
  602. }
  603. var encounteredError error
  604. for _, name := range cmd.Args() {
  605. _, _, err := readBody(cli.call("POST", "/containers/"+name+"/start", nil, false))
  606. if err != nil {
  607. if !*attach || !*openStdin {
  608. fmt.Fprintf(cli.err, "%s\n", err)
  609. }
  610. encounteredError = fmt.Errorf("Error: failed to start one or more containers")
  611. } else {
  612. if !*attach || !*openStdin {
  613. fmt.Fprintf(cli.out, "%s\n", name)
  614. }
  615. }
  616. }
  617. if encounteredError != nil {
  618. if *openStdin || *attach {
  619. cli.in.Close()
  620. }
  621. return encounteredError
  622. }
  623. if *openStdin || *attach {
  624. if tty && cli.isTerminalOut {
  625. if err := cli.monitorTtySize(cmd.Arg(0), false); err != nil {
  626. log.Errorf("Error monitoring TTY size: %s", err)
  627. }
  628. }
  629. if attchErr := <-cErr; attchErr != nil {
  630. return attchErr
  631. }
  632. _, status, err := getExitCode(cli, cmd.Arg(0))
  633. if err != nil {
  634. return err
  635. }
  636. if status != 0 {
  637. return &utils.StatusError{StatusCode: status}
  638. }
  639. }
  640. return nil
  641. }
  642. func (cli *DockerCli) CmdUnpause(args ...string) error {
  643. cmd := cli.Subcmd("unpause", "CONTAINER", "Unpause all processes within a container")
  644. if err := cmd.Parse(args); err != nil {
  645. return nil
  646. }
  647. if cmd.NArg() != 1 {
  648. cmd.Usage()
  649. return nil
  650. }
  651. var encounteredError error
  652. for _, name := range cmd.Args() {
  653. if _, _, err := readBody(cli.call("POST", fmt.Sprintf("/containers/%s/unpause", name), nil, false)); err != nil {
  654. fmt.Fprintf(cli.err, "%s\n", err)
  655. encounteredError = fmt.Errorf("Error: failed to unpause container named %s", name)
  656. } else {
  657. fmt.Fprintf(cli.out, "%s\n", name)
  658. }
  659. }
  660. return encounteredError
  661. }
  662. func (cli *DockerCli) CmdPause(args ...string) error {
  663. cmd := cli.Subcmd("pause", "CONTAINER", "Pause all processes within a container")
  664. if err := cmd.Parse(args); err != nil {
  665. return nil
  666. }
  667. if cmd.NArg() != 1 {
  668. cmd.Usage()
  669. return nil
  670. }
  671. var encounteredError error
  672. for _, name := range cmd.Args() {
  673. if _, _, err := readBody(cli.call("POST", fmt.Sprintf("/containers/%s/pause", name), nil, false)); err != nil {
  674. fmt.Fprintf(cli.err, "%s\n", err)
  675. encounteredError = fmt.Errorf("Error: failed to pause container named %s", name)
  676. } else {
  677. fmt.Fprintf(cli.out, "%s\n", name)
  678. }
  679. }
  680. return encounteredError
  681. }
  682. func (cli *DockerCli) CmdInspect(args ...string) error {
  683. cmd := cli.Subcmd("inspect", "CONTAINER|IMAGE [CONTAINER|IMAGE...]", "Return low-level information on a container or image")
  684. tmplStr := cmd.String([]string{"f", "#format", "-format"}, "", "Format the output using the given go template.")
  685. if err := cmd.Parse(args); err != nil {
  686. return nil
  687. }
  688. if cmd.NArg() < 1 {
  689. cmd.Usage()
  690. return nil
  691. }
  692. var tmpl *template.Template
  693. if *tmplStr != "" {
  694. var err error
  695. if tmpl, err = template.New("").Funcs(funcMap).Parse(*tmplStr); err != nil {
  696. fmt.Fprintf(cli.err, "Template parsing error: %v\n", err)
  697. return &utils.StatusError{StatusCode: 64,
  698. Status: "Template parsing error: " + err.Error()}
  699. }
  700. }
  701. indented := new(bytes.Buffer)
  702. indented.WriteByte('[')
  703. status := 0
  704. for _, name := range cmd.Args() {
  705. obj, _, err := readBody(cli.call("GET", "/containers/"+name+"/json", nil, false))
  706. if err != nil {
  707. obj, _, err = readBody(cli.call("GET", "/images/"+name+"/json", nil, false))
  708. if err != nil {
  709. if strings.Contains(err.Error(), "No such") {
  710. fmt.Fprintf(cli.err, "Error: No such image or container: %s\n", name)
  711. } else {
  712. fmt.Fprintf(cli.err, "%s", err)
  713. }
  714. status = 1
  715. continue
  716. }
  717. }
  718. if tmpl == nil {
  719. if err = json.Indent(indented, obj, "", " "); err != nil {
  720. fmt.Fprintf(cli.err, "%s\n", err)
  721. status = 1
  722. continue
  723. }
  724. } else {
  725. // Has template, will render
  726. var value interface{}
  727. if err := json.Unmarshal(obj, &value); err != nil {
  728. fmt.Fprintf(cli.err, "%s\n", err)
  729. status = 1
  730. continue
  731. }
  732. if err := tmpl.Execute(cli.out, value); err != nil {
  733. return err
  734. }
  735. cli.out.Write([]byte{'\n'})
  736. }
  737. indented.WriteString(",")
  738. }
  739. if indented.Len() > 1 {
  740. // Remove trailing ','
  741. indented.Truncate(indented.Len() - 1)
  742. }
  743. indented.WriteByte(']')
  744. if tmpl == nil {
  745. if _, err := io.Copy(cli.out, indented); err != nil {
  746. return err
  747. }
  748. }
  749. if status != 0 {
  750. return &utils.StatusError{StatusCode: status}
  751. }
  752. return nil
  753. }
  754. func (cli *DockerCli) CmdTop(args ...string) error {
  755. cmd := cli.Subcmd("top", "CONTAINER [ps OPTIONS]", "Display the running processes of a container")
  756. if err := cmd.Parse(args); err != nil {
  757. return nil
  758. }
  759. if cmd.NArg() == 0 {
  760. cmd.Usage()
  761. return nil
  762. }
  763. val := url.Values{}
  764. if cmd.NArg() > 1 {
  765. val.Set("ps_args", strings.Join(cmd.Args()[1:], " "))
  766. }
  767. stream, _, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/top?"+val.Encode(), nil, false)
  768. if err != nil {
  769. return err
  770. }
  771. var procs engine.Env
  772. if err := procs.Decode(stream); err != nil {
  773. return err
  774. }
  775. w := tabwriter.NewWriter(cli.out, 20, 1, 3, ' ', 0)
  776. fmt.Fprintln(w, strings.Join(procs.GetList("Titles"), "\t"))
  777. processes := [][]string{}
  778. if err := procs.GetJson("Processes", &processes); err != nil {
  779. return err
  780. }
  781. for _, proc := range processes {
  782. fmt.Fprintln(w, strings.Join(proc, "\t"))
  783. }
  784. w.Flush()
  785. return nil
  786. }
  787. func (cli *DockerCli) CmdPort(args ...string) error {
  788. 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")
  789. if err := cmd.Parse(args); err != nil {
  790. return nil
  791. }
  792. if cmd.NArg() < 1 {
  793. cmd.Usage()
  794. return nil
  795. }
  796. steam, _, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/json", nil, false)
  797. if err != nil {
  798. return err
  799. }
  800. env := engine.Env{}
  801. if err := env.Decode(steam); err != nil {
  802. return err
  803. }
  804. ports := nat.PortMap{}
  805. if err := env.GetSubEnv("NetworkSettings").GetJson("Ports", &ports); err != nil {
  806. return err
  807. }
  808. if cmd.NArg() == 2 {
  809. var (
  810. port = cmd.Arg(1)
  811. proto = "tcp"
  812. parts = strings.SplitN(port, "/", 2)
  813. )
  814. if len(parts) == 2 && len(parts[1]) != 0 {
  815. port = parts[0]
  816. proto = parts[1]
  817. }
  818. natPort := port + "/" + proto
  819. if frontends, exists := ports[nat.Port(port+"/"+proto)]; exists && frontends != nil {
  820. for _, frontend := range frontends {
  821. fmt.Fprintf(cli.out, "%s:%s\n", frontend.HostIp, frontend.HostPort)
  822. }
  823. return nil
  824. }
  825. return fmt.Errorf("Error: No public port '%s' published for %s", natPort, cmd.Arg(0))
  826. }
  827. for from, frontends := range ports {
  828. for _, frontend := range frontends {
  829. fmt.Fprintf(cli.out, "%s -> %s:%s\n", from, frontend.HostIp, frontend.HostPort)
  830. }
  831. }
  832. return nil
  833. }
  834. // 'docker rmi IMAGE' removes all images with the name IMAGE
  835. func (cli *DockerCli) CmdRmi(args ...string) error {
  836. var (
  837. cmd = cli.Subcmd("rmi", "IMAGE [IMAGE...]", "Remove one or more images")
  838. force = cmd.Bool([]string{"f", "-force"}, false, "Force removal of the image")
  839. noprune = cmd.Bool([]string{"-no-prune"}, false, "Do not delete untagged parents")
  840. )
  841. if err := cmd.Parse(args); err != nil {
  842. return nil
  843. }
  844. if cmd.NArg() < 1 {
  845. cmd.Usage()
  846. return nil
  847. }
  848. v := url.Values{}
  849. if *force {
  850. v.Set("force", "1")
  851. }
  852. if *noprune {
  853. v.Set("noprune", "1")
  854. }
  855. var encounteredError error
  856. for _, name := range cmd.Args() {
  857. body, _, err := readBody(cli.call("DELETE", "/images/"+name+"?"+v.Encode(), nil, false))
  858. if err != nil {
  859. fmt.Fprintf(cli.err, "%s\n", err)
  860. encounteredError = fmt.Errorf("Error: failed to remove one or more images")
  861. } else {
  862. outs := engine.NewTable("Created", 0)
  863. if _, err := outs.ReadListFrom(body); err != nil {
  864. fmt.Fprintf(cli.err, "%s\n", err)
  865. encounteredError = fmt.Errorf("Error: failed to remove one or more images")
  866. continue
  867. }
  868. for _, out := range outs.Data {
  869. if out.Get("Deleted") != "" {
  870. fmt.Fprintf(cli.out, "Deleted: %s\n", out.Get("Deleted"))
  871. } else {
  872. fmt.Fprintf(cli.out, "Untagged: %s\n", out.Get("Untagged"))
  873. }
  874. }
  875. }
  876. }
  877. return encounteredError
  878. }
  879. func (cli *DockerCli) CmdHistory(args ...string) error {
  880. cmd := cli.Subcmd("history", "IMAGE", "Show the history of an image")
  881. quiet := cmd.Bool([]string{"q", "-quiet"}, false, "Only show numeric IDs")
  882. noTrunc := cmd.Bool([]string{"#notrunc", "-no-trunc"}, false, "Don't truncate output")
  883. if err := cmd.Parse(args); err != nil {
  884. return nil
  885. }
  886. if cmd.NArg() != 1 {
  887. cmd.Usage()
  888. return nil
  889. }
  890. body, _, err := readBody(cli.call("GET", "/images/"+cmd.Arg(0)+"/history", nil, false))
  891. if err != nil {
  892. return err
  893. }
  894. outs := engine.NewTable("Created", 0)
  895. if _, err := outs.ReadListFrom(body); err != nil {
  896. return err
  897. }
  898. w := tabwriter.NewWriter(cli.out, 20, 1, 3, ' ', 0)
  899. if !*quiet {
  900. fmt.Fprintln(w, "IMAGE\tCREATED\tCREATED BY\tSIZE")
  901. }
  902. for _, out := range outs.Data {
  903. outID := out.Get("Id")
  904. if !*quiet {
  905. if *noTrunc {
  906. fmt.Fprintf(w, "%s\t", outID)
  907. } else {
  908. fmt.Fprintf(w, "%s\t", utils.TruncateID(outID))
  909. }
  910. fmt.Fprintf(w, "%s ago\t", units.HumanDuration(time.Now().UTC().Sub(time.Unix(out.GetInt64("Created"), 0))))
  911. if *noTrunc {
  912. fmt.Fprintf(w, "%s\t", out.Get("CreatedBy"))
  913. } else {
  914. fmt.Fprintf(w, "%s\t", utils.Trunc(out.Get("CreatedBy"), 45))
  915. }
  916. fmt.Fprintf(w, "%s\n", units.HumanSize(out.GetInt64("Size")))
  917. } else {
  918. if *noTrunc {
  919. fmt.Fprintln(w, outID)
  920. } else {
  921. fmt.Fprintln(w, utils.TruncateID(outID))
  922. }
  923. }
  924. }
  925. w.Flush()
  926. return nil
  927. }
  928. func (cli *DockerCli) CmdRm(args ...string) error {
  929. cmd := cli.Subcmd("rm", "CONTAINER [CONTAINER...]", "Remove one or more containers")
  930. v := cmd.Bool([]string{"v", "-volumes"}, false, "Remove the volumes associated with the container")
  931. link := cmd.Bool([]string{"l", "#link", "-link"}, false, "Remove the specified link and not the underlying container")
  932. force := cmd.Bool([]string{"f", "-force"}, false, "Force the removal of a running container (uses SIGKILL)")
  933. if err := cmd.Parse(args); err != nil {
  934. return nil
  935. }
  936. if cmd.NArg() < 1 {
  937. cmd.Usage()
  938. return nil
  939. }
  940. val := url.Values{}
  941. if *v {
  942. val.Set("v", "1")
  943. }
  944. if *link {
  945. val.Set("link", "1")
  946. }
  947. if *force {
  948. val.Set("force", "1")
  949. }
  950. var encounteredError error
  951. for _, name := range cmd.Args() {
  952. _, _, err := readBody(cli.call("DELETE", "/containers/"+name+"?"+val.Encode(), nil, false))
  953. if err != nil {
  954. fmt.Fprintf(cli.err, "%s\n", err)
  955. encounteredError = fmt.Errorf("Error: failed to remove one or more containers")
  956. } else {
  957. fmt.Fprintf(cli.out, "%s\n", name)
  958. }
  959. }
  960. return encounteredError
  961. }
  962. // 'docker kill NAME' kills a running container
  963. func (cli *DockerCli) CmdKill(args ...string) error {
  964. cmd := cli.Subcmd("kill", "CONTAINER [CONTAINER...]", "Kill a running container using SIGKILL or a specified signal")
  965. signal := cmd.String([]string{"s", "-signal"}, "KILL", "Signal to send to the container")
  966. if err := cmd.Parse(args); err != nil {
  967. return nil
  968. }
  969. if cmd.NArg() < 1 {
  970. cmd.Usage()
  971. return nil
  972. }
  973. var encounteredError error
  974. for _, name := range cmd.Args() {
  975. if _, _, err := readBody(cli.call("POST", fmt.Sprintf("/containers/%s/kill?signal=%s", name, *signal), nil, false)); err != nil {
  976. fmt.Fprintf(cli.err, "%s\n", err)
  977. encounteredError = fmt.Errorf("Error: failed to kill one or more containers")
  978. } else {
  979. fmt.Fprintf(cli.out, "%s\n", name)
  980. }
  981. }
  982. return encounteredError
  983. }
  984. func (cli *DockerCli) CmdImport(args ...string) error {
  985. 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.")
  986. if err := cmd.Parse(args); err != nil {
  987. return nil
  988. }
  989. if cmd.NArg() < 1 {
  990. cmd.Usage()
  991. return nil
  992. }
  993. var (
  994. v = url.Values{}
  995. src = cmd.Arg(0)
  996. repository = cmd.Arg(1)
  997. )
  998. v.Set("fromSrc", src)
  999. v.Set("repo", repository)
  1000. if cmd.NArg() == 3 {
  1001. fmt.Fprintf(cli.err, "[DEPRECATED] The format 'URL|- [REPOSITORY [TAG]]' as been deprecated. Please use URL|- [REPOSITORY[:TAG]]\n")
  1002. v.Set("tag", cmd.Arg(2))
  1003. }
  1004. if repository != "" {
  1005. //Check if the given image name can be resolved
  1006. repo, _ := parsers.ParseRepositoryTag(repository)
  1007. if _, _, err := registry.ResolveRepositoryName(repo); err != nil {
  1008. return err
  1009. }
  1010. }
  1011. var in io.Reader
  1012. if src == "-" {
  1013. in = cli.in
  1014. }
  1015. return cli.stream("POST", "/images/create?"+v.Encode(), in, cli.out, nil)
  1016. }
  1017. func (cli *DockerCli) CmdPush(args ...string) error {
  1018. cmd := cli.Subcmd("push", "NAME[:TAG]", "Push an image or a repository to the registry")
  1019. if err := cmd.Parse(args); err != nil {
  1020. return nil
  1021. }
  1022. name := cmd.Arg(0)
  1023. if name == "" {
  1024. cmd.Usage()
  1025. return nil
  1026. }
  1027. cli.LoadConfigFile()
  1028. remote, tag := parsers.ParseRepositoryTag(name)
  1029. // Resolve the Repository name from fqn to hostname + name
  1030. hostname, _, err := registry.ResolveRepositoryName(remote)
  1031. if err != nil {
  1032. return err
  1033. }
  1034. // Resolve the Auth config relevant for this server
  1035. authConfig := cli.configFile.ResolveAuthConfig(hostname)
  1036. // If we're not using a custom registry, we know the restrictions
  1037. // applied to repository names and can warn the user in advance.
  1038. // Custom repositories can have different rules, and we must also
  1039. // allow pushing by image ID.
  1040. if len(strings.SplitN(name, "/", 2)) == 1 {
  1041. username := cli.configFile.Configs[registry.IndexServerAddress()].Username
  1042. if username == "" {
  1043. username = "<user>"
  1044. }
  1045. return fmt.Errorf("You cannot push a \"root\" repository. Please rename your repository in <user>/<repo> (ex: %s/%s)", username, name)
  1046. }
  1047. v := url.Values{}
  1048. v.Set("tag", tag)
  1049. push := func(authConfig registry.AuthConfig) error {
  1050. buf, err := json.Marshal(authConfig)
  1051. if err != nil {
  1052. return err
  1053. }
  1054. registryAuthHeader := []string{
  1055. base64.URLEncoding.EncodeToString(buf),
  1056. }
  1057. return cli.stream("POST", "/images/"+remote+"/push?"+v.Encode(), nil, cli.out, map[string][]string{
  1058. "X-Registry-Auth": registryAuthHeader,
  1059. })
  1060. }
  1061. if err := push(authConfig); err != nil {
  1062. if strings.Contains(err.Error(), "Status 401") {
  1063. fmt.Fprintln(cli.out, "\nPlease login prior to push:")
  1064. if err := cli.CmdLogin(hostname); err != nil {
  1065. return err
  1066. }
  1067. authConfig := cli.configFile.ResolveAuthConfig(hostname)
  1068. return push(authConfig)
  1069. }
  1070. return err
  1071. }
  1072. return nil
  1073. }
  1074. func (cli *DockerCli) CmdPull(args ...string) error {
  1075. cmd := cli.Subcmd("pull", "NAME[:TAG]", "Pull an image or a repository from the registry")
  1076. allTags := cmd.Bool([]string{"a", "-all-tags"}, false, "Download all tagged images in the repository")
  1077. if err := cmd.Parse(args); err != nil {
  1078. return nil
  1079. }
  1080. if cmd.NArg() != 1 {
  1081. cmd.Usage()
  1082. return nil
  1083. }
  1084. var (
  1085. v = url.Values{}
  1086. remote = cmd.Arg(0)
  1087. newRemote = remote
  1088. )
  1089. taglessRemote, tag := parsers.ParseRepositoryTag(remote)
  1090. if tag == "" && !*allTags {
  1091. newRemote = taglessRemote + ":latest"
  1092. }
  1093. if tag != "" && *allTags {
  1094. return fmt.Errorf("tag can't be used with --all-tags/-a")
  1095. }
  1096. v.Set("fromImage", newRemote)
  1097. // Resolve the Repository name from fqn to hostname + name
  1098. hostname, _, err := registry.ResolveRepositoryName(taglessRemote)
  1099. if err != nil {
  1100. return err
  1101. }
  1102. cli.LoadConfigFile()
  1103. // Resolve the Auth config relevant for this server
  1104. authConfig := cli.configFile.ResolveAuthConfig(hostname)
  1105. pull := func(authConfig registry.AuthConfig) error {
  1106. buf, err := json.Marshal(authConfig)
  1107. if err != nil {
  1108. return err
  1109. }
  1110. registryAuthHeader := []string{
  1111. base64.URLEncoding.EncodeToString(buf),
  1112. }
  1113. return cli.stream("POST", "/images/create?"+v.Encode(), nil, cli.out, map[string][]string{
  1114. "X-Registry-Auth": registryAuthHeader,
  1115. })
  1116. }
  1117. if err := pull(authConfig); err != nil {
  1118. if strings.Contains(err.Error(), "Status 401") {
  1119. fmt.Fprintln(cli.out, "\nPlease login prior to pull:")
  1120. if err := cli.CmdLogin(hostname); err != nil {
  1121. return err
  1122. }
  1123. authConfig := cli.configFile.ResolveAuthConfig(hostname)
  1124. return pull(authConfig)
  1125. }
  1126. return err
  1127. }
  1128. return nil
  1129. }
  1130. func (cli *DockerCli) CmdImages(args ...string) error {
  1131. cmd := cli.Subcmd("images", "[NAME]", "List images")
  1132. quiet := cmd.Bool([]string{"q", "-quiet"}, false, "Only show numeric IDs")
  1133. all := cmd.Bool([]string{"a", "-all"}, false, "Show all images (by default filter out the intermediate image layers)")
  1134. noTrunc := cmd.Bool([]string{"#notrunc", "-no-trunc"}, false, "Don't truncate output")
  1135. // FIXME: --viz and --tree are deprecated. Remove them in a future version.
  1136. flViz := cmd.Bool([]string{"#v", "#viz", "#-viz"}, false, "Output graph in graphviz format")
  1137. flTree := cmd.Bool([]string{"#t", "#tree", "#-tree"}, false, "Output graph in tree format")
  1138. flFilter := opts.NewListOpts(nil)
  1139. cmd.Var(&flFilter, []string{"f", "-filter"}, "Provide filter values (i.e. 'dangling=true')")
  1140. if err := cmd.Parse(args); err != nil {
  1141. return nil
  1142. }
  1143. if cmd.NArg() > 1 {
  1144. cmd.Usage()
  1145. return nil
  1146. }
  1147. // Consolidate all filter flags, and sanity check them early.
  1148. // They'll get process in the daemon/server.
  1149. imageFilterArgs := filters.Args{}
  1150. for _, f := range flFilter.GetAll() {
  1151. var err error
  1152. imageFilterArgs, err = filters.ParseFlag(f, imageFilterArgs)
  1153. if err != nil {
  1154. return err
  1155. }
  1156. }
  1157. matchName := cmd.Arg(0)
  1158. // FIXME: --viz and --tree are deprecated. Remove them in a future version.
  1159. if *flViz || *flTree {
  1160. v := url.Values{
  1161. "all": []string{"1"},
  1162. }
  1163. if len(imageFilterArgs) > 0 {
  1164. filterJson, err := filters.ToParam(imageFilterArgs)
  1165. if err != nil {
  1166. return err
  1167. }
  1168. v.Set("filters", filterJson)
  1169. }
  1170. body, _, err := readBody(cli.call("GET", "/images/json?"+v.Encode(), nil, false))
  1171. if err != nil {
  1172. return err
  1173. }
  1174. outs := engine.NewTable("Created", 0)
  1175. if _, err := outs.ReadListFrom(body); err != nil {
  1176. return err
  1177. }
  1178. var (
  1179. printNode func(cli *DockerCli, noTrunc bool, image *engine.Env, prefix string)
  1180. startImage *engine.Env
  1181. roots = engine.NewTable("Created", outs.Len())
  1182. byParent = make(map[string]*engine.Table)
  1183. )
  1184. for _, image := range outs.Data {
  1185. if image.Get("ParentId") == "" {
  1186. roots.Add(image)
  1187. } else {
  1188. if children, exists := byParent[image.Get("ParentId")]; exists {
  1189. children.Add(image)
  1190. } else {
  1191. byParent[image.Get("ParentId")] = engine.NewTable("Created", 1)
  1192. byParent[image.Get("ParentId")].Add(image)
  1193. }
  1194. }
  1195. if matchName != "" {
  1196. if matchName == image.Get("Id") || matchName == utils.TruncateID(image.Get("Id")) {
  1197. startImage = image
  1198. }
  1199. for _, repotag := range image.GetList("RepoTags") {
  1200. if repotag == matchName {
  1201. startImage = image
  1202. }
  1203. }
  1204. }
  1205. }
  1206. if *flViz {
  1207. fmt.Fprintf(cli.out, "digraph docker {\n")
  1208. printNode = (*DockerCli).printVizNode
  1209. } else {
  1210. printNode = (*DockerCli).printTreeNode
  1211. }
  1212. if startImage != nil {
  1213. root := engine.NewTable("Created", 1)
  1214. root.Add(startImage)
  1215. cli.WalkTree(*noTrunc, root, byParent, "", printNode)
  1216. } else if matchName == "" {
  1217. cli.WalkTree(*noTrunc, roots, byParent, "", printNode)
  1218. }
  1219. if *flViz {
  1220. fmt.Fprintf(cli.out, " base [style=invisible]\n}\n")
  1221. }
  1222. } else {
  1223. v := url.Values{}
  1224. if len(imageFilterArgs) > 0 {
  1225. filterJson, err := filters.ToParam(imageFilterArgs)
  1226. if err != nil {
  1227. return err
  1228. }
  1229. v.Set("filters", filterJson)
  1230. }
  1231. if cmd.NArg() == 1 {
  1232. // FIXME rename this parameter, to not be confused with the filters flag
  1233. v.Set("filter", matchName)
  1234. }
  1235. if *all {
  1236. v.Set("all", "1")
  1237. }
  1238. body, _, err := readBody(cli.call("GET", "/images/json?"+v.Encode(), nil, false))
  1239. if err != nil {
  1240. return err
  1241. }
  1242. outs := engine.NewTable("Created", 0)
  1243. if _, err := outs.ReadListFrom(body); err != nil {
  1244. return err
  1245. }
  1246. w := tabwriter.NewWriter(cli.out, 20, 1, 3, ' ', 0)
  1247. if !*quiet {
  1248. fmt.Fprintln(w, "REPOSITORY\tTAG\tIMAGE ID\tCREATED\tVIRTUAL SIZE")
  1249. }
  1250. for _, out := range outs.Data {
  1251. for _, repotag := range out.GetList("RepoTags") {
  1252. repo, tag := parsers.ParseRepositoryTag(repotag)
  1253. outID := out.Get("Id")
  1254. if !*noTrunc {
  1255. outID = utils.TruncateID(outID)
  1256. }
  1257. if !*quiet {
  1258. 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")))
  1259. } else {
  1260. fmt.Fprintln(w, outID)
  1261. }
  1262. }
  1263. }
  1264. if !*quiet {
  1265. w.Flush()
  1266. }
  1267. }
  1268. return nil
  1269. }
  1270. // FIXME: --viz and --tree are deprecated. Remove them in a future version.
  1271. 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)) {
  1272. length := images.Len()
  1273. if length > 1 {
  1274. for index, image := range images.Data {
  1275. if index+1 == length {
  1276. printNode(cli, noTrunc, image, prefix+"└─")
  1277. if subimages, exists := byParent[image.Get("Id")]; exists {
  1278. cli.WalkTree(noTrunc, subimages, byParent, prefix+" ", printNode)
  1279. }
  1280. } else {
  1281. printNode(cli, noTrunc, image, prefix+"\u251C─")
  1282. if subimages, exists := byParent[image.Get("Id")]; exists {
  1283. cli.WalkTree(noTrunc, subimages, byParent, prefix+"\u2502 ", printNode)
  1284. }
  1285. }
  1286. }
  1287. } else {
  1288. for _, image := range images.Data {
  1289. printNode(cli, noTrunc, image, prefix+"└─")
  1290. if subimages, exists := byParent[image.Get("Id")]; exists {
  1291. cli.WalkTree(noTrunc, subimages, byParent, prefix+" ", printNode)
  1292. }
  1293. }
  1294. }
  1295. }
  1296. // FIXME: --viz and --tree are deprecated. Remove them in a future version.
  1297. func (cli *DockerCli) printVizNode(noTrunc bool, image *engine.Env, prefix string) {
  1298. var (
  1299. imageID string
  1300. parentID string
  1301. )
  1302. if noTrunc {
  1303. imageID = image.Get("Id")
  1304. parentID = image.Get("ParentId")
  1305. } else {
  1306. imageID = utils.TruncateID(image.Get("Id"))
  1307. parentID = utils.TruncateID(image.Get("ParentId"))
  1308. }
  1309. if parentID == "" {
  1310. fmt.Fprintf(cli.out, " base -> \"%s\" [style=invis]\n", imageID)
  1311. } else {
  1312. fmt.Fprintf(cli.out, " \"%s\" -> \"%s\"\n", parentID, imageID)
  1313. }
  1314. if image.GetList("RepoTags")[0] != "<none>:<none>" {
  1315. fmt.Fprintf(cli.out, " \"%s\" [label=\"%s\\n%s\",shape=box,fillcolor=\"paleturquoise\",style=\"filled,rounded\"];\n",
  1316. imageID, imageID, strings.Join(image.GetList("RepoTags"), "\\n"))
  1317. }
  1318. }
  1319. // FIXME: --viz and --tree are deprecated. Remove them in a future version.
  1320. func (cli *DockerCli) printTreeNode(noTrunc bool, image *engine.Env, prefix string) {
  1321. var imageID string
  1322. if noTrunc {
  1323. imageID = image.Get("Id")
  1324. } else {
  1325. imageID = utils.TruncateID(image.Get("Id"))
  1326. }
  1327. fmt.Fprintf(cli.out, "%s%s Virtual Size: %s", prefix, imageID, units.HumanSize(image.GetInt64("VirtualSize")))
  1328. if image.GetList("RepoTags")[0] != "<none>:<none>" {
  1329. fmt.Fprintf(cli.out, " Tags: %s\n", strings.Join(image.GetList("RepoTags"), ", "))
  1330. } else {
  1331. fmt.Fprint(cli.out, "\n")
  1332. }
  1333. }
  1334. func (cli *DockerCli) CmdPs(args ...string) error {
  1335. var (
  1336. err error
  1337. psFilterArgs = filters.Args{}
  1338. v = url.Values{}
  1339. cmd = cli.Subcmd("ps", "", "List containers")
  1340. quiet = cmd.Bool([]string{"q", "-quiet"}, false, "Only display numeric IDs")
  1341. size = cmd.Bool([]string{"s", "-size"}, false, "Display sizes")
  1342. all = cmd.Bool([]string{"a", "-all"}, false, "Show all containers. Only running containers are shown by default.")
  1343. noTrunc = cmd.Bool([]string{"#notrunc", "-no-trunc"}, false, "Don't truncate output")
  1344. nLatest = cmd.Bool([]string{"l", "-latest"}, false, "Show only the latest created container, include non-running ones.")
  1345. since = cmd.String([]string{"#sinceId", "#-since-id", "-since"}, "", "Show only containers created since Id or Name, include non-running ones.")
  1346. before = cmd.String([]string{"#beforeId", "#-before-id", "-before"}, "", "Show only container created before Id or Name, include non-running ones.")
  1347. last = cmd.Int([]string{"n"}, -1, "Show n last created containers, include non-running ones.")
  1348. flFilter = opts.NewListOpts(nil)
  1349. )
  1350. cmd.Var(&flFilter, []string{"f", "-filter"}, "Provide filter values. Valid filters:\nexited=<int> - containers with exit code of <int>\nstatus=(restarting|running|paused|exited)")
  1351. if err := cmd.Parse(args); err != nil {
  1352. return nil
  1353. }
  1354. if *last == -1 && *nLatest {
  1355. *last = 1
  1356. }
  1357. if *all {
  1358. v.Set("all", "1")
  1359. }
  1360. if *last != -1 {
  1361. v.Set("limit", strconv.Itoa(*last))
  1362. }
  1363. if *since != "" {
  1364. v.Set("since", *since)
  1365. }
  1366. if *before != "" {
  1367. v.Set("before", *before)
  1368. }
  1369. if *size {
  1370. v.Set("size", "1")
  1371. }
  1372. // Consolidate all filter flags, and sanity check them.
  1373. // They'll get processed in the daemon/server.
  1374. for _, f := range flFilter.GetAll() {
  1375. if psFilterArgs, err = filters.ParseFlag(f, psFilterArgs); err != nil {
  1376. return err
  1377. }
  1378. }
  1379. if len(psFilterArgs) > 0 {
  1380. filterJson, err := filters.ToParam(psFilterArgs)
  1381. if err != nil {
  1382. return err
  1383. }
  1384. v.Set("filters", filterJson)
  1385. }
  1386. body, _, err := readBody(cli.call("GET", "/containers/json?"+v.Encode(), nil, false))
  1387. if err != nil {
  1388. return err
  1389. }
  1390. outs := engine.NewTable("Created", 0)
  1391. if _, err := outs.ReadListFrom(body); err != nil {
  1392. return err
  1393. }
  1394. w := tabwriter.NewWriter(cli.out, 20, 1, 3, ' ', 0)
  1395. if !*quiet {
  1396. fmt.Fprint(w, "CONTAINER ID\tIMAGE\tCOMMAND\tCREATED\tSTATUS\tPORTS\tNAMES")
  1397. if *size {
  1398. fmt.Fprintln(w, "\tSIZE")
  1399. } else {
  1400. fmt.Fprint(w, "\n")
  1401. }
  1402. }
  1403. stripNamePrefix := func(ss []string) []string {
  1404. for i, s := range ss {
  1405. ss[i] = s[1:]
  1406. }
  1407. return ss
  1408. }
  1409. for _, out := range outs.Data {
  1410. outID := out.Get("Id")
  1411. if !*noTrunc {
  1412. outID = utils.TruncateID(outID)
  1413. }
  1414. if *quiet {
  1415. fmt.Fprintln(w, outID)
  1416. continue
  1417. }
  1418. var (
  1419. outNames = stripNamePrefix(out.GetList("Names"))
  1420. outCommand = strconv.Quote(out.Get("Command"))
  1421. ports = engine.NewTable("", 0)
  1422. )
  1423. if !*noTrunc {
  1424. outCommand = utils.Trunc(outCommand, 20)
  1425. // only display the default name for the container with notrunc is passed
  1426. for _, name := range outNames {
  1427. if len(strings.Split(name, "/")) == 1 {
  1428. outNames = []string{name}
  1429. break
  1430. }
  1431. }
  1432. }
  1433. ports.ReadListFrom([]byte(out.Get("Ports")))
  1434. fmt.Fprintf(w, "%s\t%s\t%s\t%s ago\t%s\t%s\t%s\t", outID, out.Get("Image"), outCommand,
  1435. units.HumanDuration(time.Now().UTC().Sub(time.Unix(out.GetInt64("Created"), 0))),
  1436. out.Get("Status"), api.DisplayablePorts(ports), strings.Join(outNames, ","))
  1437. if *size {
  1438. if out.GetInt("SizeRootFs") > 0 {
  1439. fmt.Fprintf(w, "%s (virtual %s)\n", units.HumanSize(out.GetInt64("SizeRw")), units.HumanSize(out.GetInt64("SizeRootFs")))
  1440. } else {
  1441. fmt.Fprintf(w, "%s\n", units.HumanSize(out.GetInt64("SizeRw")))
  1442. }
  1443. continue
  1444. }
  1445. fmt.Fprint(w, "\n")
  1446. }
  1447. if !*quiet {
  1448. w.Flush()
  1449. }
  1450. return nil
  1451. }
  1452. func (cli *DockerCli) CmdCommit(args ...string) error {
  1453. cmd := cli.Subcmd("commit", "CONTAINER [REPOSITORY[:TAG]]", "Create a new image from a container's changes")
  1454. flPause := cmd.Bool([]string{"p", "-pause"}, true, "Pause container during commit")
  1455. flComment := cmd.String([]string{"m", "-message"}, "", "Commit message")
  1456. flAuthor := cmd.String([]string{"a", "#author", "-author"}, "", "Author (e.g., \"John Hannibal Smith <hannibal@a-team.com>\")")
  1457. // FIXME: --run is deprecated, it will be replaced with inline Dockerfile commands.
  1458. 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")
  1459. if err := cmd.Parse(args); err != nil {
  1460. return nil
  1461. }
  1462. var (
  1463. name = cmd.Arg(0)
  1464. repository, tag = parsers.ParseRepositoryTag(cmd.Arg(1))
  1465. )
  1466. if name == "" || len(cmd.Args()) > 2 {
  1467. cmd.Usage()
  1468. return nil
  1469. }
  1470. //Check if the given image name can be resolved
  1471. if repository != "" {
  1472. if _, _, err := registry.ResolveRepositoryName(repository); err != nil {
  1473. return err
  1474. }
  1475. }
  1476. v := url.Values{}
  1477. v.Set("container", name)
  1478. v.Set("repo", repository)
  1479. v.Set("tag", tag)
  1480. v.Set("comment", *flComment)
  1481. v.Set("author", *flAuthor)
  1482. if *flPause != true {
  1483. v.Set("pause", "0")
  1484. }
  1485. var (
  1486. config *runconfig.Config
  1487. env engine.Env
  1488. )
  1489. if *flConfig != "" {
  1490. config = &runconfig.Config{}
  1491. if err := json.Unmarshal([]byte(*flConfig), config); err != nil {
  1492. return err
  1493. }
  1494. }
  1495. stream, _, err := cli.call("POST", "/commit?"+v.Encode(), config, false)
  1496. if err != nil {
  1497. return err
  1498. }
  1499. if err := env.Decode(stream); err != nil {
  1500. return err
  1501. }
  1502. fmt.Fprintf(cli.out, "%s\n", env.Get("Id"))
  1503. return nil
  1504. }
  1505. func (cli *DockerCli) CmdEvents(args ...string) error {
  1506. cmd := cli.Subcmd("events", "", "Get real time events from the server")
  1507. since := cmd.String([]string{"#since", "-since"}, "", "Show all events created since timestamp")
  1508. until := cmd.String([]string{"-until"}, "", "Stream events until this timestamp")
  1509. if err := cmd.Parse(args); err != nil {
  1510. return nil
  1511. }
  1512. if cmd.NArg() != 0 {
  1513. cmd.Usage()
  1514. return nil
  1515. }
  1516. var (
  1517. v = url.Values{}
  1518. loc = time.FixedZone(time.Now().Zone())
  1519. )
  1520. var setTime = func(key, value string) {
  1521. format := timeutils.RFC3339NanoFixed
  1522. if len(value) < len(format) {
  1523. format = format[:len(value)]
  1524. }
  1525. if t, err := time.ParseInLocation(format, value, loc); err == nil {
  1526. v.Set(key, strconv.FormatInt(t.Unix(), 10))
  1527. } else {
  1528. v.Set(key, value)
  1529. }
  1530. }
  1531. if *since != "" {
  1532. setTime("since", *since)
  1533. }
  1534. if *until != "" {
  1535. setTime("until", *until)
  1536. }
  1537. if err := cli.stream("GET", "/events?"+v.Encode(), nil, cli.out, nil); err != nil {
  1538. return err
  1539. }
  1540. return nil
  1541. }
  1542. func (cli *DockerCli) CmdExport(args ...string) error {
  1543. cmd := cli.Subcmd("export", "CONTAINER", "Export the contents of a filesystem as a tar archive to STDOUT")
  1544. if err := cmd.Parse(args); err != nil {
  1545. return nil
  1546. }
  1547. if cmd.NArg() != 1 {
  1548. cmd.Usage()
  1549. return nil
  1550. }
  1551. if err := cli.stream("GET", "/containers/"+cmd.Arg(0)+"/export", nil, cli.out, nil); err != nil {
  1552. return err
  1553. }
  1554. return nil
  1555. }
  1556. func (cli *DockerCli) CmdDiff(args ...string) error {
  1557. cmd := cli.Subcmd("diff", "CONTAINER", "Inspect changes on a container's filesystem")
  1558. if err := cmd.Parse(args); err != nil {
  1559. return nil
  1560. }
  1561. if cmd.NArg() != 1 {
  1562. cmd.Usage()
  1563. return nil
  1564. }
  1565. body, _, err := readBody(cli.call("GET", "/containers/"+cmd.Arg(0)+"/changes", nil, false))
  1566. if err != nil {
  1567. return err
  1568. }
  1569. outs := engine.NewTable("", 0)
  1570. if _, err := outs.ReadListFrom(body); err != nil {
  1571. return err
  1572. }
  1573. for _, change := range outs.Data {
  1574. var kind string
  1575. switch change.GetInt("Kind") {
  1576. case archive.ChangeModify:
  1577. kind = "C"
  1578. case archive.ChangeAdd:
  1579. kind = "A"
  1580. case archive.ChangeDelete:
  1581. kind = "D"
  1582. }
  1583. fmt.Fprintf(cli.out, "%s %s\n", kind, change.Get("Path"))
  1584. }
  1585. return nil
  1586. }
  1587. func (cli *DockerCli) CmdLogs(args ...string) error {
  1588. var (
  1589. cmd = cli.Subcmd("logs", "CONTAINER", "Fetch the logs of a container")
  1590. follow = cmd.Bool([]string{"f", "-follow"}, false, "Follow log output")
  1591. times = cmd.Bool([]string{"t", "-timestamps"}, false, "Show timestamps")
  1592. tail = cmd.String([]string{"-tail"}, "all", "Output the specified number of lines at the end of logs (defaults to all logs)")
  1593. )
  1594. if err := cmd.Parse(args); err != nil {
  1595. return nil
  1596. }
  1597. if cmd.NArg() != 1 {
  1598. cmd.Usage()
  1599. return nil
  1600. }
  1601. name := cmd.Arg(0)
  1602. steam, _, err := cli.call("GET", "/containers/"+name+"/json", nil, false)
  1603. if err != nil {
  1604. return err
  1605. }
  1606. env := engine.Env{}
  1607. if err := env.Decode(steam); err != nil {
  1608. return err
  1609. }
  1610. v := url.Values{}
  1611. v.Set("stdout", "1")
  1612. v.Set("stderr", "1")
  1613. if *times {
  1614. v.Set("timestamps", "1")
  1615. }
  1616. if *follow {
  1617. v.Set("follow", "1")
  1618. }
  1619. v.Set("tail", *tail)
  1620. return cli.streamHelper("GET", "/containers/"+name+"/logs?"+v.Encode(), env.GetSubEnv("Config").GetBool("Tty"), nil, cli.out, cli.err, nil)
  1621. }
  1622. func (cli *DockerCli) CmdAttach(args ...string) error {
  1623. var (
  1624. cmd = cli.Subcmd("attach", "CONTAINER", "Attach to a running container")
  1625. noStdin = cmd.Bool([]string{"#nostdin", "-no-stdin"}, false, "Do not attach STDIN")
  1626. 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.")
  1627. )
  1628. if err := cmd.Parse(args); err != nil {
  1629. return nil
  1630. }
  1631. if cmd.NArg() != 1 {
  1632. cmd.Usage()
  1633. return nil
  1634. }
  1635. name := cmd.Arg(0)
  1636. stream, _, err := cli.call("GET", "/containers/"+name+"/json", nil, false)
  1637. if err != nil {
  1638. return err
  1639. }
  1640. env := engine.Env{}
  1641. if err := env.Decode(stream); err != nil {
  1642. return err
  1643. }
  1644. if !env.GetSubEnv("State").GetBool("Running") {
  1645. return fmt.Errorf("You cannot attach to a stopped container, start it first")
  1646. }
  1647. var (
  1648. config = env.GetSubEnv("Config")
  1649. tty = config.GetBool("Tty")
  1650. )
  1651. if tty && cli.isTerminalOut {
  1652. if err := cli.monitorTtySize(cmd.Arg(0), false); err != nil {
  1653. log.Debugf("Error monitoring TTY size: %s", err)
  1654. }
  1655. }
  1656. var in io.ReadCloser
  1657. v := url.Values{}
  1658. v.Set("stream", "1")
  1659. if !*noStdin && config.GetBool("OpenStdin") {
  1660. v.Set("stdin", "1")
  1661. in = cli.in
  1662. }
  1663. v.Set("stdout", "1")
  1664. v.Set("stderr", "1")
  1665. if *proxy && !tty {
  1666. sigc := cli.forwardAllSignals(cmd.Arg(0))
  1667. defer signal.StopCatch(sigc)
  1668. }
  1669. if err := cli.hijack("POST", "/containers/"+cmd.Arg(0)+"/attach?"+v.Encode(), tty, in, cli.out, cli.err, nil, nil); err != nil {
  1670. return err
  1671. }
  1672. _, status, err := getExitCode(cli, cmd.Arg(0))
  1673. if err != nil {
  1674. return err
  1675. }
  1676. if status != 0 {
  1677. return &utils.StatusError{StatusCode: status}
  1678. }
  1679. return nil
  1680. }
  1681. func (cli *DockerCli) CmdSearch(args ...string) error {
  1682. cmd := cli.Subcmd("search", "TERM", "Search the Docker Hub for images")
  1683. noTrunc := cmd.Bool([]string{"#notrunc", "-no-trunc"}, false, "Don't truncate output")
  1684. trusted := cmd.Bool([]string{"#t", "#trusted", "#-trusted"}, false, "Only show trusted builds")
  1685. automated := cmd.Bool([]string{"-automated"}, false, "Only show automated builds")
  1686. stars := cmd.Int([]string{"s", "#stars", "-stars"}, 0, "Only displays with at least x stars")
  1687. if err := cmd.Parse(args); err != nil {
  1688. return nil
  1689. }
  1690. if cmd.NArg() != 1 {
  1691. cmd.Usage()
  1692. return nil
  1693. }
  1694. v := url.Values{}
  1695. v.Set("term", cmd.Arg(0))
  1696. body, _, err := readBody(cli.call("GET", "/images/search?"+v.Encode(), nil, true))
  1697. if err != nil {
  1698. return err
  1699. }
  1700. outs := engine.NewTable("star_count", 0)
  1701. if _, err := outs.ReadListFrom(body); err != nil {
  1702. return err
  1703. }
  1704. w := tabwriter.NewWriter(cli.out, 10, 1, 3, ' ', 0)
  1705. fmt.Fprintf(w, "NAME\tDESCRIPTION\tSTARS\tOFFICIAL\tAUTOMATED\n")
  1706. for _, out := range outs.Data {
  1707. if ((*automated || *trusted) && (!out.GetBool("is_trusted") && !out.GetBool("is_automated"))) || (*stars > out.GetInt("star_count")) {
  1708. continue
  1709. }
  1710. desc := strings.Replace(out.Get("description"), "\n", " ", -1)
  1711. desc = strings.Replace(desc, "\r", " ", -1)
  1712. if !*noTrunc && len(desc) > 45 {
  1713. desc = utils.Trunc(desc, 42) + "..."
  1714. }
  1715. fmt.Fprintf(w, "%s\t%s\t%d\t", out.Get("name"), desc, out.GetInt("star_count"))
  1716. if out.GetBool("is_official") {
  1717. fmt.Fprint(w, "[OK]")
  1718. }
  1719. fmt.Fprint(w, "\t")
  1720. if out.GetBool("is_automated") || out.GetBool("is_trusted") {
  1721. fmt.Fprint(w, "[OK]")
  1722. }
  1723. fmt.Fprint(w, "\n")
  1724. }
  1725. w.Flush()
  1726. return nil
  1727. }
  1728. // Ports type - Used to parse multiple -p flags
  1729. type ports []int
  1730. func (cli *DockerCli) CmdTag(args ...string) error {
  1731. cmd := cli.Subcmd("tag", "IMAGE[:TAG] [REGISTRYHOST/][USERNAME/]NAME[:TAG]", "Tag an image into a repository")
  1732. force := cmd.Bool([]string{"f", "#force", "-force"}, false, "Force")
  1733. if err := cmd.Parse(args); err != nil {
  1734. return nil
  1735. }
  1736. if cmd.NArg() != 2 {
  1737. cmd.Usage()
  1738. return nil
  1739. }
  1740. var (
  1741. repository, tag = parsers.ParseRepositoryTag(cmd.Arg(1))
  1742. v = url.Values{}
  1743. )
  1744. //Check if the given image name can be resolved
  1745. if _, _, err := registry.ResolveRepositoryName(repository); err != nil {
  1746. return err
  1747. }
  1748. v.Set("repo", repository)
  1749. v.Set("tag", tag)
  1750. if *force {
  1751. v.Set("force", "1")
  1752. }
  1753. if _, _, err := readBody(cli.call("POST", "/images/"+cmd.Arg(0)+"/tag?"+v.Encode(), nil, false)); err != nil {
  1754. return err
  1755. }
  1756. return nil
  1757. }
  1758. func (cli *DockerCli) pullImage(image string) error {
  1759. return cli.pullImageCustomOut(image, cli.out)
  1760. }
  1761. func (cli *DockerCli) pullImageCustomOut(image string, out io.Writer) error {
  1762. v := url.Values{}
  1763. repos, tag := parsers.ParseRepositoryTag(image)
  1764. // pull only the image tagged 'latest' if no tag was specified
  1765. if tag == "" {
  1766. tag = "latest"
  1767. }
  1768. v.Set("fromImage", repos)
  1769. v.Set("tag", tag)
  1770. // Resolve the Repository name from fqn to hostname + name
  1771. hostname, _, err := registry.ResolveRepositoryName(repos)
  1772. if err != nil {
  1773. return err
  1774. }
  1775. // Load the auth config file, to be able to pull the image
  1776. cli.LoadConfigFile()
  1777. // Resolve the Auth config relevant for this server
  1778. authConfig := cli.configFile.ResolveAuthConfig(hostname)
  1779. buf, err := json.Marshal(authConfig)
  1780. if err != nil {
  1781. return err
  1782. }
  1783. registryAuthHeader := []string{
  1784. base64.URLEncoding.EncodeToString(buf),
  1785. }
  1786. if err = cli.stream("POST", "/images/create?"+v.Encode(), nil, out, map[string][]string{"X-Registry-Auth": registryAuthHeader}); err != nil {
  1787. return err
  1788. }
  1789. return nil
  1790. }
  1791. type cidFile struct {
  1792. path string
  1793. file *os.File
  1794. written bool
  1795. }
  1796. func newCIDFile(path string) (*cidFile, error) {
  1797. if _, err := os.Stat(path); err == nil {
  1798. return nil, fmt.Errorf("Container ID file found, make sure the other container isn't running or delete %s", path)
  1799. }
  1800. f, err := os.Create(path)
  1801. if err != nil {
  1802. return nil, fmt.Errorf("Failed to create the container ID file: %s", err)
  1803. }
  1804. return &cidFile{path: path, file: f}, nil
  1805. }
  1806. func (cid *cidFile) Close() error {
  1807. cid.file.Close()
  1808. if !cid.written {
  1809. if err := os.Remove(cid.path); err != nil {
  1810. return fmt.Errorf("failed to remove the CID file '%s': %s \n", cid.path, err)
  1811. }
  1812. }
  1813. return nil
  1814. }
  1815. func (cid *cidFile) Write(id string) error {
  1816. if _, err := cid.file.Write([]byte(id)); err != nil {
  1817. return fmt.Errorf("Failed to write the container ID to the file: %s", err)
  1818. }
  1819. cid.written = true
  1820. return nil
  1821. }
  1822. func (cli *DockerCli) createContainer(config *runconfig.Config, hostConfig *runconfig.HostConfig, cidfile, name string) (engine.Env, error) {
  1823. containerValues := url.Values{}
  1824. if name != "" {
  1825. containerValues.Set("name", name)
  1826. }
  1827. mergedConfig := runconfig.MergeConfigs(config, hostConfig)
  1828. var containerIDFile *cidFile
  1829. if cidfile != "" {
  1830. var err error
  1831. if containerIDFile, err = newCIDFile(cidfile); err != nil {
  1832. return nil, err
  1833. }
  1834. defer containerIDFile.Close()
  1835. }
  1836. //create the container
  1837. stream, statusCode, err := cli.call("POST", "/containers/create?"+containerValues.Encode(), mergedConfig, false)
  1838. //if image not found try to pull it
  1839. if statusCode == 404 {
  1840. fmt.Fprintf(cli.err, "Unable to find image '%s' locally\n", config.Image)
  1841. // we don't want to write to stdout anything apart from container.ID
  1842. if err = cli.pullImageCustomOut(config.Image, cli.err); err != nil {
  1843. return nil, err
  1844. }
  1845. // Retry
  1846. if stream, _, err = cli.call("POST", "/containers/create?"+containerValues.Encode(), mergedConfig, false); err != nil {
  1847. return nil, err
  1848. }
  1849. } else if err != nil {
  1850. return nil, err
  1851. }
  1852. var result engine.Env
  1853. if err := result.Decode(stream); err != nil {
  1854. return nil, err
  1855. }
  1856. for _, warning := range result.GetList("Warnings") {
  1857. fmt.Fprintf(cli.err, "WARNING: %s\n", warning)
  1858. }
  1859. if containerIDFile != nil {
  1860. if err = containerIDFile.Write(result.Get("Id")); err != nil {
  1861. return nil, err
  1862. }
  1863. }
  1864. return result, nil
  1865. }
  1866. func (cli *DockerCli) CmdCreate(args ...string) error {
  1867. cmd := cli.Subcmd("create", "IMAGE [COMMAND] [ARG...]", "Create a new container")
  1868. // These are flags not stored in Config/HostConfig
  1869. var (
  1870. flName = cmd.String([]string{"-name"}, "", "Assign a name to the container")
  1871. )
  1872. config, hostConfig, cmd, err := runconfig.Parse(cmd, args, nil)
  1873. if err != nil {
  1874. return err
  1875. }
  1876. if config.Image == "" {
  1877. cmd.Usage()
  1878. return nil
  1879. }
  1880. createResult, err := cli.createContainer(config, hostConfig, hostConfig.ContainerIDFile, *flName)
  1881. if err != nil {
  1882. return err
  1883. }
  1884. fmt.Fprintf(cli.out, "%s\n", createResult.Get("Id"))
  1885. return nil
  1886. }
  1887. func (cli *DockerCli) CmdRun(args ...string) error {
  1888. // FIXME: just use runconfig.Parse already
  1889. cmd := cli.Subcmd("run", "IMAGE [COMMAND] [ARG...]", "Run a command in a new container")
  1890. // These are flags not stored in Config/HostConfig
  1891. var (
  1892. flAutoRemove = cmd.Bool([]string{"#rm", "-rm"}, false, "Automatically remove the container when it exits (incompatible with -d)")
  1893. flDetach = cmd.Bool([]string{"d", "-detach"}, false, "Detached mode: run the container in the background and print the new container ID")
  1894. 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.")
  1895. flName = cmd.String([]string{"#name", "-name"}, "", "Assign a name to the container")
  1896. flAttach *opts.ListOpts
  1897. ErrConflictAttachDetach = fmt.Errorf("Conflicting options: -a and -d")
  1898. ErrConflictRestartPolicyAndAutoRemove = fmt.Errorf("Conflicting options: --restart and --rm")
  1899. ErrConflictDetachAutoRemove = fmt.Errorf("Conflicting options: --rm and -d")
  1900. )
  1901. config, hostConfig, cmd, err := runconfig.Parse(cmd, args, nil)
  1902. if err != nil {
  1903. return err
  1904. }
  1905. if config.Image == "" {
  1906. cmd.Usage()
  1907. return nil
  1908. }
  1909. if *flDetach {
  1910. if fl := cmd.Lookup("attach"); fl != nil {
  1911. flAttach = fl.Value.(*opts.ListOpts)
  1912. if flAttach.Len() != 0 {
  1913. return ErrConflictAttachDetach
  1914. }
  1915. }
  1916. if *flAutoRemove {
  1917. return ErrConflictDetachAutoRemove
  1918. }
  1919. config.AttachStdin = false
  1920. config.AttachStdout = false
  1921. config.AttachStderr = false
  1922. config.StdinOnce = false
  1923. }
  1924. // Disable flSigProxy when in TTY mode
  1925. sigProxy := *flSigProxy
  1926. if config.Tty {
  1927. sigProxy = false
  1928. }
  1929. runResult, err := cli.createContainer(config, hostConfig, hostConfig.ContainerIDFile, *flName)
  1930. if err != nil {
  1931. return err
  1932. }
  1933. if sigProxy {
  1934. sigc := cli.forwardAllSignals(runResult.Get("Id"))
  1935. defer signal.StopCatch(sigc)
  1936. }
  1937. var (
  1938. waitDisplayId chan struct{}
  1939. errCh chan error
  1940. )
  1941. if !config.AttachStdout && !config.AttachStderr {
  1942. // Make this asynchronous to allow the client to write to stdin before having to read the ID
  1943. waitDisplayId = make(chan struct{})
  1944. go func() {
  1945. defer close(waitDisplayId)
  1946. fmt.Fprintf(cli.out, "%s\n", runResult.Get("Id"))
  1947. }()
  1948. }
  1949. if *flAutoRemove && (hostConfig.RestartPolicy.Name == "always" || hostConfig.RestartPolicy.Name == "on-failure") {
  1950. return ErrConflictRestartPolicyAndAutoRemove
  1951. }
  1952. // We need to instantiate the chan because the select needs it. It can
  1953. // be closed but can't be uninitialized.
  1954. hijacked := make(chan io.Closer)
  1955. // Block the return until the chan gets closed
  1956. defer func() {
  1957. log.Debugf("End of CmdRun(), Waiting for hijack to finish.")
  1958. if _, ok := <-hijacked; ok {
  1959. log.Errorf("Hijack did not finish (chan still open)")
  1960. }
  1961. }()
  1962. if config.AttachStdin || config.AttachStdout || config.AttachStderr {
  1963. var (
  1964. out, stderr io.Writer
  1965. in io.ReadCloser
  1966. v = url.Values{}
  1967. )
  1968. v.Set("stream", "1")
  1969. if config.AttachStdin {
  1970. v.Set("stdin", "1")
  1971. in = cli.in
  1972. }
  1973. if config.AttachStdout {
  1974. v.Set("stdout", "1")
  1975. out = cli.out
  1976. }
  1977. if config.AttachStderr {
  1978. v.Set("stderr", "1")
  1979. if config.Tty {
  1980. stderr = cli.out
  1981. } else {
  1982. stderr = cli.err
  1983. }
  1984. }
  1985. errCh = promise.Go(func() error {
  1986. return cli.hijack("POST", "/containers/"+runResult.Get("Id")+"/attach?"+v.Encode(), config.Tty, in, out, stderr, hijacked, nil)
  1987. })
  1988. } else {
  1989. close(hijacked)
  1990. }
  1991. // Acknowledge the hijack before starting
  1992. select {
  1993. case closer := <-hijacked:
  1994. // Make sure that the hijack gets closed when returning (results
  1995. // in closing the hijack chan and freeing server's goroutines)
  1996. if closer != nil {
  1997. defer closer.Close()
  1998. }
  1999. case err := <-errCh:
  2000. if err != nil {
  2001. log.Debugf("Error hijack: %s", err)
  2002. return err
  2003. }
  2004. }
  2005. //start the container
  2006. if _, _, err = readBody(cli.call("POST", "/containers/"+runResult.Get("Id")+"/start", nil, false)); err != nil {
  2007. return err
  2008. }
  2009. if (config.AttachStdin || config.AttachStdout || config.AttachStderr) && config.Tty && cli.isTerminalOut {
  2010. if err := cli.monitorTtySize(runResult.Get("Id"), false); err != nil {
  2011. log.Errorf("Error monitoring TTY size: %s", err)
  2012. }
  2013. }
  2014. if errCh != nil {
  2015. if err := <-errCh; err != nil {
  2016. log.Debugf("Error hijack: %s", err)
  2017. return err
  2018. }
  2019. }
  2020. // Detached mode: wait for the id to be displayed and return.
  2021. if !config.AttachStdout && !config.AttachStderr {
  2022. // Detached mode
  2023. <-waitDisplayId
  2024. return nil
  2025. }
  2026. var status int
  2027. // Attached mode
  2028. if *flAutoRemove {
  2029. // Autoremove: wait for the container to finish, retrieve
  2030. // the exit code and remove the container
  2031. if _, _, err := readBody(cli.call("POST", "/containers/"+runResult.Get("Id")+"/wait", nil, false)); err != nil {
  2032. return err
  2033. }
  2034. if _, status, err = getExitCode(cli, runResult.Get("Id")); err != nil {
  2035. return err
  2036. }
  2037. if _, _, err := readBody(cli.call("DELETE", "/containers/"+runResult.Get("Id")+"?v=1", nil, false)); err != nil {
  2038. return err
  2039. }
  2040. } else {
  2041. // No Autoremove: Simply retrieve the exit code
  2042. if !config.Tty {
  2043. // In non-TTY mode, we can't detach, so we must wait for container exit
  2044. if status, err = waitForExit(cli, runResult.Get("Id")); err != nil {
  2045. return err
  2046. }
  2047. } else {
  2048. // In TTY mode, there is a race: if the process dies too slowly, the state could
  2049. // be updated after the getExitCode call and result in the wrong exit code being reported
  2050. if _, status, err = getExitCode(cli, runResult.Get("Id")); err != nil {
  2051. return err
  2052. }
  2053. }
  2054. }
  2055. if status != 0 {
  2056. return &utils.StatusError{StatusCode: status}
  2057. }
  2058. return nil
  2059. }
  2060. func (cli *DockerCli) CmdCp(args ...string) error {
  2061. cmd := cli.Subcmd("cp", "CONTAINER:PATH HOSTPATH", "Copy files/folders from the PATH to the HOSTPATH")
  2062. if err := cmd.Parse(args); err != nil {
  2063. return nil
  2064. }
  2065. if cmd.NArg() != 2 {
  2066. cmd.Usage()
  2067. return nil
  2068. }
  2069. var copyData engine.Env
  2070. info := strings.Split(cmd.Arg(0), ":")
  2071. if len(info) != 2 {
  2072. return fmt.Errorf("Error: Path not specified")
  2073. }
  2074. copyData.Set("Resource", info[1])
  2075. copyData.Set("HostPath", cmd.Arg(1))
  2076. stream, statusCode, err := cli.call("POST", "/containers/"+info[0]+"/copy", copyData, false)
  2077. if stream != nil {
  2078. defer stream.Close()
  2079. }
  2080. if statusCode == 404 {
  2081. return fmt.Errorf("No such container: %v", info[0])
  2082. }
  2083. if err != nil {
  2084. return err
  2085. }
  2086. if statusCode == 200 {
  2087. if err := archive.Untar(stream, copyData.Get("HostPath"), &archive.TarOptions{NoLchown: true}); err != nil {
  2088. return err
  2089. }
  2090. }
  2091. return nil
  2092. }
  2093. func (cli *DockerCli) CmdSave(args ...string) error {
  2094. cmd := cli.Subcmd("save", "IMAGE [IMAGE...]", "Save an image(s) to a tar archive (streamed to STDOUT by default)")
  2095. outfile := cmd.String([]string{"o", "-output"}, "", "Write to a file, instead of STDOUT")
  2096. if err := cmd.Parse(args); err != nil {
  2097. return err
  2098. }
  2099. if cmd.NArg() < 1 {
  2100. cmd.Usage()
  2101. return nil
  2102. }
  2103. var (
  2104. output io.Writer = cli.out
  2105. err error
  2106. )
  2107. if *outfile != "" {
  2108. output, err = os.Create(*outfile)
  2109. if err != nil {
  2110. return err
  2111. }
  2112. } else if cli.isTerminalOut {
  2113. return errors.New("Cowardly refusing to save to a terminal. Use the -o flag or redirect.")
  2114. }
  2115. if len(cmd.Args()) == 1 {
  2116. image := cmd.Arg(0)
  2117. if err := cli.stream("GET", "/images/"+image+"/get", nil, output, nil); err != nil {
  2118. return err
  2119. }
  2120. } else {
  2121. v := url.Values{}
  2122. for _, arg := range cmd.Args() {
  2123. v.Add("names", arg)
  2124. }
  2125. if err := cli.stream("GET", "/images/get?"+v.Encode(), nil, output, nil); err != nil {
  2126. return err
  2127. }
  2128. }
  2129. return nil
  2130. }
  2131. func (cli *DockerCli) CmdLoad(args ...string) error {
  2132. cmd := cli.Subcmd("load", "", "Load an image from a tar archive on STDIN")
  2133. infile := cmd.String([]string{"i", "-input"}, "", "Read from a tar archive file, instead of STDIN")
  2134. if err := cmd.Parse(args); err != nil {
  2135. return err
  2136. }
  2137. if cmd.NArg() != 0 {
  2138. cmd.Usage()
  2139. return nil
  2140. }
  2141. var (
  2142. input io.Reader = cli.in
  2143. err error
  2144. )
  2145. if *infile != "" {
  2146. input, err = os.Open(*infile)
  2147. if err != nil {
  2148. return err
  2149. }
  2150. }
  2151. if err := cli.stream("POST", "/images/load", input, cli.out, nil); err != nil {
  2152. return err
  2153. }
  2154. return nil
  2155. }
  2156. func (cli *DockerCli) CmdExec(args ...string) error {
  2157. cmd := cli.Subcmd("exec", "CONTAINER COMMAND [ARG...]", "Run a command in a running container")
  2158. execConfig, err := runconfig.ParseExec(cmd, args)
  2159. if err != nil {
  2160. return err
  2161. }
  2162. if execConfig.Container == "" {
  2163. cmd.Usage()
  2164. return nil
  2165. }
  2166. stream, _, err := cli.call("POST", "/containers/"+execConfig.Container+"/exec", execConfig, false)
  2167. if err != nil {
  2168. return err
  2169. }
  2170. var execResult engine.Env
  2171. if err := execResult.Decode(stream); err != nil {
  2172. return err
  2173. }
  2174. execID := execResult.Get("Id")
  2175. if execID == "" {
  2176. fmt.Fprintf(cli.out, "exec ID empty")
  2177. return nil
  2178. }
  2179. if execConfig.Detach {
  2180. if _, _, err := readBody(cli.call("POST", "/exec/"+execID+"/start", execConfig, false)); err != nil {
  2181. return err
  2182. }
  2183. return nil
  2184. }
  2185. // Interactive exec requested.
  2186. var (
  2187. out, stderr io.Writer
  2188. in io.ReadCloser
  2189. hijacked = make(chan io.Closer)
  2190. errCh chan error
  2191. )
  2192. // Block the return until the chan gets closed
  2193. defer func() {
  2194. log.Debugf("End of CmdExec(), Waiting for hijack to finish.")
  2195. if _, ok := <-hijacked; ok {
  2196. log.Errorf("Hijack did not finish (chan still open)")
  2197. }
  2198. }()
  2199. if execConfig.AttachStdin {
  2200. in = cli.in
  2201. }
  2202. if execConfig.AttachStdout {
  2203. out = cli.out
  2204. }
  2205. if execConfig.AttachStderr {
  2206. if execConfig.Tty {
  2207. stderr = cli.out
  2208. } else {
  2209. stderr = cli.err
  2210. }
  2211. }
  2212. errCh = promise.Go(func() error {
  2213. return cli.hijack("POST", "/exec/"+execID+"/start", execConfig.Tty, in, out, stderr, hijacked, execConfig)
  2214. })
  2215. // Acknowledge the hijack before starting
  2216. select {
  2217. case closer := <-hijacked:
  2218. // Make sure that hijack gets closed when returning. (result
  2219. // in closing hijack chan and freeing server's goroutines.
  2220. if closer != nil {
  2221. defer closer.Close()
  2222. }
  2223. case err := <-errCh:
  2224. if err != nil {
  2225. log.Debugf("Error hijack: %s", err)
  2226. return err
  2227. }
  2228. }
  2229. if execConfig.Tty && cli.isTerminalIn {
  2230. if err := cli.monitorTtySize(execID, true); err != nil {
  2231. log.Errorf("Error monitoring TTY size: %s", err)
  2232. }
  2233. }
  2234. if err := <-errCh; err != nil {
  2235. log.Debugf("Error hijack: %s", err)
  2236. return err
  2237. }
  2238. return nil
  2239. }