commands.go 68 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570
  1. package docker
  2. import (
  3. "archive/tar"
  4. "bufio"
  5. "bytes"
  6. "encoding/base64"
  7. "encoding/json"
  8. "errors"
  9. "flag"
  10. "fmt"
  11. "github.com/dotcloud/docker/archive"
  12. "github.com/dotcloud/docker/auth"
  13. "github.com/dotcloud/docker/engine"
  14. "github.com/dotcloud/docker/registry"
  15. "github.com/dotcloud/docker/term"
  16. "github.com/dotcloud/docker/utils"
  17. "io"
  18. "io/ioutil"
  19. "net"
  20. "net/http"
  21. "net/http/httputil"
  22. "net/url"
  23. "os"
  24. "os/signal"
  25. "path"
  26. "reflect"
  27. "regexp"
  28. "runtime"
  29. "sort"
  30. "strconv"
  31. "strings"
  32. "syscall"
  33. "text/tabwriter"
  34. "text/template"
  35. "time"
  36. )
  37. var (
  38. GITCOMMIT string
  39. VERSION string
  40. )
  41. var (
  42. ErrConnectionRefused = errors.New("Can't connect to docker daemon. Is 'docker -d' running on this host?")
  43. )
  44. func (cli *DockerCli) getMethod(name string) (func(...string) error, bool) {
  45. methodName := "Cmd" + strings.ToUpper(name[:1]) + strings.ToLower(name[1:])
  46. method := reflect.ValueOf(cli).MethodByName(methodName)
  47. if !method.IsValid() {
  48. return nil, false
  49. }
  50. return method.Interface().(func(...string) error), true
  51. }
  52. func ParseCommands(proto, addr string, args ...string) error {
  53. cli := NewDockerCli(os.Stdin, os.Stdout, os.Stderr, proto, addr)
  54. if len(args) > 0 {
  55. method, exists := cli.getMethod(args[0])
  56. if !exists {
  57. fmt.Println("Error: Command not found:", args[0])
  58. return cli.CmdHelp(args[1:]...)
  59. }
  60. return method(args[1:]...)
  61. }
  62. return cli.CmdHelp(args...)
  63. }
  64. func (cli *DockerCli) CmdHelp(args ...string) error {
  65. if len(args) > 0 {
  66. method, exists := cli.getMethod(args[0])
  67. if !exists {
  68. fmt.Fprintf(cli.err, "Error: Command not found: %s\n", args[0])
  69. } else {
  70. method("--help")
  71. return nil
  72. }
  73. }
  74. 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", DEFAULTUNIXSOCKET)
  75. for _, command := range [][]string{
  76. {"attach", "Attach to a running container"},
  77. {"build", "Build a container from a Dockerfile"},
  78. {"commit", "Create a new image from a container's changes"},
  79. {"cp", "Copy files/folders from the containers filesystem to the host path"},
  80. {"diff", "Inspect changes on a container's filesystem"},
  81. {"events", "Get real time events from the server"},
  82. {"export", "Stream the contents of a container as a tar archive"},
  83. {"history", "Show the history of an image"},
  84. {"images", "List images"},
  85. {"import", "Create a new filesystem image from the contents of a tarball"},
  86. {"info", "Display system-wide information"},
  87. {"insert", "Insert a file in an image"},
  88. {"inspect", "Return low-level information on a container"},
  89. {"kill", "Kill a running container"},
  90. {"load", "Load an image from a tar archive"},
  91. {"login", "Register or Login to the docker registry server"},
  92. {"logs", "Fetch the logs of a container"},
  93. {"port", "Lookup the public-facing port which is NAT-ed to PRIVATE_PORT"},
  94. {"ps", "List containers"},
  95. {"pull", "Pull an image or a repository from the docker registry server"},
  96. {"push", "Push an image or a repository to the docker registry server"},
  97. {"restart", "Restart a running container"},
  98. {"rm", "Remove one or more containers"},
  99. {"rmi", "Remove one or more images"},
  100. {"run", "Run a command in a new container"},
  101. {"save", "Save an image to a tar archive"},
  102. {"search", "Search for an image in the docker index"},
  103. {"start", "Start a stopped container"},
  104. {"stop", "Stop a running container"},
  105. {"tag", "Tag an image into a repository"},
  106. {"top", "Lookup the running processes of a container"},
  107. {"version", "Show the docker version information"},
  108. {"wait", "Block until a container stops, then print its exit code"},
  109. } {
  110. help += fmt.Sprintf(" %-10.10s%s\n", command[0], command[1])
  111. }
  112. fmt.Fprintf(cli.err, "%s\n", help)
  113. return nil
  114. }
  115. func (cli *DockerCli) CmdInsert(args ...string) error {
  116. cmd := cli.Subcmd("insert", "IMAGE URL PATH", "Insert a file from URL in the IMAGE at PATH")
  117. if err := cmd.Parse(args); err != nil {
  118. return nil
  119. }
  120. if cmd.NArg() != 3 {
  121. cmd.Usage()
  122. return nil
  123. }
  124. v := url.Values{}
  125. v.Set("url", cmd.Arg(1))
  126. v.Set("path", cmd.Arg(2))
  127. return cli.stream("POST", "/images/"+cmd.Arg(0)+"/insert?"+v.Encode(), nil, cli.out, nil)
  128. }
  129. // mkBuildContext returns an archive of an empty context with the contents
  130. // of `dockerfile` at the path ./Dockerfile
  131. func MkBuildContext(dockerfile string, files [][2]string) (archive.Archive, error) {
  132. buf := new(bytes.Buffer)
  133. tw := tar.NewWriter(buf)
  134. files = append(files, [2]string{"Dockerfile", dockerfile})
  135. for _, file := range files {
  136. name, content := file[0], file[1]
  137. hdr := &tar.Header{
  138. Name: name,
  139. Size: int64(len(content)),
  140. }
  141. if err := tw.WriteHeader(hdr); err != nil {
  142. return nil, err
  143. }
  144. if _, err := tw.Write([]byte(content)); err != nil {
  145. return nil, err
  146. }
  147. }
  148. if err := tw.Close(); err != nil {
  149. return nil, err
  150. }
  151. return buf, nil
  152. }
  153. func (cli *DockerCli) CmdBuild(args ...string) error {
  154. cmd := cli.Subcmd("build", "[OPTIONS] PATH | URL | -", "Build a new container image from the source code at PATH")
  155. tag := cmd.String("t", "", "Repository name (and optionally a tag) to be applied to the resulting image in case of success")
  156. suppressOutput := cmd.Bool("q", false, "Suppress verbose build output")
  157. noCache := cmd.Bool("no-cache", false, "Do not use cache when building the image")
  158. rm := cmd.Bool("rm", false, "Remove intermediate containers after a successful build")
  159. if err := cmd.Parse(args); err != nil {
  160. return nil
  161. }
  162. if cmd.NArg() != 1 {
  163. cmd.Usage()
  164. return nil
  165. }
  166. var (
  167. context archive.Archive
  168. isRemote bool
  169. err error
  170. )
  171. if cmd.Arg(0) == "-" {
  172. // As a special case, 'docker build -' will build from an empty context with the
  173. // contents of stdin as a Dockerfile
  174. dockerfile, err := ioutil.ReadAll(cli.in)
  175. if err != nil {
  176. return err
  177. }
  178. context, err = MkBuildContext(string(dockerfile), nil)
  179. } else if utils.IsURL(cmd.Arg(0)) || utils.IsGIT(cmd.Arg(0)) {
  180. isRemote = true
  181. } else {
  182. if _, err := os.Stat(cmd.Arg(0)); err != nil {
  183. return err
  184. }
  185. filename := path.Join(cmd.Arg(0), "Dockerfile")
  186. if _, err = os.Stat(filename); os.IsNotExist(err) {
  187. return fmt.Errorf("no Dockerfile found in %s", cmd.Arg(0))
  188. }
  189. context, err = archive.Tar(cmd.Arg(0), archive.Uncompressed)
  190. }
  191. var body io.Reader
  192. // Setup an upload progress bar
  193. // FIXME: ProgressReader shouldn't be this annoying to use
  194. if context != nil {
  195. sf := utils.NewStreamFormatter(false)
  196. body = utils.ProgressReader(ioutil.NopCloser(context), 0, cli.err, sf, true, "", "Uploading context")
  197. }
  198. // Upload the build context
  199. v := &url.Values{}
  200. v.Set("t", *tag)
  201. if *suppressOutput {
  202. v.Set("q", "1")
  203. }
  204. if isRemote {
  205. v.Set("remote", cmd.Arg(0))
  206. }
  207. if *noCache {
  208. v.Set("nocache", "1")
  209. }
  210. if *rm {
  211. v.Set("rm", "1")
  212. }
  213. headers := http.Header(make(map[string][]string))
  214. buf, err := json.Marshal(cli.configFile)
  215. if err != nil {
  216. return err
  217. }
  218. headers.Add("X-Registry-Auth", base64.URLEncoding.EncodeToString(buf))
  219. if context != nil {
  220. headers.Set("Content-Type", "application/tar")
  221. }
  222. err = cli.stream("POST", fmt.Sprintf("/build?%s", v.Encode()), body, cli.out, headers)
  223. if jerr, ok := err.(*utils.JSONError); ok {
  224. return &utils.StatusError{Status: jerr.Message, StatusCode: jerr.Code}
  225. }
  226. return err
  227. }
  228. // 'docker login': login / register a user to registry service.
  229. func (cli *DockerCli) CmdLogin(args ...string) error {
  230. cmd := cli.Subcmd("login", "[OPTIONS] [SERVER]", "Register or Login to a docker registry server, if no server is specified \""+auth.IndexServerAddress()+"\" is the default.")
  231. var username, password, email string
  232. cmd.StringVar(&username, "u", "", "username")
  233. cmd.StringVar(&password, "p", "", "password")
  234. cmd.StringVar(&email, "e", "", "email")
  235. err := cmd.Parse(args)
  236. if err != nil {
  237. return nil
  238. }
  239. serverAddress := auth.IndexServerAddress()
  240. if len(cmd.Args()) > 0 {
  241. serverAddress, err = registry.ExpandAndVerifyRegistryUrl(cmd.Arg(0))
  242. if err != nil {
  243. return err
  244. }
  245. fmt.Fprintf(cli.out, "Login against server at %s\n", serverAddress)
  246. }
  247. promptDefault := func(prompt string, configDefault string) {
  248. if configDefault == "" {
  249. fmt.Fprintf(cli.out, "%s: ", prompt)
  250. } else {
  251. fmt.Fprintf(cli.out, "%s (%s): ", prompt, configDefault)
  252. }
  253. }
  254. readInput := func(in io.Reader, out io.Writer) string {
  255. reader := bufio.NewReader(in)
  256. line, _, err := reader.ReadLine()
  257. if err != nil {
  258. fmt.Fprintln(out, err.Error())
  259. os.Exit(1)
  260. }
  261. return string(line)
  262. }
  263. cli.LoadConfigFile()
  264. authconfig, ok := cli.configFile.Configs[serverAddress]
  265. if !ok {
  266. authconfig = auth.AuthConfig{}
  267. }
  268. if username == "" {
  269. promptDefault("Username", authconfig.Username)
  270. username = readInput(cli.in, cli.out)
  271. if username == "" {
  272. username = authconfig.Username
  273. }
  274. }
  275. if username != authconfig.Username {
  276. if password == "" {
  277. oldState, _ := term.SaveState(cli.terminalFd)
  278. fmt.Fprintf(cli.out, "Password: ")
  279. term.DisableEcho(cli.terminalFd, oldState)
  280. password = readInput(cli.in, cli.out)
  281. fmt.Fprint(cli.out, "\n")
  282. term.RestoreTerminal(cli.terminalFd, oldState)
  283. if password == "" {
  284. return fmt.Errorf("Error : Password Required")
  285. }
  286. }
  287. if email == "" {
  288. promptDefault("Email", authconfig.Email)
  289. email = readInput(cli.in, cli.out)
  290. if email == "" {
  291. email = authconfig.Email
  292. }
  293. }
  294. } else {
  295. password = authconfig.Password
  296. email = authconfig.Email
  297. }
  298. authconfig.Username = username
  299. authconfig.Password = password
  300. authconfig.Email = email
  301. authconfig.ServerAddress = serverAddress
  302. cli.configFile.Configs[serverAddress] = authconfig
  303. body, statusCode, err := cli.call("POST", "/auth", cli.configFile.Configs[serverAddress])
  304. if statusCode == 401 {
  305. delete(cli.configFile.Configs, serverAddress)
  306. auth.SaveConfig(cli.configFile)
  307. return err
  308. }
  309. if err != nil {
  310. return err
  311. }
  312. var out2 APIAuth
  313. err = json.Unmarshal(body, &out2)
  314. if err != nil {
  315. cli.configFile, _ = auth.LoadConfig(os.Getenv("HOME"))
  316. return err
  317. }
  318. auth.SaveConfig(cli.configFile)
  319. if out2.Status != "" {
  320. fmt.Fprintf(cli.out, "%s\n", out2.Status)
  321. }
  322. return nil
  323. }
  324. // 'docker wait': block until a container stops
  325. func (cli *DockerCli) CmdWait(args ...string) error {
  326. cmd := cli.Subcmd("wait", "CONTAINER [CONTAINER...]", "Block until a container stops, then print its exit code.")
  327. if err := cmd.Parse(args); err != nil {
  328. return nil
  329. }
  330. if cmd.NArg() < 1 {
  331. cmd.Usage()
  332. return nil
  333. }
  334. var encounteredError error
  335. for _, name := range cmd.Args() {
  336. status, err := waitForExit(cli, name)
  337. if err != nil {
  338. fmt.Fprintf(cli.err, "%s\n", err)
  339. encounteredError = fmt.Errorf("Error: failed to wait one or more containers")
  340. } else {
  341. fmt.Fprintf(cli.out, "%d\n", status)
  342. }
  343. }
  344. return encounteredError
  345. }
  346. // 'docker version': show version information
  347. func (cli *DockerCli) CmdVersion(args ...string) error {
  348. cmd := cli.Subcmd("version", "", "Show the docker version information.")
  349. if err := cmd.Parse(args); err != nil {
  350. return nil
  351. }
  352. if cmd.NArg() > 0 {
  353. cmd.Usage()
  354. return nil
  355. }
  356. if VERSION != "" {
  357. fmt.Fprintf(cli.out, "Client version: %s\n", VERSION)
  358. }
  359. fmt.Fprintf(cli.out, "Go version (client): %s\n", runtime.Version())
  360. if GITCOMMIT != "" {
  361. fmt.Fprintf(cli.out, "Git commit (client): %s\n", GITCOMMIT)
  362. }
  363. body, _, err := cli.call("GET", "/version", nil)
  364. if err != nil {
  365. return err
  366. }
  367. out := engine.NewOutput()
  368. remoteVersion, err := out.AddEnv()
  369. if err != nil {
  370. utils.Errorf("Error reading remote version: %s\n", err)
  371. return err
  372. }
  373. if _, err := out.Write(body); err != nil {
  374. utils.Errorf("Error reading remote version: %s\n", err)
  375. return err
  376. }
  377. out.Close()
  378. fmt.Fprintf(cli.out, "Server version: %s\n", remoteVersion.Get("Version"))
  379. fmt.Fprintf(cli.out, "Git commit (server): %s\n", remoteVersion.Get("GitCommit"))
  380. fmt.Fprintf(cli.out, "Go version (server): %s\n", remoteVersion.Get("GoVersion"))
  381. release := utils.GetReleaseVersion()
  382. if release != "" {
  383. fmt.Fprintf(cli.out, "Last stable version: %s", release)
  384. if (VERSION != "" || remoteVersion.Exists("Version")) && (strings.Trim(VERSION, "-dev") != release || strings.Trim(remoteVersion.Get("Version"), "-dev") != release) {
  385. fmt.Fprintf(cli.out, ", please update docker")
  386. }
  387. fmt.Fprintf(cli.out, "\n")
  388. }
  389. return nil
  390. }
  391. // 'docker info': display system-wide information.
  392. func (cli *DockerCli) CmdInfo(args ...string) error {
  393. cmd := cli.Subcmd("info", "", "Display system-wide information")
  394. if err := cmd.Parse(args); err != nil {
  395. return nil
  396. }
  397. if cmd.NArg() > 0 {
  398. cmd.Usage()
  399. return nil
  400. }
  401. body, _, err := cli.call("GET", "/info", nil)
  402. if err != nil {
  403. return err
  404. }
  405. out := engine.NewOutput()
  406. remoteInfo, err := out.AddEnv()
  407. if err != nil {
  408. return err
  409. }
  410. if _, err := out.Write(body); err != nil {
  411. utils.Errorf("Error reading remote info: %s\n", err)
  412. return err
  413. }
  414. out.Close()
  415. fmt.Fprintf(cli.out, "Containers: %d\n", remoteInfo.GetInt("Containers"))
  416. fmt.Fprintf(cli.out, "Images: %d\n", remoteInfo.GetInt("Images"))
  417. fmt.Fprintf(cli.out, "Driver: %s\n", remoteInfo.Get("Driver"))
  418. var driverStatus [][2]string
  419. if err := remoteInfo.GetJson("DriverStatus", &driverStatus); err != nil {
  420. return err
  421. }
  422. for _, pair := range driverStatus {
  423. fmt.Fprintf(cli.out, " %s: %s\n", pair[0], pair[1])
  424. }
  425. if remoteInfo.GetBool("Debug") || os.Getenv("DEBUG") != "" {
  426. fmt.Fprintf(cli.out, "Debug mode (server): %v\n", remoteInfo.GetBool("Debug"))
  427. fmt.Fprintf(cli.out, "Debug mode (client): %v\n", os.Getenv("DEBUG") != "")
  428. fmt.Fprintf(cli.out, "Fds: %d\n", remoteInfo.GetInt("NFd"))
  429. fmt.Fprintf(cli.out, "Goroutines: %d\n", remoteInfo.GetInt("NGoroutines"))
  430. fmt.Fprintf(cli.out, "LXC Version: %s\n", remoteInfo.Get("LXCVersion"))
  431. fmt.Fprintf(cli.out, "EventsListeners: %d\n", remoteInfo.GetInt("NEventsListener"))
  432. fmt.Fprintf(cli.out, "Kernel Version: %s\n", remoteInfo.Get("KernelVersion"))
  433. }
  434. if len(remoteInfo.GetList("IndexServerAddress")) != 0 {
  435. cli.LoadConfigFile()
  436. u := cli.configFile.Configs[remoteInfo.Get("IndexServerAddress")].Username
  437. if len(u) > 0 {
  438. fmt.Fprintf(cli.out, "Username: %v\n", u)
  439. fmt.Fprintf(cli.out, "Registry: %v\n", remoteInfo.GetList("IndexServerAddress"))
  440. }
  441. }
  442. if !remoteInfo.GetBool("MemoryLimit") {
  443. fmt.Fprintf(cli.err, "WARNING: No memory limit support\n")
  444. }
  445. if !remoteInfo.GetBool("SwapLimit") {
  446. fmt.Fprintf(cli.err, "WARNING: No swap limit support\n")
  447. }
  448. if !remoteInfo.GetBool("IPv4Forwarding") {
  449. fmt.Fprintf(cli.err, "WARNING: IPv4 forwarding is disabled.\n")
  450. }
  451. return nil
  452. }
  453. func (cli *DockerCli) CmdStop(args ...string) error {
  454. cmd := cli.Subcmd("stop", "[OPTIONS] CONTAINER [CONTAINER...]", "Stop a running container (Send SIGTERM, and then SIGKILL after grace period)")
  455. nSeconds := cmd.Int("t", 10, "Number of seconds to wait for the container to stop before killing it.")
  456. if err := cmd.Parse(args); err != nil {
  457. return nil
  458. }
  459. if cmd.NArg() < 1 {
  460. cmd.Usage()
  461. return nil
  462. }
  463. v := url.Values{}
  464. v.Set("t", strconv.Itoa(*nSeconds))
  465. var encounteredError error
  466. for _, name := range cmd.Args() {
  467. _, _, err := cli.call("POST", "/containers/"+name+"/stop?"+v.Encode(), nil)
  468. if err != nil {
  469. fmt.Fprintf(cli.err, "%s\n", err)
  470. encounteredError = fmt.Errorf("Error: failed to stop one or more containers")
  471. } else {
  472. fmt.Fprintf(cli.out, "%s\n", name)
  473. }
  474. }
  475. return encounteredError
  476. }
  477. func (cli *DockerCli) CmdRestart(args ...string) error {
  478. cmd := cli.Subcmd("restart", "[OPTIONS] CONTAINER [CONTAINER...]", "Restart a running container")
  479. nSeconds := cmd.Int("t", 10, "Number of seconds to try to stop for before killing the container. Once killed it will then be restarted. Default=10")
  480. if err := cmd.Parse(args); err != nil {
  481. return nil
  482. }
  483. if cmd.NArg() < 1 {
  484. cmd.Usage()
  485. return nil
  486. }
  487. v := url.Values{}
  488. v.Set("t", strconv.Itoa(*nSeconds))
  489. var encounteredError error
  490. for _, name := range cmd.Args() {
  491. _, _, err := cli.call("POST", "/containers/"+name+"/restart?"+v.Encode(), nil)
  492. if err != nil {
  493. fmt.Fprintf(cli.err, "%s\n", err)
  494. encounteredError = fmt.Errorf("Error: failed to restart one or more containers")
  495. } else {
  496. fmt.Fprintf(cli.out, "%s\n", name)
  497. }
  498. }
  499. return encounteredError
  500. }
  501. func (cli *DockerCli) forwardAllSignals(cid string) chan os.Signal {
  502. sigc := make(chan os.Signal, 1)
  503. utils.CatchAll(sigc)
  504. go func() {
  505. for s := range sigc {
  506. if s == syscall.SIGCHLD {
  507. continue
  508. }
  509. if _, _, err := cli.call("POST", fmt.Sprintf("/containers/%s/kill?signal=%d", cid, s), nil); err != nil {
  510. utils.Debugf("Error sending signal: %s", err)
  511. }
  512. }
  513. }()
  514. return sigc
  515. }
  516. func (cli *DockerCli) CmdStart(args ...string) error {
  517. cmd := cli.Subcmd("start", "CONTAINER [CONTAINER...]", "Restart a stopped container")
  518. attach := cmd.Bool("a", false, "Attach container's stdout/stderr and forward all signals to the process")
  519. openStdin := cmd.Bool("i", false, "Attach container's stdin")
  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. var cErr chan error
  528. var tty bool
  529. if *attach || *openStdin {
  530. if cmd.NArg() > 1 {
  531. return fmt.Errorf("Impossible to start and attach multiple containers at once.")
  532. }
  533. body, _, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/json", nil)
  534. if err != nil {
  535. return err
  536. }
  537. container := &Container{}
  538. err = json.Unmarshal(body, container)
  539. if err != nil {
  540. return err
  541. }
  542. tty = container.Config.Tty
  543. if !container.Config.Tty {
  544. sigc := cli.forwardAllSignals(cmd.Arg(0))
  545. defer utils.StopCatch(sigc)
  546. }
  547. var in io.ReadCloser
  548. v := url.Values{}
  549. v.Set("stream", "1")
  550. if *openStdin && container.Config.OpenStdin {
  551. v.Set("stdin", "1")
  552. in = cli.in
  553. }
  554. v.Set("stdout", "1")
  555. v.Set("stderr", "1")
  556. cErr = utils.Go(func() error {
  557. return cli.hijack("POST", "/containers/"+cmd.Arg(0)+"/attach?"+v.Encode(), container.Config.Tty, in, cli.out, cli.err, nil)
  558. })
  559. }
  560. var encounteredError error
  561. for _, name := range cmd.Args() {
  562. _, _, err := cli.call("POST", "/containers/"+name+"/start", nil)
  563. if err != nil {
  564. if !*attach || !*openStdin {
  565. fmt.Fprintf(cli.err, "%s\n", err)
  566. encounteredError = fmt.Errorf("Error: failed to start one or more containers")
  567. }
  568. } else {
  569. if !*attach || !*openStdin {
  570. fmt.Fprintf(cli.out, "%s\n", name)
  571. }
  572. }
  573. }
  574. if encounteredError != nil {
  575. if *openStdin || *attach {
  576. cli.in.Close()
  577. <-cErr
  578. }
  579. return encounteredError
  580. }
  581. if *openStdin || *attach {
  582. if tty && cli.isTerminal {
  583. if err := cli.monitorTtySize(cmd.Arg(0)); err != nil {
  584. utils.Errorf("Error monitoring TTY size: %s\n", err)
  585. }
  586. }
  587. return <-cErr
  588. }
  589. return nil
  590. }
  591. func (cli *DockerCli) CmdInspect(args ...string) error {
  592. cmd := cli.Subcmd("inspect", "CONTAINER|IMAGE [CONTAINER|IMAGE...]", "Return low-level information on a container/image")
  593. tmplStr := cmd.String("format", "", "Format the output using the given go template.")
  594. if err := cmd.Parse(args); err != nil {
  595. return nil
  596. }
  597. if cmd.NArg() < 1 {
  598. cmd.Usage()
  599. return nil
  600. }
  601. var tmpl *template.Template
  602. if *tmplStr != "" {
  603. var err error
  604. if tmpl, err = template.New("").Parse(*tmplStr); err != nil {
  605. fmt.Fprintf(cli.err, "Template parsing error: %v\n", err)
  606. return &utils.StatusError{StatusCode: 64,
  607. Status: "Template parsing error: " + err.Error()}
  608. }
  609. }
  610. indented := new(bytes.Buffer)
  611. indented.WriteByte('[')
  612. status := 0
  613. for _, name := range cmd.Args() {
  614. obj, _, err := cli.call("GET", "/containers/"+name+"/json", nil)
  615. if err != nil {
  616. obj, _, err = cli.call("GET", "/images/"+name+"/json", nil)
  617. if err != nil {
  618. if strings.Contains(err.Error(), "No such") {
  619. fmt.Fprintf(cli.err, "Error: No such image or container: %s\n", name)
  620. } else {
  621. fmt.Fprintf(cli.err, "%s", err)
  622. }
  623. status = 1
  624. continue
  625. }
  626. }
  627. if tmpl == nil {
  628. if err = json.Indent(indented, obj, "", " "); err != nil {
  629. fmt.Fprintf(cli.err, "%s\n", err)
  630. status = 1
  631. continue
  632. }
  633. } else {
  634. // Has template, will render
  635. var value interface{}
  636. if err := json.Unmarshal(obj, &value); err != nil {
  637. fmt.Fprintf(cli.err, "%s\n", err)
  638. status = 1
  639. continue
  640. }
  641. if err := tmpl.Execute(cli.out, value); err != nil {
  642. return err
  643. }
  644. cli.out.Write([]byte{'\n'})
  645. }
  646. indented.WriteString(",")
  647. }
  648. if indented.Len() > 1 {
  649. // Remove trailing ','
  650. indented.Truncate(indented.Len() - 1)
  651. }
  652. indented.WriteByte(']')
  653. if tmpl == nil {
  654. if _, err := io.Copy(cli.out, indented); err != nil {
  655. return err
  656. }
  657. }
  658. if status != 0 {
  659. return &utils.StatusError{StatusCode: status}
  660. }
  661. return nil
  662. }
  663. func (cli *DockerCli) CmdTop(args ...string) error {
  664. cmd := cli.Subcmd("top", "CONTAINER [ps OPTIONS]", "Lookup the running processes of a container")
  665. if err := cmd.Parse(args); err != nil {
  666. return nil
  667. }
  668. if cmd.NArg() == 0 {
  669. cmd.Usage()
  670. return nil
  671. }
  672. val := url.Values{}
  673. if cmd.NArg() > 1 {
  674. val.Set("ps_args", strings.Join(cmd.Args()[1:], " "))
  675. }
  676. body, _, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/top?"+val.Encode(), nil)
  677. if err != nil {
  678. return err
  679. }
  680. procs := APITop{}
  681. err = json.Unmarshal(body, &procs)
  682. if err != nil {
  683. return err
  684. }
  685. w := tabwriter.NewWriter(cli.out, 20, 1, 3, ' ', 0)
  686. fmt.Fprintln(w, strings.Join(procs.Titles, "\t"))
  687. for _, proc := range procs.Processes {
  688. fmt.Fprintln(w, strings.Join(proc, "\t"))
  689. }
  690. w.Flush()
  691. return nil
  692. }
  693. func (cli *DockerCli) CmdPort(args ...string) error {
  694. cmd := cli.Subcmd("port", "CONTAINER PRIVATE_PORT", "Lookup the public-facing port which is NAT-ed to PRIVATE_PORT")
  695. if err := cmd.Parse(args); err != nil {
  696. return nil
  697. }
  698. if cmd.NArg() != 2 {
  699. cmd.Usage()
  700. return nil
  701. }
  702. port := cmd.Arg(1)
  703. proto := "tcp"
  704. parts := strings.SplitN(port, "/", 2)
  705. if len(parts) == 2 && len(parts[1]) != 0 {
  706. port = parts[0]
  707. proto = parts[1]
  708. }
  709. body, _, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/json", nil)
  710. if err != nil {
  711. return err
  712. }
  713. var out Container
  714. err = json.Unmarshal(body, &out)
  715. if err != nil {
  716. return err
  717. }
  718. if frontends, exists := out.NetworkSettings.Ports[Port(port+"/"+proto)]; exists && frontends != nil {
  719. for _, frontend := range frontends {
  720. fmt.Fprintf(cli.out, "%s:%s\n", frontend.HostIp, frontend.HostPort)
  721. }
  722. } else {
  723. return fmt.Errorf("Error: No public port '%s' published for %s", cmd.Arg(1), cmd.Arg(0))
  724. }
  725. return nil
  726. }
  727. // 'docker rmi IMAGE' removes all images with the name IMAGE
  728. func (cli *DockerCli) CmdRmi(args ...string) error {
  729. cmd := cli.Subcmd("rmi", "IMAGE [IMAGE...]", "Remove one or more images")
  730. if err := cmd.Parse(args); err != nil {
  731. return nil
  732. }
  733. if cmd.NArg() < 1 {
  734. cmd.Usage()
  735. return nil
  736. }
  737. var encounteredError error
  738. for _, name := range cmd.Args() {
  739. body, _, err := cli.call("DELETE", "/images/"+name, nil)
  740. if err != nil {
  741. fmt.Fprintf(cli.err, "%s\n", err)
  742. encounteredError = fmt.Errorf("Error: failed to remove one or more images")
  743. } else {
  744. var outs []APIRmi
  745. err = json.Unmarshal(body, &outs)
  746. if err != nil {
  747. fmt.Fprintf(cli.err, "%s\n", err)
  748. encounteredError = fmt.Errorf("Error: failed to remove one or more images")
  749. continue
  750. }
  751. for _, out := range outs {
  752. if out.Deleted != "" {
  753. fmt.Fprintf(cli.out, "Deleted: %s\n", out.Deleted)
  754. } else {
  755. fmt.Fprintf(cli.out, "Untagged: %s\n", out.Untagged)
  756. }
  757. }
  758. }
  759. }
  760. return encounteredError
  761. }
  762. func (cli *DockerCli) CmdHistory(args ...string) error {
  763. cmd := cli.Subcmd("history", "[OPTIONS] IMAGE", "Show the history of an image")
  764. quiet := cmd.Bool("q", false, "only show numeric IDs")
  765. noTrunc := cmd.Bool("notrunc", false, "Don't truncate output")
  766. if err := cmd.Parse(args); err != nil {
  767. return nil
  768. }
  769. if cmd.NArg() != 1 {
  770. cmd.Usage()
  771. return nil
  772. }
  773. body, _, err := cli.call("GET", "/images/"+cmd.Arg(0)+"/history", nil)
  774. if err != nil {
  775. return err
  776. }
  777. var outs []APIHistory
  778. err = json.Unmarshal(body, &outs)
  779. if err != nil {
  780. return err
  781. }
  782. w := tabwriter.NewWriter(cli.out, 20, 1, 3, ' ', 0)
  783. if !*quiet {
  784. fmt.Fprintln(w, "IMAGE\tCREATED\tCREATED BY\tSIZE")
  785. }
  786. for _, out := range outs {
  787. if !*quiet {
  788. if *noTrunc {
  789. fmt.Fprintf(w, "%s\t", out.ID)
  790. } else {
  791. fmt.Fprintf(w, "%s\t", utils.TruncateID(out.ID))
  792. }
  793. fmt.Fprintf(w, "%s ago\t", utils.HumanDuration(time.Now().UTC().Sub(time.Unix(out.Created, 0))))
  794. if *noTrunc {
  795. fmt.Fprintf(w, "%s\t", out.CreatedBy)
  796. } else {
  797. fmt.Fprintf(w, "%s\t", utils.Trunc(out.CreatedBy, 45))
  798. }
  799. fmt.Fprintf(w, "%s\n", utils.HumanSize(out.Size))
  800. } else {
  801. if *noTrunc {
  802. fmt.Fprintln(w, out.ID)
  803. } else {
  804. fmt.Fprintln(w, utils.TruncateID(out.ID))
  805. }
  806. }
  807. }
  808. w.Flush()
  809. return nil
  810. }
  811. func (cli *DockerCli) CmdRm(args ...string) error {
  812. cmd := cli.Subcmd("rm", "[OPTIONS] CONTAINER [CONTAINER...]", "Remove one or more containers")
  813. v := cmd.Bool("v", false, "Remove the volumes associated to the container")
  814. link := cmd.Bool("link", false, "Remove the specified link and not the underlying container")
  815. if err := cmd.Parse(args); err != nil {
  816. return nil
  817. }
  818. if cmd.NArg() < 1 {
  819. cmd.Usage()
  820. return nil
  821. }
  822. val := url.Values{}
  823. if *v {
  824. val.Set("v", "1")
  825. }
  826. if *link {
  827. val.Set("link", "1")
  828. }
  829. var encounteredError error
  830. for _, name := range cmd.Args() {
  831. _, _, err := cli.call("DELETE", "/containers/"+name+"?"+val.Encode(), nil)
  832. if err != nil {
  833. fmt.Fprintf(cli.err, "%s\n", err)
  834. encounteredError = fmt.Errorf("Error: failed to remove one or more containers")
  835. } else {
  836. fmt.Fprintf(cli.out, "%s\n", name)
  837. }
  838. }
  839. return encounteredError
  840. }
  841. // 'docker kill NAME' kills a running container
  842. func (cli *DockerCli) CmdKill(args ...string) error {
  843. cmd := cli.Subcmd("kill", "CONTAINER [CONTAINER...]", "Kill a running container (send SIGKILL)")
  844. if err := cmd.Parse(args); err != nil {
  845. return nil
  846. }
  847. if cmd.NArg() < 1 {
  848. cmd.Usage()
  849. return nil
  850. }
  851. var encounteredError error
  852. for _, name := range args {
  853. if _, _, err := cli.call("POST", "/containers/"+name+"/kill", nil); err != nil {
  854. fmt.Fprintf(cli.err, "%s\n", err)
  855. encounteredError = fmt.Errorf("Error: failed to kill one or more containers")
  856. } else {
  857. fmt.Fprintf(cli.out, "%s\n", name)
  858. }
  859. }
  860. return encounteredError
  861. }
  862. func (cli *DockerCli) CmdImport(args ...string) error {
  863. 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.")
  864. if err := cmd.Parse(args); err != nil {
  865. return nil
  866. }
  867. if cmd.NArg() < 1 {
  868. cmd.Usage()
  869. return nil
  870. }
  871. var src, repository, tag string
  872. if cmd.NArg() == 3 {
  873. fmt.Fprintf(cli.err, "[DEPRECATED] The format 'URL|- [REPOSITORY [TAG]]' as been deprecated. Please use URL|- [REPOSITORY[:TAG]]\n")
  874. src, repository, tag = cmd.Arg(0), cmd.Arg(1), cmd.Arg(2)
  875. } else {
  876. src = cmd.Arg(0)
  877. repository, tag = utils.ParseRepositoryTag(cmd.Arg(1))
  878. }
  879. v := url.Values{}
  880. v.Set("repo", repository)
  881. v.Set("tag", tag)
  882. v.Set("fromSrc", src)
  883. var in io.Reader
  884. if src == "-" {
  885. in = cli.in
  886. }
  887. return cli.stream("POST", "/images/create?"+v.Encode(), in, cli.out, nil)
  888. }
  889. func (cli *DockerCli) CmdPush(args ...string) error {
  890. cmd := cli.Subcmd("push", "NAME", "Push an image or a repository to the registry")
  891. if err := cmd.Parse(args); err != nil {
  892. return nil
  893. }
  894. name := cmd.Arg(0)
  895. if name == "" {
  896. cmd.Usage()
  897. return nil
  898. }
  899. cli.LoadConfigFile()
  900. // Resolve the Repository name from fqn to endpoint + name
  901. endpoint, _, err := registry.ResolveRepositoryName(name)
  902. if err != nil {
  903. return err
  904. }
  905. // Resolve the Auth config relevant for this server
  906. authConfig := cli.configFile.ResolveAuthConfig(endpoint)
  907. // If we're not using a custom registry, we know the restrictions
  908. // applied to repository names and can warn the user in advance.
  909. // Custom repositories can have different rules, and we must also
  910. // allow pushing by image ID.
  911. if len(strings.SplitN(name, "/", 2)) == 1 {
  912. username := cli.configFile.Configs[auth.IndexServerAddress()].Username
  913. if username == "" {
  914. username = "<user>"
  915. }
  916. return fmt.Errorf("Impossible to push a \"root\" repository. Please rename your repository in <user>/<repo> (ex: %s/%s)", username, name)
  917. }
  918. v := url.Values{}
  919. push := func(authConfig auth.AuthConfig) error {
  920. buf, err := json.Marshal(authConfig)
  921. if err != nil {
  922. return err
  923. }
  924. registryAuthHeader := []string{
  925. base64.URLEncoding.EncodeToString(buf),
  926. }
  927. return cli.stream("POST", "/images/"+name+"/push?"+v.Encode(), nil, cli.out, map[string][]string{
  928. "X-Registry-Auth": registryAuthHeader,
  929. })
  930. }
  931. if err := push(authConfig); err != nil {
  932. if err.Error() == registry.ErrLoginRequired.Error() {
  933. fmt.Fprintln(cli.out, "\nPlease login prior to push:")
  934. if err := cli.CmdLogin(endpoint); err != nil {
  935. return err
  936. }
  937. authConfig := cli.configFile.ResolveAuthConfig(endpoint)
  938. return push(authConfig)
  939. }
  940. return err
  941. }
  942. return nil
  943. }
  944. func (cli *DockerCli) CmdPull(args ...string) error {
  945. cmd := cli.Subcmd("pull", "NAME", "Pull an image or a repository from the registry")
  946. tag := cmd.String("t", "", "Download tagged image in repository")
  947. if err := cmd.Parse(args); err != nil {
  948. return nil
  949. }
  950. if cmd.NArg() != 1 {
  951. cmd.Usage()
  952. return nil
  953. }
  954. remote, parsedTag := utils.ParseRepositoryTag(cmd.Arg(0))
  955. if *tag == "" {
  956. *tag = parsedTag
  957. }
  958. // Resolve the Repository name from fqn to endpoint + name
  959. endpoint, _, err := registry.ResolveRepositoryName(remote)
  960. if err != nil {
  961. return err
  962. }
  963. cli.LoadConfigFile()
  964. // Resolve the Auth config relevant for this server
  965. authConfig := cli.configFile.ResolveAuthConfig(endpoint)
  966. v := url.Values{}
  967. v.Set("fromImage", remote)
  968. v.Set("tag", *tag)
  969. pull := func(authConfig auth.AuthConfig) error {
  970. buf, err := json.Marshal(authConfig)
  971. if err != nil {
  972. return err
  973. }
  974. registryAuthHeader := []string{
  975. base64.URLEncoding.EncodeToString(buf),
  976. }
  977. return cli.stream("POST", "/images/create?"+v.Encode(), nil, cli.out, map[string][]string{
  978. "X-Registry-Auth": registryAuthHeader,
  979. })
  980. }
  981. if err := pull(authConfig); err != nil {
  982. if err.Error() == registry.ErrLoginRequired.Error() {
  983. fmt.Fprintln(cli.out, "\nPlease login prior to push:")
  984. if err := cli.CmdLogin(endpoint); err != nil {
  985. return err
  986. }
  987. authConfig := cli.configFile.ResolveAuthConfig(endpoint)
  988. return pull(authConfig)
  989. }
  990. return err
  991. }
  992. return nil
  993. }
  994. func (cli *DockerCli) CmdImages(args ...string) error {
  995. cmd := cli.Subcmd("images", "[OPTIONS] [NAME]", "List images")
  996. quiet := cmd.Bool("q", false, "only show numeric IDs")
  997. all := cmd.Bool("a", false, "show all images (by default filter out the intermediate images used to build)")
  998. noTrunc := cmd.Bool("notrunc", false, "Don't truncate output")
  999. flViz := cmd.Bool("viz", false, "output graph in graphviz format")
  1000. flTree := cmd.Bool("tree", false, "output graph in tree format")
  1001. if err := cmd.Parse(args); err != nil {
  1002. return nil
  1003. }
  1004. if cmd.NArg() > 1 {
  1005. cmd.Usage()
  1006. return nil
  1007. }
  1008. filter := cmd.Arg(0)
  1009. if *flViz || *flTree {
  1010. body, _, err := cli.call("GET", "/images/json?all=1", nil)
  1011. if err != nil {
  1012. return err
  1013. }
  1014. var outs []APIImages
  1015. if err := json.Unmarshal(body, &outs); err != nil {
  1016. return err
  1017. }
  1018. var (
  1019. printNode func(cli *DockerCli, noTrunc bool, image APIImages, prefix string)
  1020. startImage APIImages
  1021. roots []APIImages
  1022. byParent = make(map[string][]APIImages)
  1023. )
  1024. for _, image := range outs {
  1025. if image.ParentId == "" {
  1026. roots = append(roots, image)
  1027. } else {
  1028. if children, exists := byParent[image.ParentId]; exists {
  1029. byParent[image.ParentId] = append(children, image)
  1030. } else {
  1031. byParent[image.ParentId] = []APIImages{image}
  1032. }
  1033. }
  1034. if filter != "" {
  1035. if filter == image.ID || filter == utils.TruncateID(image.ID) {
  1036. startImage = image
  1037. }
  1038. for _, repotag := range image.RepoTags {
  1039. if repotag == filter {
  1040. startImage = image
  1041. }
  1042. }
  1043. }
  1044. }
  1045. if *flViz {
  1046. fmt.Fprintf(cli.out, "digraph docker {\n")
  1047. printNode = (*DockerCli).printVizNode
  1048. } else {
  1049. printNode = (*DockerCli).printTreeNode
  1050. }
  1051. if startImage.ID != "" {
  1052. cli.WalkTree(*noTrunc, &[]APIImages{startImage}, byParent, "", printNode)
  1053. } else if filter == "" {
  1054. cli.WalkTree(*noTrunc, &roots, byParent, "", printNode)
  1055. }
  1056. if *flViz {
  1057. fmt.Fprintf(cli.out, " base [style=invisible]\n}\n")
  1058. }
  1059. } else {
  1060. v := url.Values{}
  1061. if cmd.NArg() == 1 {
  1062. v.Set("filter", filter)
  1063. }
  1064. if *all {
  1065. v.Set("all", "1")
  1066. }
  1067. body, _, err := cli.call("GET", "/images/json?"+v.Encode(), nil)
  1068. if err != nil {
  1069. return err
  1070. }
  1071. var outs []APIImages
  1072. err = json.Unmarshal(body, &outs)
  1073. if err != nil {
  1074. return err
  1075. }
  1076. w := tabwriter.NewWriter(cli.out, 20, 1, 3, ' ', 0)
  1077. if !*quiet {
  1078. fmt.Fprintln(w, "REPOSITORY\tTAG\tIMAGE ID\tCREATED\tVIRTUAL SIZE")
  1079. }
  1080. for _, out := range outs {
  1081. for _, repotag := range out.RepoTags {
  1082. repo, tag := utils.ParseRepositoryTag(repotag)
  1083. if !*noTrunc {
  1084. out.ID = utils.TruncateID(out.ID)
  1085. }
  1086. if !*quiet {
  1087. fmt.Fprintf(w, "%s\t%s\t%s\t%s ago\t%s\n", repo, tag, out.ID, utils.HumanDuration(time.Now().UTC().Sub(time.Unix(out.Created, 0))), utils.HumanSize(out.VirtualSize))
  1088. } else {
  1089. fmt.Fprintln(w, out.ID)
  1090. }
  1091. }
  1092. }
  1093. if !*quiet {
  1094. w.Flush()
  1095. }
  1096. }
  1097. return nil
  1098. }
  1099. func (cli *DockerCli) WalkTree(noTrunc bool, images *[]APIImages, byParent map[string][]APIImages, prefix string, printNode func(cli *DockerCli, noTrunc bool, image APIImages, prefix string)) {
  1100. length := len(*images)
  1101. if length > 1 {
  1102. for index, image := range *images {
  1103. if index+1 == length {
  1104. printNode(cli, noTrunc, image, prefix+"└─")
  1105. if subimages, exists := byParent[image.ID]; exists {
  1106. cli.WalkTree(noTrunc, &subimages, byParent, prefix+" ", printNode)
  1107. }
  1108. } else {
  1109. printNode(cli, noTrunc, image, prefix+"|─")
  1110. if subimages, exists := byParent[image.ID]; exists {
  1111. cli.WalkTree(noTrunc, &subimages, byParent, prefix+"| ", printNode)
  1112. }
  1113. }
  1114. }
  1115. } else {
  1116. for _, image := range *images {
  1117. printNode(cli, noTrunc, image, prefix+"└─")
  1118. if subimages, exists := byParent[image.ID]; exists {
  1119. cli.WalkTree(noTrunc, &subimages, byParent, prefix+" ", printNode)
  1120. }
  1121. }
  1122. }
  1123. }
  1124. func (cli *DockerCli) printVizNode(noTrunc bool, image APIImages, prefix string) {
  1125. var (
  1126. imageID string
  1127. parentID string
  1128. )
  1129. if noTrunc {
  1130. imageID = image.ID
  1131. parentID = image.ParentId
  1132. } else {
  1133. imageID = utils.TruncateID(image.ID)
  1134. parentID = utils.TruncateID(image.ParentId)
  1135. }
  1136. if image.ParentId == "" {
  1137. fmt.Fprintf(cli.out, " base -> \"%s\" [style=invis]\n", imageID)
  1138. } else {
  1139. fmt.Fprintf(cli.out, " \"%s\" -> \"%s\"\n", parentID, imageID)
  1140. }
  1141. if image.RepoTags[0] != "<none>:<none>" {
  1142. fmt.Fprintf(cli.out, " \"%s\" [label=\"%s\\n%s\",shape=box,fillcolor=\"paleturquoise\",style=\"filled,rounded\"];\n",
  1143. imageID, imageID, strings.Join(image.RepoTags, "\\n"))
  1144. }
  1145. }
  1146. func (cli *DockerCli) printTreeNode(noTrunc bool, image APIImages, prefix string) {
  1147. var imageID string
  1148. if noTrunc {
  1149. imageID = image.ID
  1150. } else {
  1151. imageID = utils.TruncateID(image.ID)
  1152. }
  1153. fmt.Fprintf(cli.out, "%s%s Virtual Size: %s", prefix, imageID, utils.HumanSize(image.VirtualSize))
  1154. if image.RepoTags[0] != "<none>:<none>" {
  1155. fmt.Fprintf(cli.out, " Tags: %s\n", strings.Join(image.RepoTags, ", "))
  1156. } else {
  1157. fmt.Fprint(cli.out, "\n")
  1158. }
  1159. }
  1160. func displayablePorts(ports []APIPort) string {
  1161. result := []string{}
  1162. for _, port := range ports {
  1163. if port.IP == "" {
  1164. result = append(result, fmt.Sprintf("%d/%s", port.PublicPort, port.Type))
  1165. } else {
  1166. result = append(result, fmt.Sprintf("%s:%d->%d/%s", port.IP, port.PublicPort, port.PrivatePort, port.Type))
  1167. }
  1168. }
  1169. sort.Strings(result)
  1170. return strings.Join(result, ", ")
  1171. }
  1172. func (cli *DockerCli) CmdPs(args ...string) error {
  1173. cmd := cli.Subcmd("ps", "[OPTIONS]", "List containers")
  1174. quiet := cmd.Bool("q", false, "Only display numeric IDs")
  1175. size := cmd.Bool("s", false, "Display sizes")
  1176. all := cmd.Bool("a", false, "Show all containers. Only running containers are shown by default.")
  1177. noTrunc := cmd.Bool("notrunc", false, "Don't truncate output")
  1178. nLatest := cmd.Bool("l", false, "Show only the latest created container, include non-running ones.")
  1179. since := cmd.String("sinceId", "", "Show only containers created since Id, include non-running ones.")
  1180. before := cmd.String("beforeId", "", "Show only container created before Id, include non-running ones.")
  1181. last := cmd.Int("n", -1, "Show n last created containers, include non-running ones.")
  1182. if err := cmd.Parse(args); err != nil {
  1183. return nil
  1184. }
  1185. v := url.Values{}
  1186. if *last == -1 && *nLatest {
  1187. *last = 1
  1188. }
  1189. if *all {
  1190. v.Set("all", "1")
  1191. }
  1192. if *last != -1 {
  1193. v.Set("limit", strconv.Itoa(*last))
  1194. }
  1195. if *since != "" {
  1196. v.Set("since", *since)
  1197. }
  1198. if *before != "" {
  1199. v.Set("before", *before)
  1200. }
  1201. if *size {
  1202. v.Set("size", "1")
  1203. }
  1204. body, _, err := cli.call("GET", "/containers/json?"+v.Encode(), nil)
  1205. if err != nil {
  1206. return err
  1207. }
  1208. var outs []APIContainers
  1209. err = json.Unmarshal(body, &outs)
  1210. if err != nil {
  1211. return err
  1212. }
  1213. w := tabwriter.NewWriter(cli.out, 20, 1, 3, ' ', 0)
  1214. if !*quiet {
  1215. fmt.Fprint(w, "CONTAINER ID\tIMAGE\tCOMMAND\tCREATED\tSTATUS\tPORTS\tNAMES")
  1216. if *size {
  1217. fmt.Fprintln(w, "\tSIZE")
  1218. } else {
  1219. fmt.Fprint(w, "\n")
  1220. }
  1221. }
  1222. for _, out := range outs {
  1223. if !*noTrunc {
  1224. out.ID = utils.TruncateID(out.ID)
  1225. }
  1226. // Remove the leading / from the names
  1227. for i := 0; i < len(out.Names); i++ {
  1228. out.Names[i] = out.Names[i][1:]
  1229. }
  1230. if !*quiet {
  1231. if !*noTrunc {
  1232. out.Command = utils.Trunc(out.Command, 20)
  1233. }
  1234. fmt.Fprintf(w, "%s\t%s\t%s\t%s ago\t%s\t%s\t%s\t", out.ID, out.Image, out.Command, utils.HumanDuration(time.Now().UTC().Sub(time.Unix(out.Created, 0))), out.Status, displayablePorts(out.Ports), strings.Join(out.Names, ","))
  1235. if *size {
  1236. if out.SizeRootFs > 0 {
  1237. fmt.Fprintf(w, "%s (virtual %s)\n", utils.HumanSize(out.SizeRw), utils.HumanSize(out.SizeRootFs))
  1238. } else {
  1239. fmt.Fprintf(w, "%s\n", utils.HumanSize(out.SizeRw))
  1240. }
  1241. } else {
  1242. fmt.Fprint(w, "\n")
  1243. }
  1244. } else {
  1245. fmt.Fprintln(w, out.ID)
  1246. }
  1247. }
  1248. if !*quiet {
  1249. w.Flush()
  1250. }
  1251. return nil
  1252. }
  1253. func (cli *DockerCli) CmdCommit(args ...string) error {
  1254. cmd := cli.Subcmd("commit", "[OPTIONS] CONTAINER [REPOSITORY[:TAG]]", "Create a new image from a container's changes")
  1255. flComment := cmd.String("m", "", "Commit message")
  1256. flAuthor := cmd.String("author", "", "Author (eg. \"John Hannibal Smith <hannibal@a-team.com>\"")
  1257. flConfig := cmd.String("run", "", "Config automatically applied when the image is run. "+`(ex: -run='{"Cmd": ["cat", "/world"], "PortSpecs": ["22"]}')`)
  1258. if err := cmd.Parse(args); err != nil {
  1259. return nil
  1260. }
  1261. var name, repository, tag string
  1262. if cmd.NArg() == 3 {
  1263. fmt.Fprintf(cli.err, "[DEPRECATED] The format 'CONTAINER [REPOSITORY [TAG]]' as been deprecated. Please use CONTAINER [REPOSITORY[:TAG]]\n")
  1264. name, repository, tag = cmd.Arg(0), cmd.Arg(1), cmd.Arg(2)
  1265. } else {
  1266. name = cmd.Arg(0)
  1267. repository, tag = utils.ParseRepositoryTag(cmd.Arg(1))
  1268. }
  1269. if name == "" {
  1270. cmd.Usage()
  1271. return nil
  1272. }
  1273. v := url.Values{}
  1274. v.Set("container", name)
  1275. v.Set("repo", repository)
  1276. v.Set("tag", tag)
  1277. v.Set("comment", *flComment)
  1278. v.Set("author", *flAuthor)
  1279. var config *Config
  1280. if *flConfig != "" {
  1281. config = &Config{}
  1282. if err := json.Unmarshal([]byte(*flConfig), config); err != nil {
  1283. return err
  1284. }
  1285. }
  1286. body, _, err := cli.call("POST", "/commit?"+v.Encode(), config)
  1287. if err != nil {
  1288. return err
  1289. }
  1290. apiID := &APIID{}
  1291. err = json.Unmarshal(body, apiID)
  1292. if err != nil {
  1293. return err
  1294. }
  1295. fmt.Fprintf(cli.out, "%s\n", apiID.ID)
  1296. return nil
  1297. }
  1298. func (cli *DockerCli) CmdEvents(args ...string) error {
  1299. cmd := cli.Subcmd("events", "[OPTIONS]", "Get real time events from the server")
  1300. since := cmd.String("since", "", "Show previously created events and then stream.")
  1301. if err := cmd.Parse(args); err != nil {
  1302. return nil
  1303. }
  1304. if cmd.NArg() != 0 {
  1305. cmd.Usage()
  1306. return nil
  1307. }
  1308. v := url.Values{}
  1309. if *since != "" {
  1310. loc := time.FixedZone(time.Now().Zone())
  1311. format := "2006-01-02 15:04:05 -0700 MST"
  1312. if len(*since) < len(format) {
  1313. format = format[:len(*since)]
  1314. }
  1315. if t, err := time.ParseInLocation(format, *since, loc); err == nil {
  1316. v.Set("since", strconv.FormatInt(t.Unix(), 10))
  1317. } else {
  1318. v.Set("since", *since)
  1319. }
  1320. }
  1321. if err := cli.stream("GET", "/events?"+v.Encode(), nil, cli.out, nil); err != nil {
  1322. return err
  1323. }
  1324. return nil
  1325. }
  1326. func (cli *DockerCli) CmdExport(args ...string) error {
  1327. cmd := cli.Subcmd("export", "CONTAINER", "Export the contents of a filesystem as a tar archive to STDOUT")
  1328. if err := cmd.Parse(args); err != nil {
  1329. return nil
  1330. }
  1331. if cmd.NArg() != 1 {
  1332. cmd.Usage()
  1333. return nil
  1334. }
  1335. if err := cli.stream("GET", "/containers/"+cmd.Arg(0)+"/export", nil, cli.out, nil); err != nil {
  1336. return err
  1337. }
  1338. return nil
  1339. }
  1340. func (cli *DockerCli) CmdDiff(args ...string) error {
  1341. cmd := cli.Subcmd("diff", "CONTAINER", "Inspect changes on a container's filesystem")
  1342. if err := cmd.Parse(args); err != nil {
  1343. return nil
  1344. }
  1345. if cmd.NArg() != 1 {
  1346. cmd.Usage()
  1347. return nil
  1348. }
  1349. body, _, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/changes", nil)
  1350. if err != nil {
  1351. return err
  1352. }
  1353. changes := []Change{}
  1354. err = json.Unmarshal(body, &changes)
  1355. if err != nil {
  1356. return err
  1357. }
  1358. for _, change := range changes {
  1359. fmt.Fprintf(cli.out, "%s\n", change.String())
  1360. }
  1361. return nil
  1362. }
  1363. func (cli *DockerCli) CmdLogs(args ...string) error {
  1364. cmd := cli.Subcmd("logs", "CONTAINER", "Fetch the logs of a container")
  1365. follow := cmd.Bool("f", false, "Follow log output")
  1366. if err := cmd.Parse(args); err != nil {
  1367. return nil
  1368. }
  1369. if cmd.NArg() != 1 {
  1370. cmd.Usage()
  1371. return nil
  1372. }
  1373. name := cmd.Arg(0)
  1374. body, _, err := cli.call("GET", "/containers/"+name+"/json", nil)
  1375. if err != nil {
  1376. return err
  1377. }
  1378. container := &Container{}
  1379. err = json.Unmarshal(body, container)
  1380. if err != nil {
  1381. return err
  1382. }
  1383. v := url.Values{}
  1384. v.Set("logs", "1")
  1385. v.Set("stdout", "1")
  1386. v.Set("stderr", "1")
  1387. if *follow && container.State.Running {
  1388. v.Set("stream", "1")
  1389. }
  1390. if err := cli.hijack("POST", "/containers/"+name+"/attach?"+v.Encode(), container.Config.Tty, nil, cli.out, cli.err, nil); err != nil {
  1391. return err
  1392. }
  1393. return nil
  1394. }
  1395. func (cli *DockerCli) CmdAttach(args ...string) error {
  1396. cmd := cli.Subcmd("attach", "[OPTIONS] CONTAINER", "Attach to a running container")
  1397. noStdin := cmd.Bool("nostdin", false, "Do not attach stdin")
  1398. proxy := cmd.Bool("sig-proxy", true, "Proxify all received signal to the process (even in non-tty mode)")
  1399. if err := cmd.Parse(args); err != nil {
  1400. return nil
  1401. }
  1402. if cmd.NArg() != 1 {
  1403. cmd.Usage()
  1404. return nil
  1405. }
  1406. name := cmd.Arg(0)
  1407. body, _, err := cli.call("GET", "/containers/"+name+"/json", nil)
  1408. if err != nil {
  1409. return err
  1410. }
  1411. container := &Container{}
  1412. err = json.Unmarshal(body, container)
  1413. if err != nil {
  1414. return err
  1415. }
  1416. if !container.State.IsRunning() {
  1417. return fmt.Errorf("Impossible to attach to a stopped container, start it first")
  1418. }
  1419. if container.Config.Tty && cli.isTerminal {
  1420. if err := cli.monitorTtySize(cmd.Arg(0)); err != nil {
  1421. utils.Debugf("Error monitoring TTY size: %s", err)
  1422. }
  1423. }
  1424. var in io.ReadCloser
  1425. v := url.Values{}
  1426. v.Set("stream", "1")
  1427. if !*noStdin && container.Config.OpenStdin {
  1428. v.Set("stdin", "1")
  1429. in = cli.in
  1430. }
  1431. v.Set("stdout", "1")
  1432. v.Set("stderr", "1")
  1433. if *proxy && !container.Config.Tty {
  1434. sigc := cli.forwardAllSignals(cmd.Arg(0))
  1435. defer utils.StopCatch(sigc)
  1436. }
  1437. if err := cli.hijack("POST", "/containers/"+cmd.Arg(0)+"/attach?"+v.Encode(), container.Config.Tty, in, cli.out, cli.err, nil); err != nil {
  1438. return err
  1439. }
  1440. _, status, err := getExitCode(cli, cmd.Arg(0))
  1441. if err != nil {
  1442. return err
  1443. }
  1444. if status != 0 {
  1445. return &utils.StatusError{StatusCode: status}
  1446. }
  1447. return nil
  1448. }
  1449. func (cli *DockerCli) CmdSearch(args ...string) error {
  1450. cmd := cli.Subcmd("search", "TERM", "Search the docker index for images")
  1451. noTrunc := cmd.Bool("notrunc", false, "Don't truncate output")
  1452. trusted := cmd.Bool("trusted", false, "Only show trusted builds")
  1453. stars := cmd.Int("stars", 0, "Only displays with at least xxx stars")
  1454. if err := cmd.Parse(args); err != nil {
  1455. return nil
  1456. }
  1457. if cmd.NArg() != 1 {
  1458. cmd.Usage()
  1459. return nil
  1460. }
  1461. v := url.Values{}
  1462. v.Set("term", cmd.Arg(0))
  1463. body, _, err := cli.call("GET", "/images/search?"+v.Encode(), nil)
  1464. if err != nil {
  1465. return err
  1466. }
  1467. outs := []registry.SearchResult{}
  1468. err = json.Unmarshal(body, &outs)
  1469. if err != nil {
  1470. return err
  1471. }
  1472. w := tabwriter.NewWriter(cli.out, 10, 1, 3, ' ', 0)
  1473. fmt.Fprintf(w, "NAME\tDESCRIPTION\tSTARS\tOFFICIAL\tTRUSTED\n")
  1474. for _, out := range outs {
  1475. if (*trusted && !out.IsTrusted) || (*stars > out.StarCount) {
  1476. continue
  1477. }
  1478. desc := strings.Replace(out.Description, "\n", " ", -1)
  1479. desc = strings.Replace(desc, "\r", " ", -1)
  1480. if !*noTrunc && len(desc) > 45 {
  1481. desc = utils.Trunc(desc, 42) + "..."
  1482. }
  1483. fmt.Fprintf(w, "%s\t%s\t%d\t", out.Name, desc, out.StarCount)
  1484. if out.IsOfficial {
  1485. fmt.Fprint(w, "[OK]")
  1486. }
  1487. fmt.Fprint(w, "\t")
  1488. if out.IsTrusted {
  1489. fmt.Fprint(w, "[OK]")
  1490. }
  1491. fmt.Fprint(w, "\n")
  1492. }
  1493. w.Flush()
  1494. return nil
  1495. }
  1496. // Ports type - Used to parse multiple -p flags
  1497. type ports []int
  1498. func (cli *DockerCli) CmdTag(args ...string) error {
  1499. cmd := cli.Subcmd("tag", "[OPTIONS] IMAGE REPOSITORY[:TAG]", "Tag an image into a repository")
  1500. force := cmd.Bool("f", false, "Force")
  1501. if err := cmd.Parse(args); err != nil {
  1502. return nil
  1503. }
  1504. if cmd.NArg() != 2 && cmd.NArg() != 3 {
  1505. cmd.Usage()
  1506. return nil
  1507. }
  1508. var repository, tag string
  1509. if cmd.NArg() == 3 {
  1510. fmt.Fprintf(cli.err, "[DEPRECATED] The format 'IMAGE [REPOSITORY [TAG]]' as been deprecated. Please use IMAGE [REPOSITORY[:TAG]]\n")
  1511. repository, tag = cmd.Arg(1), cmd.Arg(2)
  1512. } else {
  1513. repository, tag = utils.ParseRepositoryTag(cmd.Arg(1))
  1514. }
  1515. v := url.Values{}
  1516. v.Set("repo", repository)
  1517. v.Set("tag", tag)
  1518. if *force {
  1519. v.Set("force", "1")
  1520. }
  1521. if _, _, err := cli.call("POST", "/images/"+cmd.Arg(0)+"/tag?"+v.Encode(), nil); err != nil {
  1522. return err
  1523. }
  1524. return nil
  1525. }
  1526. //FIXME Only used in tests
  1527. func ParseRun(args []string, capabilities *Capabilities) (*Config, *HostConfig, *flag.FlagSet, error) {
  1528. cmd := flag.NewFlagSet("run", flag.ContinueOnError)
  1529. cmd.SetOutput(ioutil.Discard)
  1530. cmd.Usage = nil
  1531. return parseRun(cmd, args, capabilities)
  1532. }
  1533. func parseRun(cmd *flag.FlagSet, args []string, capabilities *Capabilities) (*Config, *HostConfig, *flag.FlagSet, error) {
  1534. var (
  1535. // FIXME: use utils.ListOpts for attach and volumes?
  1536. flAttach = NewListOpts(ValidateAttach)
  1537. flVolumes = NewListOpts(ValidatePath)
  1538. flLinks = NewListOpts(ValidateLink)
  1539. flEnv = NewListOpts(ValidateEnv)
  1540. flPublish ListOpts
  1541. flExpose ListOpts
  1542. flDns ListOpts
  1543. flVolumesFrom ListOpts
  1544. flLxcOpts ListOpts
  1545. flAutoRemove = cmd.Bool("rm", false, "Automatically remove the container when it exits (incompatible with -d)")
  1546. flDetach = cmd.Bool("d", false, "Detached mode: Run container in the background, print new container id")
  1547. flNetwork = cmd.Bool("n", true, "Enable networking for this container")
  1548. flPrivileged = cmd.Bool("privileged", false, "Give extended privileges to this container")
  1549. flPublishAll = cmd.Bool("P", false, "Publish all exposed ports to the host interfaces")
  1550. flStdin = cmd.Bool("i", false, "Keep stdin open even if not attached")
  1551. flTty = cmd.Bool("t", false, "Allocate a pseudo-tty")
  1552. flContainerIDFile = cmd.String("cidfile", "", "Write the container ID to the file")
  1553. flEntrypoint = cmd.String("entrypoint", "", "Overwrite the default entrypoint of the image")
  1554. flHostname = cmd.String("h", "", "Container host name")
  1555. flMemoryString = cmd.String("m", "", "Memory limit (format: <number><optional unit>, where unit = b, k, m or g)")
  1556. flUser = cmd.String("u", "", "Username or UID")
  1557. flWorkingDir = cmd.String("w", "", "Working directory inside the container")
  1558. flCpuShares = cmd.Int64("c", 0, "CPU shares (relative weight)")
  1559. // For documentation purpose
  1560. _ = cmd.Bool("sig-proxy", true, "Proxify all received signal to the process (even in non-tty mode)")
  1561. _ = cmd.String("name", "", "Assign a name to the container")
  1562. )
  1563. cmd.Var(&flAttach, "a", "Attach to stdin, stdout or stderr.")
  1564. cmd.Var(&flVolumes, "v", "Bind mount a volume (e.g. from the host: -v /host:/container, from docker: -v /container)")
  1565. cmd.Var(&flLinks, "link", "Add link to another container (name:alias)")
  1566. cmd.Var(&flEnv, "e", "Set environment variables")
  1567. cmd.Var(&flPublish, "p", fmt.Sprintf("Publish a container's port to the host (format: %s) (use 'docker port' to see the actual mapping)", PortSpecTemplateFormat))
  1568. cmd.Var(&flExpose, "expose", "Expose a port from the container without publishing it to your host")
  1569. cmd.Var(&flDns, "dns", "Set custom dns servers")
  1570. cmd.Var(&flVolumesFrom, "volumes-from", "Mount volumes from the specified container(s)")
  1571. cmd.Var(&flLxcOpts, "lxc-conf", "Add custom lxc options -lxc-conf=\"lxc.cgroup.cpuset.cpus = 0,1\"")
  1572. if err := cmd.Parse(args); err != nil {
  1573. return nil, nil, cmd, err
  1574. }
  1575. // Check if the kernel supports memory limit cgroup.
  1576. if capabilities != nil && *flMemoryString != "" && !capabilities.MemoryLimit {
  1577. *flMemoryString = ""
  1578. }
  1579. // Validate input params
  1580. if *flDetach && flAttach.Len() > 0 {
  1581. return nil, nil, cmd, ErrConflictAttachDetach
  1582. }
  1583. if *flWorkingDir != "" && !path.IsAbs(*flWorkingDir) {
  1584. return nil, nil, cmd, ErrInvalidWorikingDirectory
  1585. }
  1586. if *flDetach && *flAutoRemove {
  1587. return nil, nil, cmd, ErrConflictDetachAutoRemove
  1588. }
  1589. // If neither -d or -a are set, attach to everything by default
  1590. if flAttach.Len() == 0 && !*flDetach {
  1591. if !*flDetach {
  1592. flAttach.Set("stdout")
  1593. flAttach.Set("stderr")
  1594. if *flStdin {
  1595. flAttach.Set("stdin")
  1596. }
  1597. }
  1598. }
  1599. var flMemory int64
  1600. if *flMemoryString != "" {
  1601. parsedMemory, err := utils.RAMInBytes(*flMemoryString)
  1602. if err != nil {
  1603. return nil, nil, cmd, err
  1604. }
  1605. flMemory = parsedMemory
  1606. }
  1607. var binds []string
  1608. // add any bind targets to the list of container volumes
  1609. for bind := range flVolumes.GetMap() {
  1610. if arr := strings.Split(bind, ":"); len(arr) > 1 {
  1611. if arr[0] == "/" {
  1612. return nil, nil, cmd, fmt.Errorf("Invalid bind mount: source can't be '/'")
  1613. }
  1614. dstDir := arr[1]
  1615. flVolumes.Set(dstDir)
  1616. binds = append(binds, bind)
  1617. flVolumes.Delete(bind)
  1618. } else if bind == "/" {
  1619. return nil, nil, cmd, fmt.Errorf("Invalid volume: path can't be '/'")
  1620. }
  1621. }
  1622. var (
  1623. parsedArgs = cmd.Args()
  1624. runCmd []string
  1625. entrypoint []string
  1626. image string
  1627. )
  1628. if len(parsedArgs) >= 1 {
  1629. image = cmd.Arg(0)
  1630. }
  1631. if len(parsedArgs) > 1 {
  1632. runCmd = parsedArgs[1:]
  1633. }
  1634. if *flEntrypoint != "" {
  1635. entrypoint = []string{*flEntrypoint}
  1636. }
  1637. lxcConf, err := parseLxcConfOpts(flLxcOpts)
  1638. if err != nil {
  1639. return nil, nil, cmd, err
  1640. }
  1641. var (
  1642. domainname string
  1643. hostname = *flHostname
  1644. parts = strings.SplitN(hostname, ".", 2)
  1645. )
  1646. if len(parts) > 1 {
  1647. hostname = parts[0]
  1648. domainname = parts[1]
  1649. }
  1650. ports, portBindings, err := parsePortSpecs(flPublish.GetAll())
  1651. if err != nil {
  1652. return nil, nil, cmd, err
  1653. }
  1654. // Merge in exposed ports to the map of published ports
  1655. for _, e := range flExpose.GetAll() {
  1656. if strings.Contains(e, ":") {
  1657. return nil, nil, cmd, fmt.Errorf("Invalid port format for -expose: %s", e)
  1658. }
  1659. p := NewPort(splitProtoPort(e))
  1660. if _, exists := ports[p]; !exists {
  1661. ports[p] = struct{}{}
  1662. }
  1663. }
  1664. config := &Config{
  1665. Hostname: hostname,
  1666. Domainname: domainname,
  1667. PortSpecs: nil, // Deprecated
  1668. ExposedPorts: ports,
  1669. User: *flUser,
  1670. Tty: *flTty,
  1671. NetworkDisabled: !*flNetwork,
  1672. OpenStdin: *flStdin,
  1673. Memory: flMemory,
  1674. CpuShares: *flCpuShares,
  1675. AttachStdin: flAttach.Get("stdin"),
  1676. AttachStdout: flAttach.Get("stdout"),
  1677. AttachStderr: flAttach.Get("stderr"),
  1678. Env: flEnv.GetAll(),
  1679. Cmd: runCmd,
  1680. Dns: flDns.GetAll(),
  1681. Image: image,
  1682. Volumes: flVolumes.GetMap(),
  1683. VolumesFrom: strings.Join(flVolumesFrom.GetAll(), ","),
  1684. Entrypoint: entrypoint,
  1685. WorkingDir: *flWorkingDir,
  1686. }
  1687. hostConfig := &HostConfig{
  1688. Binds: binds,
  1689. ContainerIDFile: *flContainerIDFile,
  1690. LxcConf: lxcConf,
  1691. Privileged: *flPrivileged,
  1692. PortBindings: portBindings,
  1693. Links: flLinks.GetAll(),
  1694. PublishAllPorts: *flPublishAll,
  1695. }
  1696. if capabilities != nil && flMemory > 0 && !capabilities.SwapLimit {
  1697. //fmt.Fprintf(stdout, "WARNING: Your kernel does not support swap limit capabilities. Limitation discarded.\n")
  1698. config.MemorySwap = -1
  1699. }
  1700. // When allocating stdin in attached mode, close stdin at client disconnect
  1701. if config.OpenStdin && config.AttachStdin {
  1702. config.StdinOnce = true
  1703. }
  1704. return config, hostConfig, cmd, nil
  1705. }
  1706. func (cli *DockerCli) CmdRun(args ...string) error {
  1707. config, hostConfig, cmd, err := parseRun(cli.Subcmd("run", "[OPTIONS] IMAGE [COMMAND] [ARG...]", "Run a command in a new container"), args, nil)
  1708. if err != nil {
  1709. return err
  1710. }
  1711. if config.Image == "" {
  1712. cmd.Usage()
  1713. return nil
  1714. }
  1715. // Retrieve relevant client-side config
  1716. var (
  1717. flName = cmd.Lookup("name")
  1718. flRm = cmd.Lookup("rm")
  1719. flSigProxy = cmd.Lookup("sig-proxy")
  1720. autoRemove, _ = strconv.ParseBool(flRm.Value.String())
  1721. sigProxy, _ = strconv.ParseBool(flSigProxy.Value.String())
  1722. )
  1723. // Disable sigProxy in case on TTY
  1724. if config.Tty {
  1725. sigProxy = false
  1726. }
  1727. var containerIDFile io.WriteCloser
  1728. if len(hostConfig.ContainerIDFile) > 0 {
  1729. if _, err := os.Stat(hostConfig.ContainerIDFile); err == nil {
  1730. return fmt.Errorf("cid file found, make sure the other container isn't running or delete %s", hostConfig.ContainerIDFile)
  1731. }
  1732. if containerIDFile, err = os.Create(hostConfig.ContainerIDFile); err != nil {
  1733. return fmt.Errorf("failed to create the container ID file: %s", err)
  1734. }
  1735. defer containerIDFile.Close()
  1736. }
  1737. containerValues := url.Values{}
  1738. if name := flName.Value.String(); name != "" {
  1739. containerValues.Set("name", name)
  1740. }
  1741. //create the container
  1742. body, statusCode, err := cli.call("POST", "/containers/create?"+containerValues.Encode(), config)
  1743. //if image not found try to pull it
  1744. if statusCode == 404 {
  1745. _, tag := utils.ParseRepositoryTag(config.Image)
  1746. if tag == "" {
  1747. tag = DEFAULTTAG
  1748. }
  1749. fmt.Fprintf(cli.err, "Unable to find image '%s' (tag: %s) locally\n", config.Image, tag)
  1750. v := url.Values{}
  1751. repos, tag := utils.ParseRepositoryTag(config.Image)
  1752. v.Set("fromImage", repos)
  1753. v.Set("tag", tag)
  1754. // Resolve the Repository name from fqn to endpoint + name
  1755. endpoint, _, err := registry.ResolveRepositoryName(repos)
  1756. if err != nil {
  1757. return err
  1758. }
  1759. // Load the auth config file, to be able to pull the image
  1760. cli.LoadConfigFile()
  1761. // Resolve the Auth config relevant for this server
  1762. authConfig := cli.configFile.ResolveAuthConfig(endpoint)
  1763. buf, err := json.Marshal(authConfig)
  1764. if err != nil {
  1765. return err
  1766. }
  1767. registryAuthHeader := []string{
  1768. base64.URLEncoding.EncodeToString(buf),
  1769. }
  1770. if err = cli.stream("POST", "/images/create?"+v.Encode(), nil, cli.err, map[string][]string{"X-Registry-Auth": registryAuthHeader}); err != nil {
  1771. return err
  1772. }
  1773. if body, _, err = cli.call("POST", "/containers/create?"+containerValues.Encode(), config); err != nil {
  1774. return err
  1775. }
  1776. } else if err != nil {
  1777. return err
  1778. }
  1779. var runResult APIRun
  1780. if err := json.Unmarshal(body, &runResult); err != nil {
  1781. return err
  1782. }
  1783. for _, warning := range runResult.Warnings {
  1784. fmt.Fprintf(cli.err, "WARNING: %s\n", warning)
  1785. }
  1786. if len(hostConfig.ContainerIDFile) > 0 {
  1787. if _, err = containerIDFile.Write([]byte(runResult.ID)); err != nil {
  1788. return fmt.Errorf("failed to write the container ID to the file: %s", err)
  1789. }
  1790. }
  1791. if sigProxy {
  1792. sigc := cli.forwardAllSignals(runResult.ID)
  1793. defer utils.StopCatch(sigc)
  1794. }
  1795. var (
  1796. waitDisplayId chan struct{}
  1797. errCh chan error
  1798. )
  1799. if !config.AttachStdout && !config.AttachStderr {
  1800. // Make this asynchrone in order to let the client write to stdin before having to read the ID
  1801. waitDisplayId = make(chan struct{})
  1802. go func() {
  1803. defer close(waitDisplayId)
  1804. fmt.Fprintf(cli.out, "%s\n", runResult.ID)
  1805. }()
  1806. }
  1807. // We need to instanciate the chan because the select needs it. It can
  1808. // be closed but can't be uninitialized.
  1809. hijacked := make(chan io.Closer)
  1810. // Block the return until the chan gets closed
  1811. defer func() {
  1812. utils.Debugf("End of CmdRun(), Waiting for hijack to finish.")
  1813. if _, ok := <-hijacked; ok {
  1814. utils.Errorf("Hijack did not finish (chan still open)")
  1815. }
  1816. }()
  1817. if config.AttachStdin || config.AttachStdout || config.AttachStderr {
  1818. var (
  1819. out, stderr io.Writer
  1820. in io.ReadCloser
  1821. v = url.Values{}
  1822. )
  1823. v.Set("stream", "1")
  1824. if config.AttachStdin {
  1825. v.Set("stdin", "1")
  1826. in = cli.in
  1827. }
  1828. if config.AttachStdout {
  1829. v.Set("stdout", "1")
  1830. out = cli.out
  1831. }
  1832. if config.AttachStderr {
  1833. v.Set("stderr", "1")
  1834. if config.Tty {
  1835. stderr = cli.out
  1836. } else {
  1837. stderr = cli.err
  1838. }
  1839. }
  1840. errCh = utils.Go(func() error {
  1841. return cli.hijack("POST", "/containers/"+runResult.ID+"/attach?"+v.Encode(), config.Tty, in, out, stderr, hijacked)
  1842. })
  1843. } else {
  1844. close(hijacked)
  1845. }
  1846. // Acknowledge the hijack before starting
  1847. select {
  1848. case closer := <-hijacked:
  1849. // Make sure that hijack gets closed when returning. (result
  1850. // in closing hijack chan and freeing server's goroutines.
  1851. if closer != nil {
  1852. defer closer.Close()
  1853. }
  1854. case err := <-errCh:
  1855. if err != nil {
  1856. utils.Debugf("Error hijack: %s", err)
  1857. return err
  1858. }
  1859. }
  1860. //start the container
  1861. if _, _, err = cli.call("POST", "/containers/"+runResult.ID+"/start", hostConfig); err != nil {
  1862. return err
  1863. }
  1864. if (config.AttachStdin || config.AttachStdout || config.AttachStderr) && config.Tty && cli.isTerminal {
  1865. if err := cli.monitorTtySize(runResult.ID); err != nil {
  1866. utils.Errorf("Error monitoring TTY size: %s\n", err)
  1867. }
  1868. }
  1869. if errCh != nil {
  1870. if err := <-errCh; err != nil {
  1871. utils.Debugf("Error hijack: %s", err)
  1872. return err
  1873. }
  1874. }
  1875. // Detached mode: wait for the id to be displayed and return.
  1876. if !config.AttachStdout && !config.AttachStderr {
  1877. // Detached mode
  1878. <-waitDisplayId
  1879. return nil
  1880. }
  1881. var status int
  1882. // Attached mode
  1883. if autoRemove {
  1884. // Autoremove: wait for the container to finish, retrieve
  1885. // the exit code and remove the container
  1886. if _, _, err := cli.call("POST", "/containers/"+runResult.ID+"/wait", nil); err != nil {
  1887. return err
  1888. }
  1889. if _, status, err = getExitCode(cli, runResult.ID); err != nil {
  1890. return err
  1891. }
  1892. if _, _, err := cli.call("DELETE", "/containers/"+runResult.ID, nil); err != nil {
  1893. return err
  1894. }
  1895. } else {
  1896. // No Autoremove: Simply retrieve the exit code
  1897. if _, status, err = getExitCode(cli, runResult.ID); err != nil {
  1898. return err
  1899. }
  1900. }
  1901. if status != 0 {
  1902. return &utils.StatusError{StatusCode: status}
  1903. }
  1904. return nil
  1905. }
  1906. func (cli *DockerCli) CmdCp(args ...string) error {
  1907. cmd := cli.Subcmd("cp", "CONTAINER:PATH HOSTPATH", "Copy files/folders from the PATH to the HOSTPATH")
  1908. if err := cmd.Parse(args); err != nil {
  1909. return nil
  1910. }
  1911. if cmd.NArg() != 2 {
  1912. cmd.Usage()
  1913. return nil
  1914. }
  1915. var copyData APICopy
  1916. info := strings.Split(cmd.Arg(0), ":")
  1917. if len(info) != 2 {
  1918. return fmt.Errorf("Error: Path not specified")
  1919. }
  1920. copyData.Resource = info[1]
  1921. copyData.HostPath = cmd.Arg(1)
  1922. data, statusCode, err := cli.call("POST", "/containers/"+info[0]+"/copy", copyData)
  1923. if err != nil {
  1924. return err
  1925. }
  1926. if statusCode == 200 {
  1927. r := bytes.NewReader(data)
  1928. if err := archive.Untar(r, copyData.HostPath, nil); err != nil {
  1929. return err
  1930. }
  1931. }
  1932. return nil
  1933. }
  1934. func (cli *DockerCli) CmdSave(args ...string) error {
  1935. cmd := cli.Subcmd("save", "IMAGE", "Save an image to a tar archive (streamed to stdout)")
  1936. if err := cmd.Parse(args); err != nil {
  1937. return err
  1938. }
  1939. if cmd.NArg() != 1 {
  1940. cmd.Usage()
  1941. return nil
  1942. }
  1943. image := cmd.Arg(0)
  1944. if err := cli.stream("GET", "/images/"+image+"/get", nil, cli.out, nil); err != nil {
  1945. return err
  1946. }
  1947. return nil
  1948. }
  1949. func (cli *DockerCli) CmdLoad(args ...string) error {
  1950. cmd := cli.Subcmd("load", "SOURCE", "Load an image from a tar archive")
  1951. if err := cmd.Parse(args); err != nil {
  1952. return err
  1953. }
  1954. if cmd.NArg() != 0 {
  1955. cmd.Usage()
  1956. return nil
  1957. }
  1958. if err := cli.stream("POST", "/images/load", cli.in, cli.out, nil); err != nil {
  1959. return err
  1960. }
  1961. return nil
  1962. }
  1963. func (cli *DockerCli) call(method, path string, data interface{}) ([]byte, int, error) {
  1964. var params io.Reader
  1965. if data != nil {
  1966. buf, err := json.Marshal(data)
  1967. if err != nil {
  1968. return nil, -1, err
  1969. }
  1970. params = bytes.NewBuffer(buf)
  1971. }
  1972. // fixme: refactor client to support redirect
  1973. re := regexp.MustCompile("/+")
  1974. path = re.ReplaceAllString(path, "/")
  1975. req, err := http.NewRequest(method, fmt.Sprintf("/v%g%s", APIVERSION, path), params)
  1976. if err != nil {
  1977. return nil, -1, err
  1978. }
  1979. req.Header.Set("User-Agent", "Docker-Client/"+VERSION)
  1980. req.Host = cli.addr
  1981. if data != nil {
  1982. req.Header.Set("Content-Type", "application/json")
  1983. } else if method == "POST" {
  1984. req.Header.Set("Content-Type", "plain/text")
  1985. }
  1986. dial, err := net.Dial(cli.proto, cli.addr)
  1987. if err != nil {
  1988. if strings.Contains(err.Error(), "connection refused") {
  1989. return nil, -1, ErrConnectionRefused
  1990. }
  1991. return nil, -1, err
  1992. }
  1993. clientconn := httputil.NewClientConn(dial, nil)
  1994. resp, err := clientconn.Do(req)
  1995. defer clientconn.Close()
  1996. if err != nil {
  1997. if strings.Contains(err.Error(), "connection refused") {
  1998. return nil, -1, ErrConnectionRefused
  1999. }
  2000. return nil, -1, err
  2001. }
  2002. defer resp.Body.Close()
  2003. body, err := ioutil.ReadAll(resp.Body)
  2004. if err != nil {
  2005. return nil, -1, err
  2006. }
  2007. if resp.StatusCode < 200 || resp.StatusCode >= 400 {
  2008. if len(body) == 0 {
  2009. return nil, resp.StatusCode, fmt.Errorf("Error: %s", http.StatusText(resp.StatusCode))
  2010. }
  2011. return nil, resp.StatusCode, fmt.Errorf("Error: %s", bytes.TrimSpace(body))
  2012. }
  2013. return body, resp.StatusCode, nil
  2014. }
  2015. func (cli *DockerCli) stream(method, path string, in io.Reader, out io.Writer, headers map[string][]string) error {
  2016. if (method == "POST" || method == "PUT") && in == nil {
  2017. in = bytes.NewReader([]byte{})
  2018. }
  2019. // fixme: refactor client to support redirect
  2020. re := regexp.MustCompile("/+")
  2021. path = re.ReplaceAllString(path, "/")
  2022. req, err := http.NewRequest(method, fmt.Sprintf("/v%g%s", APIVERSION, path), in)
  2023. if err != nil {
  2024. return err
  2025. }
  2026. req.Header.Set("User-Agent", "Docker-Client/"+VERSION)
  2027. req.Host = cli.addr
  2028. if method == "POST" {
  2029. req.Header.Set("Content-Type", "plain/text")
  2030. }
  2031. if headers != nil {
  2032. for k, v := range headers {
  2033. req.Header[k] = v
  2034. }
  2035. }
  2036. dial, err := net.Dial(cli.proto, cli.addr)
  2037. if err != nil {
  2038. if strings.Contains(err.Error(), "connection refused") {
  2039. return fmt.Errorf("Can't connect to docker daemon. Is 'docker -d' running on this host?")
  2040. }
  2041. return err
  2042. }
  2043. clientconn := httputil.NewClientConn(dial, nil)
  2044. resp, err := clientconn.Do(req)
  2045. defer clientconn.Close()
  2046. if err != nil {
  2047. if strings.Contains(err.Error(), "connection refused") {
  2048. return fmt.Errorf("Can't connect to docker daemon. Is 'docker -d' running on this host?")
  2049. }
  2050. return err
  2051. }
  2052. defer resp.Body.Close()
  2053. if resp.StatusCode < 200 || resp.StatusCode >= 400 {
  2054. body, err := ioutil.ReadAll(resp.Body)
  2055. if err != nil {
  2056. return err
  2057. }
  2058. if len(body) == 0 {
  2059. return fmt.Errorf("Error :%s", http.StatusText(resp.StatusCode))
  2060. }
  2061. return fmt.Errorf("Error: %s", bytes.TrimSpace(body))
  2062. }
  2063. if matchesContentType(resp.Header.Get("Content-Type"), "application/json") {
  2064. return utils.DisplayJSONMessagesStream(resp.Body, out, cli.terminalFd, cli.isTerminal)
  2065. }
  2066. if _, err := io.Copy(out, resp.Body); err != nil {
  2067. return err
  2068. }
  2069. return nil
  2070. }
  2071. func (cli *DockerCli) hijack(method, path string, setRawTerminal bool, in io.ReadCloser, stdout, stderr io.Writer, started chan io.Closer) error {
  2072. defer func() {
  2073. if started != nil {
  2074. close(started)
  2075. }
  2076. }()
  2077. // fixme: refactor client to support redirect
  2078. re := regexp.MustCompile("/+")
  2079. path = re.ReplaceAllString(path, "/")
  2080. req, err := http.NewRequest(method, fmt.Sprintf("/v%g%s", APIVERSION, path), nil)
  2081. if err != nil {
  2082. return err
  2083. }
  2084. req.Header.Set("User-Agent", "Docker-Client/"+VERSION)
  2085. req.Header.Set("Content-Type", "plain/text")
  2086. req.Host = cli.addr
  2087. dial, err := net.Dial(cli.proto, cli.addr)
  2088. if err != nil {
  2089. if strings.Contains(err.Error(), "connection refused") {
  2090. return fmt.Errorf("Can't connect to docker daemon. Is 'docker -d' running on this host?")
  2091. }
  2092. return err
  2093. }
  2094. clientconn := httputil.NewClientConn(dial, nil)
  2095. defer clientconn.Close()
  2096. // Server hijacks the connection, error 'connection closed' expected
  2097. clientconn.Do(req)
  2098. rwc, br := clientconn.Hijack()
  2099. defer rwc.Close()
  2100. if started != nil {
  2101. started <- rwc
  2102. }
  2103. var receiveStdout chan error
  2104. var oldState *term.State
  2105. if in != nil && setRawTerminal && cli.isTerminal && os.Getenv("NORAW") == "" {
  2106. oldState, err = term.SetRawTerminal(cli.terminalFd)
  2107. if err != nil {
  2108. return err
  2109. }
  2110. defer term.RestoreTerminal(cli.terminalFd, oldState)
  2111. }
  2112. if stdout != nil || stderr != nil {
  2113. receiveStdout = utils.Go(func() (err error) {
  2114. defer func() {
  2115. if in != nil {
  2116. if setRawTerminal && cli.isTerminal {
  2117. term.RestoreTerminal(cli.terminalFd, oldState)
  2118. }
  2119. in.Close()
  2120. }
  2121. }()
  2122. // When TTY is ON, use regular copy
  2123. if setRawTerminal {
  2124. _, err = io.Copy(stdout, br)
  2125. } else {
  2126. _, err = utils.StdCopy(stdout, stderr, br)
  2127. }
  2128. utils.Debugf("[hijack] End of stdout")
  2129. return err
  2130. })
  2131. }
  2132. sendStdin := utils.Go(func() error {
  2133. if in != nil {
  2134. io.Copy(rwc, in)
  2135. utils.Debugf("[hijack] End of stdin")
  2136. }
  2137. if tcpc, ok := rwc.(*net.TCPConn); ok {
  2138. if err := tcpc.CloseWrite(); err != nil {
  2139. utils.Errorf("Couldn't send EOF: %s\n", err)
  2140. }
  2141. } else if unixc, ok := rwc.(*net.UnixConn); ok {
  2142. if err := unixc.CloseWrite(); err != nil {
  2143. utils.Errorf("Couldn't send EOF: %s\n", err)
  2144. }
  2145. }
  2146. // Discard errors due to pipe interruption
  2147. return nil
  2148. })
  2149. if stdout != nil || stderr != nil {
  2150. if err := <-receiveStdout; err != nil {
  2151. utils.Errorf("Error receiveStdout: %s", err)
  2152. return err
  2153. }
  2154. }
  2155. if !cli.isTerminal {
  2156. if err := <-sendStdin; err != nil {
  2157. utils.Errorf("Error sendStdin: %s", err)
  2158. return err
  2159. }
  2160. }
  2161. return nil
  2162. }
  2163. func (cli *DockerCli) getTtySize() (int, int) {
  2164. if !cli.isTerminal {
  2165. return 0, 0
  2166. }
  2167. ws, err := term.GetWinsize(cli.terminalFd)
  2168. if err != nil {
  2169. utils.Errorf("Error getting size: %s", err)
  2170. if ws == nil {
  2171. return 0, 0
  2172. }
  2173. }
  2174. return int(ws.Height), int(ws.Width)
  2175. }
  2176. func (cli *DockerCli) resizeTty(id string) {
  2177. height, width := cli.getTtySize()
  2178. if height == 0 && width == 0 {
  2179. return
  2180. }
  2181. v := url.Values{}
  2182. v.Set("h", strconv.Itoa(height))
  2183. v.Set("w", strconv.Itoa(width))
  2184. if _, _, err := cli.call("POST", "/containers/"+id+"/resize?"+v.Encode(), nil); err != nil {
  2185. utils.Errorf("Error resize: %s", err)
  2186. }
  2187. }
  2188. func (cli *DockerCli) monitorTtySize(id string) error {
  2189. cli.resizeTty(id)
  2190. sigchan := make(chan os.Signal, 1)
  2191. signal.Notify(sigchan, syscall.SIGWINCH)
  2192. go func() {
  2193. for _ = range sigchan {
  2194. cli.resizeTty(id)
  2195. }
  2196. }()
  2197. return nil
  2198. }
  2199. func (cli *DockerCli) Subcmd(name, signature, description string) *flag.FlagSet {
  2200. flags := flag.NewFlagSet(name, flag.ContinueOnError)
  2201. flags.Usage = func() {
  2202. fmt.Fprintf(cli.err, "\nUsage: docker %s %s\n\n%s\n\n", name, signature, description)
  2203. flags.PrintDefaults()
  2204. os.Exit(2)
  2205. }
  2206. return flags
  2207. }
  2208. func (cli *DockerCli) LoadConfigFile() (err error) {
  2209. cli.configFile, err = auth.LoadConfig(os.Getenv("HOME"))
  2210. if err != nil {
  2211. fmt.Fprintf(cli.err, "WARNING: %s\n", err)
  2212. }
  2213. return err
  2214. }
  2215. func waitForExit(cli *DockerCli, containerId string) (int, error) {
  2216. body, _, err := cli.call("POST", "/containers/"+containerId+"/wait", nil)
  2217. if err != nil {
  2218. // If we can't connect, then the daemon probably died.
  2219. if err != ErrConnectionRefused {
  2220. return -1, err
  2221. }
  2222. return -1, nil
  2223. }
  2224. var out APIWait
  2225. if err := json.Unmarshal(body, &out); err != nil {
  2226. return -1, err
  2227. }
  2228. return out.StatusCode, nil
  2229. }
  2230. // getExitCode perform an inspect on the container. It returns
  2231. // the running state and the exit code.
  2232. func getExitCode(cli *DockerCli, containerId string) (bool, int, error) {
  2233. body, _, err := cli.call("GET", "/containers/"+containerId+"/json", nil)
  2234. if err != nil {
  2235. // If we can't connect, then the daemon probably died.
  2236. if err != ErrConnectionRefused {
  2237. return false, -1, err
  2238. }
  2239. return false, -1, nil
  2240. }
  2241. c := &Container{}
  2242. if err := json.Unmarshal(body, c); err != nil {
  2243. return false, -1, err
  2244. }
  2245. return c.State.IsRunning(), c.State.GetExitCode(), nil
  2246. }
  2247. func NewDockerCli(in io.ReadCloser, out, err io.Writer, proto, addr string) *DockerCli {
  2248. var (
  2249. isTerminal = false
  2250. terminalFd uintptr
  2251. )
  2252. if in != nil {
  2253. if file, ok := in.(*os.File); ok {
  2254. terminalFd = file.Fd()
  2255. isTerminal = term.IsTerminal(terminalFd)
  2256. }
  2257. }
  2258. if err == nil {
  2259. err = out
  2260. }
  2261. return &DockerCli{
  2262. proto: proto,
  2263. addr: addr,
  2264. in: in,
  2265. out: out,
  2266. err: err,
  2267. isTerminal: isTerminal,
  2268. terminalFd: terminalFd,
  2269. }
  2270. }
  2271. type DockerCli struct {
  2272. proto string
  2273. addr string
  2274. configFile *auth.ConfigFile
  2275. in io.ReadCloser
  2276. out io.Writer
  2277. err io.Writer
  2278. isTerminal bool
  2279. terminalFd uintptr
  2280. }