commands.go 63 KB

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