commands.go 69 KB

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