commands.go 71 KB

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