commands.go 68 KB

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