commands.go 61 KB

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