commands.go 58 KB

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