commands.go 68 KB

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