commands.go 62 KB

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