commands.go 71 KB

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