commands.go 67 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543
  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. if *flViz {
  994. body, _, err := cli.call("GET", "/images/json?all=1", nil)
  995. if err != nil {
  996. return err
  997. }
  998. var outs []APIImages
  999. err = json.Unmarshal(body, &outs)
  1000. if err != nil {
  1001. return err
  1002. }
  1003. fmt.Fprintf(cli.out, "digraph docker {\n")
  1004. for _, image := range outs {
  1005. if image.ParentId == "" {
  1006. fmt.Fprintf(cli.out, " base -> \"%s\" [style=invis]\n", utils.TruncateID(image.ID))
  1007. } else {
  1008. fmt.Fprintf(cli.out, " \"%s\" -> \"%s\"\n", utils.TruncateID(image.ParentId), utils.TruncateID(image.ID))
  1009. }
  1010. if image.RepoTags[0] != "<none>:<none>" {
  1011. 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"))
  1012. }
  1013. }
  1014. fmt.Fprintf(cli.out, " base [style=invisible]\n}\n")
  1015. } else if *flTree {
  1016. body, _, err := cli.call("GET", "/images/json?all=1", nil)
  1017. if err != nil {
  1018. return err
  1019. }
  1020. var outs []APIImages
  1021. if err := json.Unmarshal(body, &outs); err != nil {
  1022. return err
  1023. }
  1024. var (
  1025. startImageArg = cmd.Arg(0)
  1026. startImage APIImages
  1027. roots []APIImages
  1028. byParent = make(map[string][]APIImages)
  1029. )
  1030. for _, image := range outs {
  1031. if image.ParentId == "" {
  1032. roots = append(roots, image)
  1033. } else {
  1034. if children, exists := byParent[image.ParentId]; exists {
  1035. byParent[image.ParentId] = append(children, image)
  1036. } else {
  1037. byParent[image.ParentId] = []APIImages{image}
  1038. }
  1039. }
  1040. if startImageArg != "" {
  1041. if startImageArg == image.ID || startImageArg == utils.TruncateID(image.ID) {
  1042. startImage = image
  1043. }
  1044. for _, repotag := range image.RepoTags {
  1045. if repotag == startImageArg {
  1046. startImage = image
  1047. }
  1048. }
  1049. }
  1050. }
  1051. if startImageArg != "" {
  1052. WalkTree(cli, noTrunc, []APIImages{startImage}, byParent, "")
  1053. } else {
  1054. WalkTree(cli, noTrunc, roots, byParent, "")
  1055. }
  1056. } else {
  1057. v := url.Values{}
  1058. if cmd.NArg() == 1 {
  1059. v.Set("filter", cmd.Arg(0))
  1060. }
  1061. if *all {
  1062. v.Set("all", "1")
  1063. }
  1064. body, _, err := cli.call("GET", "/images/json?"+v.Encode(), nil)
  1065. if err != nil {
  1066. return err
  1067. }
  1068. var outs []APIImages
  1069. err = json.Unmarshal(body, &outs)
  1070. if err != nil {
  1071. return err
  1072. }
  1073. w := tabwriter.NewWriter(cli.out, 20, 1, 3, ' ', 0)
  1074. if !*quiet {
  1075. fmt.Fprintln(w, "REPOSITORY\tTAG\tIMAGE ID\tCREATED\tVIRTUAL SIZE")
  1076. }
  1077. for _, out := range outs {
  1078. for _, repotag := range out.RepoTags {
  1079. repo, tag := utils.ParseRepositoryTag(repotag)
  1080. if !*noTrunc {
  1081. out.ID = utils.TruncateID(out.ID)
  1082. }
  1083. if !*quiet {
  1084. 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))
  1085. } else {
  1086. fmt.Fprintln(w, out.ID)
  1087. }
  1088. }
  1089. }
  1090. if !*quiet {
  1091. w.Flush()
  1092. }
  1093. }
  1094. return nil
  1095. }
  1096. func WalkTree(cli *DockerCli, noTrunc *bool, images []APIImages, byParent map[string][]APIImages, prefix string) {
  1097. if len(images) > 1 {
  1098. length := len(images)
  1099. for index, image := range images {
  1100. if index+1 == length {
  1101. PrintTreeNode(cli, noTrunc, image, prefix+"└─")
  1102. if subimages, exists := byParent[image.ID]; exists {
  1103. WalkTree(cli, noTrunc, subimages, byParent, prefix+" ")
  1104. }
  1105. } else {
  1106. PrintTreeNode(cli, noTrunc, image, prefix+"|─")
  1107. if subimages, exists := byParent[image.ID]; exists {
  1108. WalkTree(cli, noTrunc, subimages, byParent, prefix+"| ")
  1109. }
  1110. }
  1111. }
  1112. } else {
  1113. for _, image := range images {
  1114. PrintTreeNode(cli, noTrunc, image, prefix+"└─")
  1115. if subimages, exists := byParent[image.ID]; exists {
  1116. WalkTree(cli, noTrunc, subimages, byParent, prefix+" ")
  1117. }
  1118. }
  1119. }
  1120. }
  1121. func PrintTreeNode(cli *DockerCli, noTrunc *bool, image APIImages, prefix string) {
  1122. var imageID string
  1123. if *noTrunc {
  1124. imageID = image.ID
  1125. } else {
  1126. imageID = utils.TruncateID(image.ID)
  1127. }
  1128. fmt.Fprintf(cli.out, "%s%s Size: %s (virtual %s)", prefix, imageID, utils.HumanSize(image.Size), utils.HumanSize(image.VirtualSize))
  1129. if image.RepoTags[0] != "<none>:<none>" {
  1130. fmt.Fprintf(cli.out, " Tags: %s\n", strings.Join(image.RepoTags, ", "))
  1131. } else {
  1132. fmt.Fprint(cli.out, "\n")
  1133. }
  1134. }
  1135. func displayablePorts(ports []APIPort) string {
  1136. result := []string{}
  1137. for _, port := range ports {
  1138. if port.IP == "" {
  1139. result = append(result, fmt.Sprintf("%d/%s", port.PublicPort, port.Type))
  1140. } else {
  1141. result = append(result, fmt.Sprintf("%s:%d->%d/%s", port.IP, port.PublicPort, port.PrivatePort, port.Type))
  1142. }
  1143. }
  1144. sort.Strings(result)
  1145. return strings.Join(result, ", ")
  1146. }
  1147. func (cli *DockerCli) CmdPs(args ...string) error {
  1148. cmd := cli.Subcmd("ps", "[OPTIONS]", "List containers")
  1149. quiet := cmd.Bool("q", false, "Only display numeric IDs")
  1150. size := cmd.Bool("s", false, "Display sizes")
  1151. all := cmd.Bool("a", false, "Show all containers. Only running containers are shown by default.")
  1152. noTrunc := cmd.Bool("notrunc", false, "Don't truncate output")
  1153. nLatest := cmd.Bool("l", false, "Show only the latest created container, include non-running ones.")
  1154. since := cmd.String("sinceId", "", "Show only containers created since Id, include non-running ones.")
  1155. before := cmd.String("beforeId", "", "Show only container created before Id, include non-running ones.")
  1156. last := cmd.Int("n", -1, "Show n last created containers, include non-running ones.")
  1157. if err := cmd.Parse(args); err != nil {
  1158. return nil
  1159. }
  1160. v := url.Values{}
  1161. if *last == -1 && *nLatest {
  1162. *last = 1
  1163. }
  1164. if *all {
  1165. v.Set("all", "1")
  1166. }
  1167. if *last != -1 {
  1168. v.Set("limit", strconv.Itoa(*last))
  1169. }
  1170. if *since != "" {
  1171. v.Set("since", *since)
  1172. }
  1173. if *before != "" {
  1174. v.Set("before", *before)
  1175. }
  1176. if *size {
  1177. v.Set("size", "1")
  1178. }
  1179. body, _, err := cli.call("GET", "/containers/json?"+v.Encode(), nil)
  1180. if err != nil {
  1181. return err
  1182. }
  1183. var outs []APIContainers
  1184. err = json.Unmarshal(body, &outs)
  1185. if err != nil {
  1186. return err
  1187. }
  1188. w := tabwriter.NewWriter(cli.out, 20, 1, 3, ' ', 0)
  1189. if !*quiet {
  1190. fmt.Fprint(w, "CONTAINER ID\tIMAGE\tCOMMAND\tCREATED\tSTATUS\tPORTS\tNAMES")
  1191. if *size {
  1192. fmt.Fprintln(w, "\tSIZE")
  1193. } else {
  1194. fmt.Fprint(w, "\n")
  1195. }
  1196. }
  1197. for _, out := range outs {
  1198. if !*noTrunc {
  1199. out.ID = utils.TruncateID(out.ID)
  1200. }
  1201. // Remove the leading / from the names
  1202. for i := 0; i < len(out.Names); i++ {
  1203. out.Names[i] = out.Names[i][1:]
  1204. }
  1205. if !*quiet {
  1206. if !*noTrunc {
  1207. out.Command = utils.Trunc(out.Command, 20)
  1208. }
  1209. 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, ","))
  1210. if *size {
  1211. if out.SizeRootFs > 0 {
  1212. fmt.Fprintf(w, "%s (virtual %s)\n", utils.HumanSize(out.SizeRw), utils.HumanSize(out.SizeRootFs))
  1213. } else {
  1214. fmt.Fprintf(w, "%s\n", utils.HumanSize(out.SizeRw))
  1215. }
  1216. } else {
  1217. fmt.Fprint(w, "\n")
  1218. }
  1219. } else {
  1220. fmt.Fprintln(w, out.ID)
  1221. }
  1222. }
  1223. if !*quiet {
  1224. w.Flush()
  1225. }
  1226. return nil
  1227. }
  1228. func (cli *DockerCli) CmdCommit(args ...string) error {
  1229. cmd := cli.Subcmd("commit", "[OPTIONS] CONTAINER [REPOSITORY[:TAG]]", "Create a new image from a container's changes")
  1230. flComment := cmd.String("m", "", "Commit message")
  1231. flAuthor := cmd.String("author", "", "Author (eg. \"John Hannibal Smith <hannibal@a-team.com>\"")
  1232. flConfig := cmd.String("run", "", "Config automatically applied when the image is run. "+`(ex: -run='{"Cmd": ["cat", "/world"], "PortSpecs": ["22"]}')`)
  1233. if err := cmd.Parse(args); err != nil {
  1234. return nil
  1235. }
  1236. var name, repository, tag string
  1237. if cmd.NArg() == 3 {
  1238. fmt.Fprintf(cli.err, "[DEPRECATED] The format 'CONTAINER [REPOSITORY [TAG]]' as been deprecated. Please use CONTAINER [REPOSITORY[:TAG]]\n")
  1239. name, repository, tag = cmd.Arg(0), cmd.Arg(1), cmd.Arg(2)
  1240. } else {
  1241. name = cmd.Arg(0)
  1242. repository, tag = utils.ParseRepositoryTag(cmd.Arg(1))
  1243. }
  1244. if name == "" {
  1245. cmd.Usage()
  1246. return nil
  1247. }
  1248. v := url.Values{}
  1249. v.Set("container", name)
  1250. v.Set("repo", repository)
  1251. v.Set("tag", tag)
  1252. v.Set("comment", *flComment)
  1253. v.Set("author", *flAuthor)
  1254. var config *Config
  1255. if *flConfig != "" {
  1256. config = &Config{}
  1257. if err := json.Unmarshal([]byte(*flConfig), config); err != nil {
  1258. return err
  1259. }
  1260. }
  1261. body, _, err := cli.call("POST", "/commit?"+v.Encode(), config)
  1262. if err != nil {
  1263. return err
  1264. }
  1265. apiID := &APIID{}
  1266. err = json.Unmarshal(body, apiID)
  1267. if err != nil {
  1268. return err
  1269. }
  1270. fmt.Fprintf(cli.out, "%s\n", apiID.ID)
  1271. return nil
  1272. }
  1273. func (cli *DockerCli) CmdEvents(args ...string) error {
  1274. cmd := cli.Subcmd("events", "[OPTIONS]", "Get real time events from the server")
  1275. since := cmd.String("since", "", "Show previously created events and then stream.")
  1276. if err := cmd.Parse(args); err != nil {
  1277. return nil
  1278. }
  1279. if cmd.NArg() != 0 {
  1280. cmd.Usage()
  1281. return nil
  1282. }
  1283. v := url.Values{}
  1284. if *since != "" {
  1285. loc := time.FixedZone(time.Now().Zone())
  1286. format := "2006-01-02 15:04:05 -0700 MST"
  1287. if len(*since) < len(format) {
  1288. format = format[:len(*since)]
  1289. }
  1290. if t, err := time.ParseInLocation(format, *since, loc); err == nil {
  1291. v.Set("since", strconv.FormatInt(t.Unix(), 10))
  1292. } else {
  1293. v.Set("since", *since)
  1294. }
  1295. }
  1296. if err := cli.stream("GET", "/events?"+v.Encode(), nil, cli.out, nil); err != nil {
  1297. return err
  1298. }
  1299. return nil
  1300. }
  1301. func (cli *DockerCli) CmdExport(args ...string) error {
  1302. cmd := cli.Subcmd("export", "CONTAINER", "Export the contents of a filesystem as a tar archive to STDOUT")
  1303. if err := cmd.Parse(args); err != nil {
  1304. return nil
  1305. }
  1306. if cmd.NArg() != 1 {
  1307. cmd.Usage()
  1308. return nil
  1309. }
  1310. if err := cli.stream("GET", "/containers/"+cmd.Arg(0)+"/export", nil, cli.out, nil); err != nil {
  1311. return err
  1312. }
  1313. return nil
  1314. }
  1315. func (cli *DockerCli) CmdDiff(args ...string) error {
  1316. cmd := cli.Subcmd("diff", "CONTAINER", "Inspect changes on a container's filesystem")
  1317. if err := cmd.Parse(args); err != nil {
  1318. return nil
  1319. }
  1320. if cmd.NArg() != 1 {
  1321. cmd.Usage()
  1322. return nil
  1323. }
  1324. body, _, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/changes", nil)
  1325. if err != nil {
  1326. return err
  1327. }
  1328. changes := []Change{}
  1329. err = json.Unmarshal(body, &changes)
  1330. if err != nil {
  1331. return err
  1332. }
  1333. for _, change := range changes {
  1334. fmt.Fprintf(cli.out, "%s\n", change.String())
  1335. }
  1336. return nil
  1337. }
  1338. func (cli *DockerCli) CmdLogs(args ...string) error {
  1339. cmd := cli.Subcmd("logs", "CONTAINER", "Fetch the logs of a container")
  1340. follow := cmd.Bool("f", false, "Follow log output")
  1341. if err := cmd.Parse(args); err != nil {
  1342. return nil
  1343. }
  1344. if cmd.NArg() != 1 {
  1345. cmd.Usage()
  1346. return nil
  1347. }
  1348. name := cmd.Arg(0)
  1349. body, _, err := cli.call("GET", "/containers/"+name+"/json", nil)
  1350. if err != nil {
  1351. return err
  1352. }
  1353. container := &Container{}
  1354. err = json.Unmarshal(body, container)
  1355. if err != nil {
  1356. return err
  1357. }
  1358. v := url.Values{}
  1359. v.Set("logs", "1")
  1360. v.Set("stdout", "1")
  1361. v.Set("stderr", "1")
  1362. if *follow && container.State.Running {
  1363. v.Set("stream", "1")
  1364. }
  1365. if err := cli.hijack("POST", "/containers/"+name+"/attach?"+v.Encode(), container.Config.Tty, nil, cli.out, cli.err, nil); err != nil {
  1366. return err
  1367. }
  1368. return nil
  1369. }
  1370. func (cli *DockerCli) CmdAttach(args ...string) error {
  1371. cmd := cli.Subcmd("attach", "[OPTIONS] CONTAINER", "Attach to a running container")
  1372. noStdin := cmd.Bool("nostdin", false, "Do not attach stdin")
  1373. proxy := cmd.Bool("sig-proxy", true, "Proxify all received signal to the process (even in non-tty mode)")
  1374. if err := cmd.Parse(args); err != nil {
  1375. return nil
  1376. }
  1377. if cmd.NArg() != 1 {
  1378. cmd.Usage()
  1379. return nil
  1380. }
  1381. name := cmd.Arg(0)
  1382. body, _, err := cli.call("GET", "/containers/"+name+"/json", nil)
  1383. if err != nil {
  1384. return err
  1385. }
  1386. container := &Container{}
  1387. err = json.Unmarshal(body, container)
  1388. if err != nil {
  1389. return err
  1390. }
  1391. if !container.State.IsRunning() {
  1392. return fmt.Errorf("Impossible to attach to a stopped container, start it first")
  1393. }
  1394. if container.Config.Tty && cli.isTerminal {
  1395. if err := cli.monitorTtySize(cmd.Arg(0)); err != nil {
  1396. utils.Debugf("Error monitoring TTY size: %s", err)
  1397. }
  1398. }
  1399. var in io.ReadCloser
  1400. v := url.Values{}
  1401. v.Set("stream", "1")
  1402. if !*noStdin && container.Config.OpenStdin {
  1403. v.Set("stdin", "1")
  1404. in = cli.in
  1405. }
  1406. v.Set("stdout", "1")
  1407. v.Set("stderr", "1")
  1408. if *proxy && !container.Config.Tty {
  1409. sigc := cli.forwardAllSignals(cmd.Arg(0))
  1410. defer utils.StopCatch(sigc)
  1411. }
  1412. if err := cli.hijack("POST", "/containers/"+cmd.Arg(0)+"/attach?"+v.Encode(), container.Config.Tty, in, cli.out, cli.err, nil); err != nil {
  1413. return err
  1414. }
  1415. _, status, err := getExitCode(cli, cmd.Arg(0))
  1416. if err != nil {
  1417. return err
  1418. }
  1419. if status != 0 {
  1420. return &utils.StatusError{StatusCode: status}
  1421. }
  1422. return nil
  1423. }
  1424. func (cli *DockerCli) CmdSearch(args ...string) error {
  1425. cmd := cli.Subcmd("search", "TERM", "Search the docker index for images")
  1426. noTrunc := cmd.Bool("notrunc", false, "Don't truncate output")
  1427. trusted := cmd.Bool("trusted", false, "Only show trusted builds")
  1428. stars := cmd.Int("stars", 0, "Only displays with at least xxx stars")
  1429. if err := cmd.Parse(args); err != nil {
  1430. return nil
  1431. }
  1432. if cmd.NArg() != 1 {
  1433. cmd.Usage()
  1434. return nil
  1435. }
  1436. v := url.Values{}
  1437. v.Set("term", cmd.Arg(0))
  1438. body, _, err := cli.call("GET", "/images/search?"+v.Encode(), nil)
  1439. if err != nil {
  1440. return err
  1441. }
  1442. outs := []registry.SearchResult{}
  1443. err = json.Unmarshal(body, &outs)
  1444. if err != nil {
  1445. return err
  1446. }
  1447. w := tabwriter.NewWriter(cli.out, 10, 1, 3, ' ', 0)
  1448. fmt.Fprintf(w, "NAME\tDESCRIPTION\tSTARS\tOFFICIAL\tTRUSTED\n")
  1449. for _, out := range outs {
  1450. if (*trusted && !out.IsTrusted) || (*stars > out.StarCount) {
  1451. continue
  1452. }
  1453. desc := strings.Replace(out.Description, "\n", " ", -1)
  1454. desc = strings.Replace(desc, "\r", " ", -1)
  1455. if !*noTrunc && len(desc) > 45 {
  1456. desc = utils.Trunc(desc, 42) + "..."
  1457. }
  1458. fmt.Fprintf(w, "%s\t%s\t%d\t", out.Name, desc, out.StarCount)
  1459. if out.IsOfficial {
  1460. fmt.Fprint(w, "[OK]")
  1461. }
  1462. fmt.Fprint(w, "\t")
  1463. if out.IsTrusted {
  1464. fmt.Fprint(w, "[OK]")
  1465. }
  1466. fmt.Fprint(w, "\n")
  1467. }
  1468. w.Flush()
  1469. return nil
  1470. }
  1471. // Ports type - Used to parse multiple -p flags
  1472. type ports []int
  1473. func (cli *DockerCli) CmdTag(args ...string) error {
  1474. cmd := cli.Subcmd("tag", "[OPTIONS] IMAGE REPOSITORY[:TAG]", "Tag an image into a repository")
  1475. force := cmd.Bool("f", false, "Force")
  1476. if err := cmd.Parse(args); err != nil {
  1477. return nil
  1478. }
  1479. if cmd.NArg() != 2 && cmd.NArg() != 3 {
  1480. cmd.Usage()
  1481. return nil
  1482. }
  1483. var repository, tag string
  1484. if cmd.NArg() == 3 {
  1485. fmt.Fprintf(cli.err, "[DEPRECATED] The format 'IMAGE [REPOSITORY [TAG]]' as been deprecated. Please use IMAGE [REPOSITORY[:TAG]]\n")
  1486. repository, tag = cmd.Arg(1), cmd.Arg(2)
  1487. } else {
  1488. repository, tag = utils.ParseRepositoryTag(cmd.Arg(1))
  1489. }
  1490. v := url.Values{}
  1491. v.Set("repo", repository)
  1492. v.Set("tag", tag)
  1493. if *force {
  1494. v.Set("force", "1")
  1495. }
  1496. if _, _, err := cli.call("POST", "/images/"+cmd.Arg(0)+"/tag?"+v.Encode(), nil); err != nil {
  1497. return err
  1498. }
  1499. return nil
  1500. }
  1501. //FIXME Only used in tests
  1502. func ParseRun(args []string, capabilities *Capabilities) (*Config, *HostConfig, *flag.FlagSet, error) {
  1503. cmd := flag.NewFlagSet("run", flag.ContinueOnError)
  1504. cmd.SetOutput(ioutil.Discard)
  1505. cmd.Usage = nil
  1506. return parseRun(cmd, args, capabilities)
  1507. }
  1508. func parseRun(cmd *flag.FlagSet, args []string, capabilities *Capabilities) (*Config, *HostConfig, *flag.FlagSet, error) {
  1509. var (
  1510. // FIXME: use utils.ListOpts for attach and volumes?
  1511. flAttach = NewListOpts(ValidateAttach)
  1512. flVolumes = NewListOpts(ValidatePath)
  1513. flLinks = NewListOpts(ValidateLink)
  1514. flEnv = NewListOpts(ValidateEnv)
  1515. flPublish ListOpts
  1516. flExpose ListOpts
  1517. flDns ListOpts
  1518. flVolumesFrom ListOpts
  1519. flLxcOpts ListOpts
  1520. flAutoRemove = cmd.Bool("rm", false, "Automatically remove the container when it exits (incompatible with -d)")
  1521. flDetach = cmd.Bool("d", false, "Detached mode: Run container in the background, print new container id")
  1522. flNetwork = cmd.Bool("n", true, "Enable networking for this container")
  1523. flPrivileged = cmd.Bool("privileged", false, "Give extended privileges to this container")
  1524. flPublishAll = cmd.Bool("P", false, "Publish all exposed ports to the host interfaces")
  1525. flStdin = cmd.Bool("i", false, "Keep stdin open even if not attached")
  1526. flTty = cmd.Bool("t", false, "Allocate a pseudo-tty")
  1527. flContainerIDFile = cmd.String("cidfile", "", "Write the container ID to the file")
  1528. flEntrypoint = cmd.String("entrypoint", "", "Overwrite the default entrypoint of the image")
  1529. flHostname = cmd.String("h", "", "Container host name")
  1530. flMemoryString = cmd.String("m", "", "Memory limit (format: <number><optional unit>, where unit = b, k, m or g)")
  1531. flUser = cmd.String("u", "", "Username or UID")
  1532. flWorkingDir = cmd.String("w", "", "Working directory inside the container")
  1533. flCpuShares = cmd.Int64("c", 0, "CPU shares (relative weight)")
  1534. // For documentation purpose
  1535. _ = cmd.Bool("sig-proxy", true, "Proxify all received signal to the process (even in non-tty mode)")
  1536. _ = cmd.String("name", "", "Assign a name to the container")
  1537. )
  1538. cmd.Var(&flAttach, "a", "Attach to stdin, stdout or stderr.")
  1539. cmd.Var(&flVolumes, "v", "Bind mount a volume (e.g. from the host: -v /host:/container, from docker: -v /container)")
  1540. cmd.Var(&flLinks, "link", "Add link to another container (name:alias)")
  1541. cmd.Var(&flEnv, "e", "Set environment variables")
  1542. 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))
  1543. cmd.Var(&flExpose, "expose", "Expose a port from the container without publishing it to your host")
  1544. cmd.Var(&flDns, "dns", "Set custom dns servers")
  1545. cmd.Var(&flVolumesFrom, "volumes-from", "Mount volumes from the specified container(s)")
  1546. cmd.Var(&flLxcOpts, "lxc-conf", "Add custom lxc options -lxc-conf=\"lxc.cgroup.cpuset.cpus = 0,1\"")
  1547. if err := cmd.Parse(args); err != nil {
  1548. return nil, nil, cmd, err
  1549. }
  1550. // Check if the kernel supports memory limit cgroup.
  1551. if capabilities != nil && *flMemoryString != "" && !capabilities.MemoryLimit {
  1552. *flMemoryString = ""
  1553. }
  1554. // Validate input params
  1555. if *flDetach && flAttach.Len() > 0 {
  1556. return nil, nil, cmd, ErrConflictAttachDetach
  1557. }
  1558. if *flWorkingDir != "" && !path.IsAbs(*flWorkingDir) {
  1559. return nil, nil, cmd, ErrInvalidWorikingDirectory
  1560. }
  1561. if *flDetach && *flAutoRemove {
  1562. return nil, nil, cmd, ErrConflictDetachAutoRemove
  1563. }
  1564. // If neither -d or -a are set, attach to everything by default
  1565. if flAttach.Len() == 0 && !*flDetach {
  1566. if !*flDetach {
  1567. flAttach.Set("stdout")
  1568. flAttach.Set("stderr")
  1569. if *flStdin {
  1570. flAttach.Set("stdin")
  1571. }
  1572. }
  1573. }
  1574. var flMemory int64
  1575. if *flMemoryString != "" {
  1576. parsedMemory, err := utils.RAMInBytes(*flMemoryString)
  1577. if err != nil {
  1578. return nil, nil, cmd, err
  1579. }
  1580. flMemory = parsedMemory
  1581. }
  1582. var binds []string
  1583. // add any bind targets to the list of container volumes
  1584. for bind := range flVolumes.GetMap() {
  1585. if arr := strings.Split(bind, ":"); len(arr) > 1 {
  1586. if arr[0] == "/" {
  1587. return nil, nil, cmd, fmt.Errorf("Invalid bind mount: source can't be '/'")
  1588. }
  1589. dstDir := arr[1]
  1590. flVolumes.Set(dstDir)
  1591. binds = append(binds, bind)
  1592. flVolumes.Delete(bind)
  1593. }
  1594. }
  1595. var (
  1596. parsedArgs = cmd.Args()
  1597. runCmd []string
  1598. entrypoint []string
  1599. image string
  1600. )
  1601. if len(parsedArgs) >= 1 {
  1602. image = cmd.Arg(0)
  1603. }
  1604. if len(parsedArgs) > 1 {
  1605. runCmd = parsedArgs[1:]
  1606. }
  1607. if *flEntrypoint != "" {
  1608. entrypoint = []string{*flEntrypoint}
  1609. }
  1610. lxcConf, err := parseLxcConfOpts(flLxcOpts)
  1611. if err != nil {
  1612. return nil, nil, cmd, err
  1613. }
  1614. var (
  1615. domainname string
  1616. hostname = *flHostname
  1617. parts = strings.SplitN(hostname, ".", 2)
  1618. )
  1619. if len(parts) > 1 {
  1620. hostname = parts[0]
  1621. domainname = parts[1]
  1622. }
  1623. ports, portBindings, err := parsePortSpecs(flPublish.GetAll())
  1624. if err != nil {
  1625. return nil, nil, cmd, err
  1626. }
  1627. // Merge in exposed ports to the map of published ports
  1628. for _, e := range flExpose.GetAll() {
  1629. if strings.Contains(e, ":") {
  1630. return nil, nil, cmd, fmt.Errorf("Invalid port format for -expose: %s", e)
  1631. }
  1632. p := NewPort(splitProtoPort(e))
  1633. if _, exists := ports[p]; !exists {
  1634. ports[p] = struct{}{}
  1635. }
  1636. }
  1637. config := &Config{
  1638. Hostname: hostname,
  1639. Domainname: domainname,
  1640. PortSpecs: nil, // Deprecated
  1641. ExposedPorts: ports,
  1642. User: *flUser,
  1643. Tty: *flTty,
  1644. NetworkDisabled: !*flNetwork,
  1645. OpenStdin: *flStdin,
  1646. Memory: flMemory,
  1647. CpuShares: *flCpuShares,
  1648. AttachStdin: flAttach.Get("stdin"),
  1649. AttachStdout: flAttach.Get("stdout"),
  1650. AttachStderr: flAttach.Get("stderr"),
  1651. Env: flEnv.GetAll(),
  1652. Cmd: runCmd,
  1653. Dns: flDns.GetAll(),
  1654. Image: image,
  1655. Volumes: flVolumes.GetMap(),
  1656. VolumesFrom: strings.Join(flVolumesFrom.GetAll(), ","),
  1657. Entrypoint: entrypoint,
  1658. WorkingDir: *flWorkingDir,
  1659. }
  1660. hostConfig := &HostConfig{
  1661. Binds: binds,
  1662. ContainerIDFile: *flContainerIDFile,
  1663. LxcConf: lxcConf,
  1664. Privileged: *flPrivileged,
  1665. PortBindings: portBindings,
  1666. Links: flLinks.GetAll(),
  1667. PublishAllPorts: *flPublishAll,
  1668. }
  1669. if capabilities != nil && flMemory > 0 && !capabilities.SwapLimit {
  1670. //fmt.Fprintf(stdout, "WARNING: Your kernel does not support swap limit capabilities. Limitation discarded.\n")
  1671. config.MemorySwap = -1
  1672. }
  1673. // When allocating stdin in attached mode, close stdin at client disconnect
  1674. if config.OpenStdin && config.AttachStdin {
  1675. config.StdinOnce = true
  1676. }
  1677. return config, hostConfig, cmd, nil
  1678. }
  1679. func (cli *DockerCli) CmdRun(args ...string) error {
  1680. config, hostConfig, cmd, err := parseRun(cli.Subcmd("run", "[OPTIONS] IMAGE [COMMAND] [ARG...]", "Run a command in a new container"), args, nil)
  1681. if err != nil {
  1682. return err
  1683. }
  1684. if config.Image == "" {
  1685. cmd.Usage()
  1686. return nil
  1687. }
  1688. // Retrieve relevant client-side config
  1689. var (
  1690. flName = cmd.Lookup("name")
  1691. flRm = cmd.Lookup("rm")
  1692. flSigProxy = cmd.Lookup("sig-proxy")
  1693. autoRemove, _ = strconv.ParseBool(flRm.Value.String())
  1694. sigProxy, _ = strconv.ParseBool(flSigProxy.Value.String())
  1695. )
  1696. // Disable sigProxy in case on TTY
  1697. if config.Tty {
  1698. sigProxy = false
  1699. }
  1700. var containerIDFile io.WriteCloser
  1701. if len(hostConfig.ContainerIDFile) > 0 {
  1702. if _, err := os.Stat(hostConfig.ContainerIDFile); err == nil {
  1703. return fmt.Errorf("cid file found, make sure the other container isn't running or delete %s", hostConfig.ContainerIDFile)
  1704. }
  1705. if containerIDFile, err = os.Create(hostConfig.ContainerIDFile); err != nil {
  1706. return fmt.Errorf("failed to create the container ID file: %s", err)
  1707. }
  1708. defer containerIDFile.Close()
  1709. }
  1710. containerValues := url.Values{}
  1711. if name := flName.Value.String(); name != "" {
  1712. containerValues.Set("name", name)
  1713. }
  1714. //create the container
  1715. body, statusCode, err := cli.call("POST", "/containers/create?"+containerValues.Encode(), config)
  1716. //if image not found try to pull it
  1717. if statusCode == 404 {
  1718. _, tag := utils.ParseRepositoryTag(config.Image)
  1719. if tag == "" {
  1720. tag = DEFAULTTAG
  1721. }
  1722. fmt.Fprintf(cli.err, "Unable to find image '%s' (tag: %s) locally\n", config.Image, tag)
  1723. v := url.Values{}
  1724. repos, tag := utils.ParseRepositoryTag(config.Image)
  1725. v.Set("fromImage", repos)
  1726. v.Set("tag", tag)
  1727. // Resolve the Repository name from fqn to endpoint + name
  1728. endpoint, _, err := registry.ResolveRepositoryName(repos)
  1729. if err != nil {
  1730. return err
  1731. }
  1732. // Load the auth config file, to be able to pull the image
  1733. cli.LoadConfigFile()
  1734. // Resolve the Auth config relevant for this server
  1735. authConfig := cli.configFile.ResolveAuthConfig(endpoint)
  1736. buf, err := json.Marshal(authConfig)
  1737. if err != nil {
  1738. return err
  1739. }
  1740. registryAuthHeader := []string{
  1741. base64.URLEncoding.EncodeToString(buf),
  1742. }
  1743. if err = cli.stream("POST", "/images/create?"+v.Encode(), nil, cli.err, map[string][]string{"X-Registry-Auth": registryAuthHeader}); err != nil {
  1744. return err
  1745. }
  1746. if body, _, err = cli.call("POST", "/containers/create?"+containerValues.Encode(), config); err != nil {
  1747. return err
  1748. }
  1749. } else if err != nil {
  1750. return err
  1751. }
  1752. var runResult APIRun
  1753. if err := json.Unmarshal(body, &runResult); err != nil {
  1754. return err
  1755. }
  1756. for _, warning := range runResult.Warnings {
  1757. fmt.Fprintf(cli.err, "WARNING: %s\n", warning)
  1758. }
  1759. if len(hostConfig.ContainerIDFile) > 0 {
  1760. if _, err = containerIDFile.Write([]byte(runResult.ID)); err != nil {
  1761. return fmt.Errorf("failed to write the container ID to the file: %s", err)
  1762. }
  1763. }
  1764. if sigProxy {
  1765. sigc := cli.forwardAllSignals(runResult.ID)
  1766. defer utils.StopCatch(sigc)
  1767. }
  1768. var (
  1769. waitDisplayId chan struct{}
  1770. errCh chan error
  1771. )
  1772. if !config.AttachStdout && !config.AttachStderr {
  1773. // Make this asynchrone in order to let the client write to stdin before having to read the ID
  1774. waitDisplayId = make(chan struct{})
  1775. go func() {
  1776. defer close(waitDisplayId)
  1777. fmt.Fprintf(cli.out, "%s\n", runResult.ID)
  1778. }()
  1779. }
  1780. // We need to instanciate the chan because the select needs it. It can
  1781. // be closed but can't be uninitialized.
  1782. hijacked := make(chan io.Closer)
  1783. // Block the return until the chan gets closed
  1784. defer func() {
  1785. utils.Debugf("End of CmdRun(), Waiting for hijack to finish.")
  1786. if _, ok := <-hijacked; ok {
  1787. utils.Errorf("Hijack did not finish (chan still open)")
  1788. }
  1789. }()
  1790. if config.AttachStdin || config.AttachStdout || config.AttachStderr {
  1791. var (
  1792. out, stderr io.Writer
  1793. in io.ReadCloser
  1794. v = url.Values{}
  1795. )
  1796. v.Set("stream", "1")
  1797. if config.AttachStdin {
  1798. v.Set("stdin", "1")
  1799. in = cli.in
  1800. }
  1801. if config.AttachStdout {
  1802. v.Set("stdout", "1")
  1803. out = cli.out
  1804. }
  1805. if config.AttachStderr {
  1806. v.Set("stderr", "1")
  1807. if config.Tty {
  1808. stderr = cli.out
  1809. } else {
  1810. stderr = cli.err
  1811. }
  1812. }
  1813. errCh = utils.Go(func() error {
  1814. return cli.hijack("POST", "/containers/"+runResult.ID+"/attach?"+v.Encode(), config.Tty, in, out, stderr, hijacked)
  1815. })
  1816. } else {
  1817. close(hijacked)
  1818. }
  1819. // Acknowledge the hijack before starting
  1820. select {
  1821. case closer := <-hijacked:
  1822. // Make sure that hijack gets closed when returning. (result
  1823. // in closing hijack chan and freeing server's goroutines.
  1824. if closer != nil {
  1825. defer closer.Close()
  1826. }
  1827. case err := <-errCh:
  1828. if err != nil {
  1829. utils.Debugf("Error hijack: %s", err)
  1830. return err
  1831. }
  1832. }
  1833. //start the container
  1834. if _, _, err = cli.call("POST", "/containers/"+runResult.ID+"/start", hostConfig); err != nil {
  1835. return err
  1836. }
  1837. if (config.AttachStdin || config.AttachStdout || config.AttachStderr) && config.Tty && cli.isTerminal {
  1838. if err := cli.monitorTtySize(runResult.ID); err != nil {
  1839. utils.Errorf("Error monitoring TTY size: %s\n", err)
  1840. }
  1841. }
  1842. if errCh != nil {
  1843. if err := <-errCh; err != nil {
  1844. utils.Debugf("Error hijack: %s", err)
  1845. return err
  1846. }
  1847. }
  1848. // Detached mode: wait for the id to be displayed and return.
  1849. if !config.AttachStdout && !config.AttachStderr {
  1850. // Detached mode
  1851. <-waitDisplayId
  1852. return nil
  1853. }
  1854. var status int
  1855. // Attached mode
  1856. if autoRemove {
  1857. // Autoremove: wait for the container to finish, retrieve
  1858. // the exit code and remove the container
  1859. if _, _, err := cli.call("POST", "/containers/"+runResult.ID+"/wait", nil); err != nil {
  1860. return err
  1861. }
  1862. if _, status, err = getExitCode(cli, runResult.ID); err != nil {
  1863. return err
  1864. }
  1865. if _, _, err := cli.call("DELETE", "/containers/"+runResult.ID, nil); err != nil {
  1866. return err
  1867. }
  1868. } else {
  1869. // No Autoremove: Simply retrieve the exit code
  1870. if _, status, err = getExitCode(cli, runResult.ID); err != nil {
  1871. return err
  1872. }
  1873. }
  1874. if status != 0 {
  1875. return &utils.StatusError{StatusCode: status}
  1876. }
  1877. return nil
  1878. }
  1879. func (cli *DockerCli) CmdCp(args ...string) error {
  1880. cmd := cli.Subcmd("cp", "CONTAINER:PATH HOSTPATH", "Copy files/folders from the PATH to the HOSTPATH")
  1881. if err := cmd.Parse(args); err != nil {
  1882. return nil
  1883. }
  1884. if cmd.NArg() != 2 {
  1885. cmd.Usage()
  1886. return nil
  1887. }
  1888. var copyData APICopy
  1889. info := strings.Split(cmd.Arg(0), ":")
  1890. if len(info) != 2 {
  1891. return fmt.Errorf("Error: Path not specified")
  1892. }
  1893. copyData.Resource = info[1]
  1894. copyData.HostPath = cmd.Arg(1)
  1895. data, statusCode, err := cli.call("POST", "/containers/"+info[0]+"/copy", copyData)
  1896. if err != nil {
  1897. return err
  1898. }
  1899. if statusCode == 200 {
  1900. r := bytes.NewReader(data)
  1901. if err := archive.Untar(r, copyData.HostPath, nil); err != nil {
  1902. return err
  1903. }
  1904. }
  1905. return nil
  1906. }
  1907. func (cli *DockerCli) CmdSave(args ...string) error {
  1908. cmd := cli.Subcmd("save", "IMAGE", "Save an image to a tar archive (streamed to stdout)")
  1909. if err := cmd.Parse(args); err != nil {
  1910. return err
  1911. }
  1912. if cmd.NArg() != 1 {
  1913. cmd.Usage()
  1914. return nil
  1915. }
  1916. image := cmd.Arg(0)
  1917. if err := cli.stream("GET", "/images/"+image+"/get", nil, cli.out, nil); err != nil {
  1918. return err
  1919. }
  1920. return nil
  1921. }
  1922. func (cli *DockerCli) CmdLoad(args ...string) error {
  1923. cmd := cli.Subcmd("load", "SOURCE", "Load an image from a tar archive")
  1924. if err := cmd.Parse(args); err != nil {
  1925. return err
  1926. }
  1927. if cmd.NArg() != 0 {
  1928. cmd.Usage()
  1929. return nil
  1930. }
  1931. if err := cli.stream("POST", "/images/load", cli.in, cli.out, nil); err != nil {
  1932. return err
  1933. }
  1934. return nil
  1935. }
  1936. func (cli *DockerCli) call(method, path string, data interface{}) ([]byte, int, error) {
  1937. var params io.Reader
  1938. if data != nil {
  1939. buf, err := json.Marshal(data)
  1940. if err != nil {
  1941. return nil, -1, err
  1942. }
  1943. params = bytes.NewBuffer(buf)
  1944. }
  1945. // fixme: refactor client to support redirect
  1946. re := regexp.MustCompile("/+")
  1947. path = re.ReplaceAllString(path, "/")
  1948. req, err := http.NewRequest(method, fmt.Sprintf("/v%g%s", APIVERSION, path), params)
  1949. if err != nil {
  1950. return nil, -1, err
  1951. }
  1952. req.Header.Set("User-Agent", "Docker-Client/"+VERSION)
  1953. req.Host = cli.addr
  1954. if data != nil {
  1955. req.Header.Set("Content-Type", "application/json")
  1956. } else if method == "POST" {
  1957. req.Header.Set("Content-Type", "plain/text")
  1958. }
  1959. dial, err := net.Dial(cli.proto, cli.addr)
  1960. if err != nil {
  1961. if strings.Contains(err.Error(), "connection refused") {
  1962. return nil, -1, ErrConnectionRefused
  1963. }
  1964. return nil, -1, err
  1965. }
  1966. clientconn := httputil.NewClientConn(dial, nil)
  1967. resp, err := clientconn.Do(req)
  1968. defer clientconn.Close()
  1969. if err != nil {
  1970. if strings.Contains(err.Error(), "connection refused") {
  1971. return nil, -1, ErrConnectionRefused
  1972. }
  1973. return nil, -1, err
  1974. }
  1975. defer resp.Body.Close()
  1976. body, err := ioutil.ReadAll(resp.Body)
  1977. if err != nil {
  1978. return nil, -1, err
  1979. }
  1980. if resp.StatusCode < 200 || resp.StatusCode >= 400 {
  1981. if len(body) == 0 {
  1982. return nil, resp.StatusCode, fmt.Errorf("Error: %s", http.StatusText(resp.StatusCode))
  1983. }
  1984. return nil, resp.StatusCode, fmt.Errorf("Error: %s", bytes.TrimSpace(body))
  1985. }
  1986. return body, resp.StatusCode, nil
  1987. }
  1988. func (cli *DockerCli) stream(method, path string, in io.Reader, out io.Writer, headers map[string][]string) error {
  1989. if (method == "POST" || method == "PUT") && in == nil {
  1990. in = bytes.NewReader([]byte{})
  1991. }
  1992. // fixme: refactor client to support redirect
  1993. re := regexp.MustCompile("/+")
  1994. path = re.ReplaceAllString(path, "/")
  1995. req, err := http.NewRequest(method, fmt.Sprintf("/v%g%s", APIVERSION, path), in)
  1996. if err != nil {
  1997. return err
  1998. }
  1999. req.Header.Set("User-Agent", "Docker-Client/"+VERSION)
  2000. req.Host = cli.addr
  2001. if method == "POST" {
  2002. req.Header.Set("Content-Type", "plain/text")
  2003. }
  2004. if headers != nil {
  2005. for k, v := range headers {
  2006. req.Header[k] = v
  2007. }
  2008. }
  2009. dial, err := net.Dial(cli.proto, cli.addr)
  2010. if err != nil {
  2011. if strings.Contains(err.Error(), "connection refused") {
  2012. return fmt.Errorf("Can't connect to docker daemon. Is 'docker -d' running on this host?")
  2013. }
  2014. return err
  2015. }
  2016. clientconn := httputil.NewClientConn(dial, nil)
  2017. resp, err := clientconn.Do(req)
  2018. defer clientconn.Close()
  2019. if err != nil {
  2020. if strings.Contains(err.Error(), "connection refused") {
  2021. return fmt.Errorf("Can't connect to docker daemon. Is 'docker -d' running on this host?")
  2022. }
  2023. return err
  2024. }
  2025. defer resp.Body.Close()
  2026. if resp.StatusCode < 200 || resp.StatusCode >= 400 {
  2027. body, err := ioutil.ReadAll(resp.Body)
  2028. if err != nil {
  2029. return err
  2030. }
  2031. if len(body) == 0 {
  2032. return fmt.Errorf("Error :%s", http.StatusText(resp.StatusCode))
  2033. }
  2034. return fmt.Errorf("Error: %s", bytes.TrimSpace(body))
  2035. }
  2036. if matchesContentType(resp.Header.Get("Content-Type"), "application/json") {
  2037. return utils.DisplayJSONMessagesStream(resp.Body, out, cli.terminalFd, cli.isTerminal)
  2038. }
  2039. if _, err := io.Copy(out, resp.Body); err != nil {
  2040. return err
  2041. }
  2042. return nil
  2043. }
  2044. func (cli *DockerCli) hijack(method, path string, setRawTerminal bool, in io.ReadCloser, stdout, stderr io.Writer, started chan io.Closer) error {
  2045. defer func() {
  2046. if started != nil {
  2047. close(started)
  2048. }
  2049. }()
  2050. // fixme: refactor client to support redirect
  2051. re := regexp.MustCompile("/+")
  2052. path = re.ReplaceAllString(path, "/")
  2053. req, err := http.NewRequest(method, fmt.Sprintf("/v%g%s", APIVERSION, path), nil)
  2054. if err != nil {
  2055. return err
  2056. }
  2057. req.Header.Set("User-Agent", "Docker-Client/"+VERSION)
  2058. req.Header.Set("Content-Type", "plain/text")
  2059. req.Host = cli.addr
  2060. dial, err := net.Dial(cli.proto, cli.addr)
  2061. if err != nil {
  2062. if strings.Contains(err.Error(), "connection refused") {
  2063. return fmt.Errorf("Can't connect to docker daemon. Is 'docker -d' running on this host?")
  2064. }
  2065. return err
  2066. }
  2067. clientconn := httputil.NewClientConn(dial, nil)
  2068. defer clientconn.Close()
  2069. // Server hijacks the connection, error 'connection closed' expected
  2070. clientconn.Do(req)
  2071. rwc, br := clientconn.Hijack()
  2072. defer rwc.Close()
  2073. if started != nil {
  2074. started <- rwc
  2075. }
  2076. var receiveStdout chan error
  2077. var oldState *term.State
  2078. if in != nil && setRawTerminal && cli.isTerminal && os.Getenv("NORAW") == "" {
  2079. oldState, err = term.SetRawTerminal(cli.terminalFd)
  2080. if err != nil {
  2081. return err
  2082. }
  2083. defer term.RestoreTerminal(cli.terminalFd, oldState)
  2084. }
  2085. if stdout != nil || stderr != nil {
  2086. receiveStdout = utils.Go(func() (err error) {
  2087. defer func() {
  2088. if in != nil {
  2089. if setRawTerminal && cli.isTerminal {
  2090. term.RestoreTerminal(cli.terminalFd, oldState)
  2091. }
  2092. in.Close()
  2093. }
  2094. }()
  2095. // When TTY is ON, use regular copy
  2096. if setRawTerminal {
  2097. _, err = io.Copy(stdout, br)
  2098. } else {
  2099. _, err = utils.StdCopy(stdout, stderr, br)
  2100. }
  2101. utils.Debugf("[hijack] End of stdout")
  2102. return err
  2103. })
  2104. }
  2105. sendStdin := utils.Go(func() error {
  2106. if in != nil {
  2107. io.Copy(rwc, in)
  2108. utils.Debugf("[hijack] End of stdin")
  2109. }
  2110. if tcpc, ok := rwc.(*net.TCPConn); ok {
  2111. if err := tcpc.CloseWrite(); err != nil {
  2112. utils.Errorf("Couldn't send EOF: %s\n", err)
  2113. }
  2114. } else if unixc, ok := rwc.(*net.UnixConn); ok {
  2115. if err := unixc.CloseWrite(); err != nil {
  2116. utils.Errorf("Couldn't send EOF: %s\n", err)
  2117. }
  2118. }
  2119. // Discard errors due to pipe interruption
  2120. return nil
  2121. })
  2122. if stdout != nil || stderr != nil {
  2123. if err := <-receiveStdout; err != nil {
  2124. utils.Errorf("Error receiveStdout: %s", err)
  2125. return err
  2126. }
  2127. }
  2128. if !cli.isTerminal {
  2129. if err := <-sendStdin; err != nil {
  2130. utils.Errorf("Error sendStdin: %s", err)
  2131. return err
  2132. }
  2133. }
  2134. return nil
  2135. }
  2136. func (cli *DockerCli) getTtySize() (int, int) {
  2137. if !cli.isTerminal {
  2138. return 0, 0
  2139. }
  2140. ws, err := term.GetWinsize(cli.terminalFd)
  2141. if err != nil {
  2142. utils.Errorf("Error getting size: %s", err)
  2143. if ws == nil {
  2144. return 0, 0
  2145. }
  2146. }
  2147. return int(ws.Height), int(ws.Width)
  2148. }
  2149. func (cli *DockerCli) resizeTty(id string) {
  2150. height, width := cli.getTtySize()
  2151. if height == 0 && width == 0 {
  2152. return
  2153. }
  2154. v := url.Values{}
  2155. v.Set("h", strconv.Itoa(height))
  2156. v.Set("w", strconv.Itoa(width))
  2157. if _, _, err := cli.call("POST", "/containers/"+id+"/resize?"+v.Encode(), nil); err != nil {
  2158. utils.Errorf("Error resize: %s", err)
  2159. }
  2160. }
  2161. func (cli *DockerCli) monitorTtySize(id string) error {
  2162. cli.resizeTty(id)
  2163. sigchan := make(chan os.Signal, 1)
  2164. signal.Notify(sigchan, syscall.SIGWINCH)
  2165. go func() {
  2166. for _ = range sigchan {
  2167. cli.resizeTty(id)
  2168. }
  2169. }()
  2170. return nil
  2171. }
  2172. func (cli *DockerCli) Subcmd(name, signature, description string) *flag.FlagSet {
  2173. flags := flag.NewFlagSet(name, flag.ContinueOnError)
  2174. flags.Usage = func() {
  2175. fmt.Fprintf(cli.err, "\nUsage: docker %s %s\n\n%s\n\n", name, signature, description)
  2176. flags.PrintDefaults()
  2177. os.Exit(2)
  2178. }
  2179. return flags
  2180. }
  2181. func (cli *DockerCli) LoadConfigFile() (err error) {
  2182. cli.configFile, err = auth.LoadConfig(os.Getenv("HOME"))
  2183. if err != nil {
  2184. fmt.Fprintf(cli.err, "WARNING: %s\n", err)
  2185. }
  2186. return err
  2187. }
  2188. func waitForExit(cli *DockerCli, containerId string) (int, error) {
  2189. body, _, err := cli.call("POST", "/containers/"+containerId+"/wait", nil)
  2190. if err != nil {
  2191. // If we can't connect, then the daemon probably died.
  2192. if err != ErrConnectionRefused {
  2193. return -1, err
  2194. }
  2195. return -1, nil
  2196. }
  2197. var out APIWait
  2198. if err := json.Unmarshal(body, &out); err != nil {
  2199. return -1, err
  2200. }
  2201. return out.StatusCode, nil
  2202. }
  2203. // getExitCode perform an inspect on the container. It returns
  2204. // the running state and the exit code.
  2205. func getExitCode(cli *DockerCli, containerId string) (bool, int, error) {
  2206. body, _, err := cli.call("GET", "/containers/"+containerId+"/json", nil)
  2207. if err != nil {
  2208. // If we can't connect, then the daemon probably died.
  2209. if err != ErrConnectionRefused {
  2210. return false, -1, err
  2211. }
  2212. return false, -1, nil
  2213. }
  2214. c := &Container{}
  2215. if err := json.Unmarshal(body, c); err != nil {
  2216. return false, -1, err
  2217. }
  2218. return c.State.IsRunning(), c.State.GetExitCode(), nil
  2219. }
  2220. func NewDockerCli(in io.ReadCloser, out, err io.Writer, proto, addr string) *DockerCli {
  2221. var (
  2222. isTerminal = false
  2223. terminalFd uintptr
  2224. )
  2225. if in != nil {
  2226. if file, ok := in.(*os.File); ok {
  2227. terminalFd = file.Fd()
  2228. isTerminal = term.IsTerminal(terminalFd)
  2229. }
  2230. }
  2231. if err == nil {
  2232. err = out
  2233. }
  2234. return &DockerCli{
  2235. proto: proto,
  2236. addr: addr,
  2237. in: in,
  2238. out: out,
  2239. err: err,
  2240. isTerminal: isTerminal,
  2241. terminalFd: terminalFd,
  2242. }
  2243. }
  2244. type DockerCli struct {
  2245. proto string
  2246. addr string
  2247. configFile *auth.ConfigFile
  2248. in io.ReadCloser
  2249. out io.Writer
  2250. err io.Writer
  2251. isTerminal bool
  2252. terminalFd uintptr
  2253. }