commands.go 60 KB

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