commands.go 59 KB

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