commands.go 60 KB

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