commands.go 61 KB

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