client.go 67 KB

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