commands.go 71 KB

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