commands.go 61 KB

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