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