commands.go 63 KB

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