commands.go 66 KB

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