commands.go 58 KB

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