commands.go 67 KB

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