commands.go 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959
  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/auth"
  12. "github.com/dotcloud/docker/registry"
  13. "github.com/dotcloud/docker/term"
  14. "github.com/dotcloud/docker/utils"
  15. "io"
  16. "io/ioutil"
  17. "net"
  18. "net/http"
  19. "net/http/httputil"
  20. "net/url"
  21. "os"
  22. "os/signal"
  23. "path/filepath"
  24. "reflect"
  25. "runtime"
  26. "sort"
  27. "strconv"
  28. "strings"
  29. "syscall"
  30. "text/tabwriter"
  31. "time"
  32. )
  33. var (
  34. GITCOMMIT string
  35. VERSION string
  36. )
  37. var (
  38. ErrConnectionRefused = errors.New("Can't connect to docker daemon. Is 'docker -d' running on this host?")
  39. )
  40. func (cli *DockerCli) getMethod(name string) (reflect.Method, bool) {
  41. methodName := "Cmd" + strings.ToUpper(name[:1]) + strings.ToLower(name[1:])
  42. return reflect.TypeOf(cli).MethodByName(methodName)
  43. }
  44. func ParseCommands(proto, addr string, args ...string) error {
  45. cli := NewDockerCli(os.Stdin, os.Stdout, os.Stderr, proto, addr)
  46. if len(args) > 0 {
  47. method, exists := cli.getMethod(args[0])
  48. if !exists {
  49. fmt.Println("Error: Command not found:", args[0])
  50. return cli.CmdHelp(args[1:]...)
  51. }
  52. ret := method.Func.CallSlice([]reflect.Value{
  53. reflect.ValueOf(cli),
  54. reflect.ValueOf(args[1:]),
  55. })[0].Interface()
  56. if ret == nil {
  57. return nil
  58. }
  59. return ret.(error)
  60. }
  61. return cli.CmdHelp(args...)
  62. }
  63. func (cli *DockerCli) CmdHelp(args ...string) error {
  64. if len(args) > 0 {
  65. method, exists := cli.getMethod(args[0])
  66. if !exists {
  67. fmt.Fprintf(cli.err, "Error: Command not found: %s\n", args[0])
  68. } else {
  69. method.Func.CallSlice([]reflect.Value{
  70. reflect.ValueOf(cli),
  71. reflect.ValueOf([]string{"--help"}),
  72. })[0].Interface()
  73. return nil
  74. }
  75. }
  76. 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)
  77. for _, command := range [][]string{
  78. {"attach", "Attach to a running container"},
  79. {"build", "Build a container from a Dockerfile"},
  80. {"commit", "Create a new image from a container's changes"},
  81. {"cp", "Copy files/folders from the containers filesystem to the host path"},
  82. {"diff", "Inspect changes on a container's filesystem"},
  83. {"events", "Get real time events from the server"},
  84. {"export", "Stream the contents of a container as a tar archive"},
  85. {"history", "Show the history of an image"},
  86. {"images", "List images"},
  87. {"import", "Create a new filesystem image from the contents of a tarball"},
  88. {"info", "Display system-wide information"},
  89. {"insert", "Insert a file in an image"},
  90. {"inspect", "Return low-level information on a container"},
  91. {"kill", "Kill a running container"},
  92. {"login", "Register or Login to the docker registry server"},
  93. {"logs", "Fetch the logs of a container"},
  94. {"port", "Lookup the public-facing port which is NAT-ed to PRIVATE_PORT"},
  95. {"top", "Lookup the running processes of a container"},
  96. {"ps", "List containers"},
  97. {"pull", "Pull an image or a repository from the docker registry server"},
  98. {"push", "Push an image or a repository to the docker registry server"},
  99. {"restart", "Restart a running container"},
  100. {"rm", "Remove one or more containers"},
  101. {"rmi", "Remove one or more images"},
  102. {"run", "Run a command in a new container"},
  103. {"search", "Search for an image in the docker index"},
  104. {"start", "Start a stopped container"},
  105. {"stop", "Stop a running container"},
  106. {"tag", "Tag an image into a repository"},
  107. {"version", "Show the docker version information"},
  108. {"wait", "Block until a container stops, then print its exit code"},
  109. } {
  110. help += fmt.Sprintf(" %-10.10s%s\n", command[0], command[1])
  111. }
  112. fmt.Fprintf(cli.err, "%s\n", help)
  113. return nil
  114. }
  115. func (cli *DockerCli) CmdInsert(args ...string) error {
  116. cmd := Subcmd("insert", "IMAGE URL PATH", "Insert a file from URL in the IMAGE at PATH")
  117. if err := cmd.Parse(args); err != nil {
  118. return nil
  119. }
  120. if cmd.NArg() != 3 {
  121. cmd.Usage()
  122. return nil
  123. }
  124. v := url.Values{}
  125. v.Set("url", cmd.Arg(1))
  126. v.Set("path", cmd.Arg(2))
  127. if err := cli.stream("POST", "/images/"+cmd.Arg(0)+"/insert?"+v.Encode(), nil, cli.out, nil); err != nil {
  128. return err
  129. }
  130. return nil
  131. }
  132. // mkBuildContext returns an archive of an empty context with the contents
  133. // of `dockerfile` at the path ./Dockerfile
  134. func mkBuildContext(dockerfile string, files [][2]string) (Archive, error) {
  135. buf := new(bytes.Buffer)
  136. tw := tar.NewWriter(buf)
  137. files = append(files, [2]string{"Dockerfile", dockerfile})
  138. for _, file := range files {
  139. name, content := file[0], file[1]
  140. hdr := &tar.Header{
  141. Name: name,
  142. Size: int64(len(content)),
  143. }
  144. if err := tw.WriteHeader(hdr); err != nil {
  145. return nil, err
  146. }
  147. if _, err := tw.Write([]byte(content)); err != nil {
  148. return nil, err
  149. }
  150. }
  151. if err := tw.Close(); err != nil {
  152. return nil, err
  153. }
  154. return buf, nil
  155. }
  156. func (cli *DockerCli) CmdBuild(args ...string) error {
  157. cmd := Subcmd("build", "[OPTIONS] PATH | URL | -", "Build a new container image from the source code at PATH")
  158. tag := cmd.String("t", "", "Repository name (and optionally a tag) to be applied to the resulting image in case of success")
  159. suppressOutput := cmd.Bool("q", false, "Suppress verbose build output")
  160. noCache := cmd.Bool("no-cache", false, "Do not use cache when building the image")
  161. rm := cmd.Bool("rm", false, "Remove intermediate containers after a successful build")
  162. if err := cmd.Parse(args); err != nil {
  163. return nil
  164. }
  165. if cmd.NArg() != 1 {
  166. cmd.Usage()
  167. return nil
  168. }
  169. var (
  170. context Archive
  171. isRemote bool
  172. err error
  173. )
  174. if cmd.Arg(0) == "-" {
  175. // As a special case, 'docker build -' will build from an empty context with the
  176. // contents of stdin as a Dockerfile
  177. dockerfile, err := ioutil.ReadAll(cli.in)
  178. if err != nil {
  179. return err
  180. }
  181. context, err = mkBuildContext(string(dockerfile), nil)
  182. } else if utils.IsURL(cmd.Arg(0)) || utils.IsGIT(cmd.Arg(0)) {
  183. isRemote = true
  184. } else {
  185. if _, err := os.Stat(cmd.Arg(0)); err != nil {
  186. return err
  187. }
  188. context, err = Tar(cmd.Arg(0), Uncompressed)
  189. }
  190. var body io.Reader
  191. // Setup an upload progress bar
  192. // FIXME: ProgressReader shouldn't be this annoying to use
  193. if context != nil {
  194. sf := utils.NewStreamFormatter(false)
  195. body = utils.ProgressReader(ioutil.NopCloser(context), 0, cli.err, sf.FormatProgress("", "Uploading context", "%v bytes%0.0s%0.0s"), sf, true)
  196. }
  197. // Upload the build context
  198. v := &url.Values{}
  199. v.Set("t", *tag)
  200. if *suppressOutput {
  201. v.Set("q", "1")
  202. }
  203. if isRemote {
  204. v.Set("remote", cmd.Arg(0))
  205. }
  206. if *noCache {
  207. v.Set("nocache", "1")
  208. }
  209. if *rm {
  210. v.Set("rm", "1")
  211. }
  212. req, err := http.NewRequest("POST", fmt.Sprintf("/v%g/build?%s", APIVERSION, v.Encode()), body)
  213. if err != nil {
  214. return err
  215. }
  216. if context != nil {
  217. req.Header.Set("Content-Type", "application/tar")
  218. }
  219. dial, err := net.Dial(cli.proto, cli.addr)
  220. if err != nil {
  221. return err
  222. }
  223. clientconn := httputil.NewClientConn(dial, nil)
  224. resp, err := clientconn.Do(req)
  225. defer clientconn.Close()
  226. if err != nil {
  227. return err
  228. }
  229. defer resp.Body.Close()
  230. // Check for errors
  231. if resp.StatusCode < 200 || resp.StatusCode >= 400 {
  232. body, err := ioutil.ReadAll(resp.Body)
  233. if err != nil {
  234. return err
  235. }
  236. if len(body) == 0 {
  237. return fmt.Errorf("Error: %s", http.StatusText(resp.StatusCode))
  238. }
  239. return fmt.Errorf("Error: %s", body)
  240. }
  241. // Output the result
  242. if _, err := io.Copy(cli.out, resp.Body); err != nil {
  243. return err
  244. }
  245. return nil
  246. }
  247. // 'docker login': login / register a user to registry service.
  248. func (cli *DockerCli) CmdLogin(args ...string) error {
  249. cmd := Subcmd("login", "[OPTIONS] [SERVER]", "Register or Login to a docker registry server, if no server is specified \""+auth.IndexServerAddress()+"\" is the default.")
  250. var username, password, email string
  251. cmd.StringVar(&username, "u", "", "username")
  252. cmd.StringVar(&password, "p", "", "password")
  253. cmd.StringVar(&email, "e", "", "email")
  254. err := cmd.Parse(args)
  255. if err != nil {
  256. return nil
  257. }
  258. serverAddress := auth.IndexServerAddress()
  259. if len(cmd.Args()) > 0 {
  260. serverAddress, err = registry.ExpandAndVerifyRegistryUrl(cmd.Arg(0))
  261. if err != nil {
  262. return err
  263. }
  264. fmt.Fprintf(cli.out, "Login against server at %s\n", serverAddress)
  265. }
  266. promptDefault := func(prompt string, configDefault string) {
  267. if configDefault == "" {
  268. fmt.Fprintf(cli.out, "%s: ", prompt)
  269. } else {
  270. fmt.Fprintf(cli.out, "%s (%s): ", prompt, configDefault)
  271. }
  272. }
  273. readInput := func(in io.Reader, out io.Writer) string {
  274. reader := bufio.NewReader(in)
  275. line, _, err := reader.ReadLine()
  276. if err != nil {
  277. fmt.Fprintln(out, err.Error())
  278. os.Exit(1)
  279. }
  280. return string(line)
  281. }
  282. cli.LoadConfigFile()
  283. authconfig, ok := cli.configFile.Configs[serverAddress]
  284. if !ok {
  285. authconfig = auth.AuthConfig{}
  286. }
  287. if username == "" {
  288. promptDefault("Username", authconfig.Username)
  289. username = readInput(cli.in, cli.out)
  290. if username == "" {
  291. username = authconfig.Username
  292. }
  293. }
  294. if username != authconfig.Username {
  295. if password == "" {
  296. oldState, _ := term.SaveState(cli.terminalFd)
  297. fmt.Fprintf(cli.out, "Password: ")
  298. term.DisableEcho(cli.terminalFd, oldState)
  299. password = readInput(cli.in, cli.out)
  300. fmt.Fprint(cli.out, "\n")
  301. term.RestoreTerminal(cli.terminalFd, oldState)
  302. if password == "" {
  303. return fmt.Errorf("Error : Password Required")
  304. }
  305. }
  306. if email == "" {
  307. promptDefault("Email", authconfig.Email)
  308. email = readInput(cli.in, cli.out)
  309. if email == "" {
  310. email = authconfig.Email
  311. }
  312. }
  313. } else {
  314. password = authconfig.Password
  315. email = authconfig.Email
  316. }
  317. authconfig.Username = username
  318. authconfig.Password = password
  319. authconfig.Email = email
  320. authconfig.ServerAddress = serverAddress
  321. cli.configFile.Configs[serverAddress] = authconfig
  322. body, statusCode, err := cli.call("POST", "/auth", cli.configFile.Configs[serverAddress])
  323. if statusCode == 401 {
  324. delete(cli.configFile.Configs, serverAddress)
  325. auth.SaveConfig(cli.configFile)
  326. return err
  327. }
  328. if err != nil {
  329. return err
  330. }
  331. var out2 APIAuth
  332. err = json.Unmarshal(body, &out2)
  333. if err != nil {
  334. cli.configFile, _ = auth.LoadConfig(os.Getenv("HOME"))
  335. return err
  336. }
  337. auth.SaveConfig(cli.configFile)
  338. if out2.Status != "" {
  339. fmt.Fprintf(cli.out, "%s\n", out2.Status)
  340. }
  341. return nil
  342. }
  343. // 'docker wait': block until a container stops
  344. func (cli *DockerCli) CmdWait(args ...string) error {
  345. cmd := Subcmd("wait", "CONTAINER [CONTAINER...]", "Block until a container stops, then print its exit code.")
  346. if err := cmd.Parse(args); err != nil {
  347. return nil
  348. }
  349. if cmd.NArg() < 1 {
  350. cmd.Usage()
  351. return nil
  352. }
  353. for _, name := range cmd.Args() {
  354. status, err := waitForExit(cli, name)
  355. if err != nil {
  356. fmt.Fprintf(cli.err, "%s", err)
  357. } else {
  358. fmt.Fprintf(cli.out, "%d\n", status)
  359. }
  360. }
  361. return nil
  362. }
  363. // 'docker version': show version information
  364. func (cli *DockerCli) CmdVersion(args ...string) error {
  365. cmd := Subcmd("version", "", "Show the docker version information.")
  366. if err := cmd.Parse(args); err != nil {
  367. return nil
  368. }
  369. if cmd.NArg() > 0 {
  370. cmd.Usage()
  371. return nil
  372. }
  373. if VERSION != "" {
  374. fmt.Fprintf(cli.out, "Client version: %s\n", VERSION)
  375. }
  376. fmt.Fprintf(cli.out, "Go version (client): %s\n", runtime.Version())
  377. if GITCOMMIT != "" {
  378. fmt.Fprintf(cli.out, "Git commit (client): %s\n", GITCOMMIT)
  379. }
  380. body, _, err := cli.call("GET", "/version", nil)
  381. if err != nil {
  382. return err
  383. }
  384. var out APIVersion
  385. err = json.Unmarshal(body, &out)
  386. if err != nil {
  387. utils.Errorf("Error unmarshal: body: %s, err: %s\n", body, err)
  388. return err
  389. }
  390. if out.Version != "" {
  391. fmt.Fprintf(cli.out, "Server version: %s\n", out.Version)
  392. }
  393. if out.GitCommit != "" {
  394. fmt.Fprintf(cli.out, "Git commit (server): %s\n", out.GitCommit)
  395. }
  396. if out.GoVersion != "" {
  397. fmt.Fprintf(cli.out, "Go version (server): %s\n", out.GoVersion)
  398. }
  399. release := utils.GetReleaseVersion()
  400. if release != "" {
  401. fmt.Fprintf(cli.out, "Last stable version: %s", release)
  402. if (VERSION != "" || out.Version != "") && (strings.Trim(VERSION, "-dev") != release || strings.Trim(out.Version, "-dev") != release) {
  403. fmt.Fprintf(cli.out, ", please update docker")
  404. }
  405. fmt.Fprintf(cli.out, "\n")
  406. }
  407. return nil
  408. }
  409. // 'docker info': display system-wide information.
  410. func (cli *DockerCli) CmdInfo(args ...string) error {
  411. cmd := Subcmd("info", "", "Display system-wide information")
  412. if err := cmd.Parse(args); err != nil {
  413. return nil
  414. }
  415. if cmd.NArg() > 0 {
  416. cmd.Usage()
  417. return nil
  418. }
  419. body, _, err := cli.call("GET", "/info", nil)
  420. if err != nil {
  421. return err
  422. }
  423. var out APIInfo
  424. if err := json.Unmarshal(body, &out); err != nil {
  425. return err
  426. }
  427. fmt.Fprintf(cli.out, "Containers: %d\n", out.Containers)
  428. fmt.Fprintf(cli.out, "Images: %d\n", out.Images)
  429. if out.Debug || os.Getenv("DEBUG") != "" {
  430. fmt.Fprintf(cli.out, "Debug mode (server): %v\n", out.Debug)
  431. fmt.Fprintf(cli.out, "Debug mode (client): %v\n", os.Getenv("DEBUG") != "")
  432. fmt.Fprintf(cli.out, "Fds: %d\n", out.NFd)
  433. fmt.Fprintf(cli.out, "Goroutines: %d\n", out.NGoroutines)
  434. fmt.Fprintf(cli.out, "LXC Version: %s\n", out.LXCVersion)
  435. fmt.Fprintf(cli.out, "EventsListeners: %d\n", out.NEventsListener)
  436. fmt.Fprintf(cli.out, "Kernel Version: %s\n", out.KernelVersion)
  437. }
  438. if len(out.IndexServerAddress) != 0 {
  439. cli.LoadConfigFile()
  440. u := cli.configFile.Configs[out.IndexServerAddress].Username
  441. if len(u) > 0 {
  442. fmt.Fprintf(cli.out, "Username: %v\n", u)
  443. fmt.Fprintf(cli.out, "Registry: %v\n", out.IndexServerAddress)
  444. }
  445. }
  446. if !out.MemoryLimit {
  447. fmt.Fprintf(cli.err, "WARNING: No memory limit support\n")
  448. }
  449. if !out.SwapLimit {
  450. fmt.Fprintf(cli.err, "WARNING: No swap limit support\n")
  451. }
  452. if !out.IPv4Forwarding {
  453. fmt.Fprintf(cli.err, "WARNING: IPv4 forwarding is disabled.\n")
  454. }
  455. return nil
  456. }
  457. func (cli *DockerCli) CmdStop(args ...string) error {
  458. cmd := Subcmd("stop", "[OPTIONS] CONTAINER [CONTAINER...]", "Stop a running container")
  459. nSeconds := cmd.Int("t", 10, "Number of seconds to wait for the container to stop before killing it.")
  460. if err := cmd.Parse(args); err != nil {
  461. return nil
  462. }
  463. if cmd.NArg() < 1 {
  464. cmd.Usage()
  465. return nil
  466. }
  467. v := url.Values{}
  468. v.Set("t", strconv.Itoa(*nSeconds))
  469. for _, name := range cmd.Args() {
  470. _, _, err := cli.call("POST", "/containers/"+name+"/stop?"+v.Encode(), nil)
  471. if err != nil {
  472. fmt.Fprintf(cli.err, "%s\n", err)
  473. } else {
  474. fmt.Fprintf(cli.out, "%s\n", name)
  475. }
  476. }
  477. return nil
  478. }
  479. func (cli *DockerCli) CmdRestart(args ...string) error {
  480. cmd := Subcmd("restart", "[OPTIONS] CONTAINER [CONTAINER...]", "Restart a running container")
  481. nSeconds := cmd.Int("t", 10, "Number of seconds to try to stop for before killing the container. Once killed it will then be restarted. Default=10")
  482. if err := cmd.Parse(args); err != nil {
  483. return nil
  484. }
  485. if cmd.NArg() < 1 {
  486. cmd.Usage()
  487. return nil
  488. }
  489. v := url.Values{}
  490. v.Set("t", strconv.Itoa(*nSeconds))
  491. for _, name := range cmd.Args() {
  492. _, _, err := cli.call("POST", "/containers/"+name+"/restart?"+v.Encode(), nil)
  493. if err != nil {
  494. fmt.Fprintf(cli.err, "%s\n", err)
  495. } else {
  496. fmt.Fprintf(cli.out, "%s\n", name)
  497. }
  498. }
  499. return nil
  500. }
  501. func (cli *DockerCli) CmdStart(args ...string) error {
  502. cmd := Subcmd("start", "CONTAINER [CONTAINER...]", "Restart a stopped container")
  503. if err := cmd.Parse(args); err != nil {
  504. return nil
  505. }
  506. if cmd.NArg() < 1 {
  507. cmd.Usage()
  508. return nil
  509. }
  510. var encounteredError error
  511. for _, name := range args {
  512. _, _, err := cli.call("POST", "/containers/"+name+"/start", nil)
  513. if err != nil {
  514. fmt.Fprintf(cli.err, "%s\n", err)
  515. encounteredError = fmt.Errorf("Error: failed to start one or more containers")
  516. } else {
  517. fmt.Fprintf(cli.out, "%s\n", name)
  518. }
  519. }
  520. return encounteredError
  521. }
  522. func (cli *DockerCli) CmdInspect(args ...string) error {
  523. cmd := Subcmd("inspect", "CONTAINER|IMAGE [CONTAINER|IMAGE...]", "Return low-level information on a container/image")
  524. if err := cmd.Parse(args); err != nil {
  525. return nil
  526. }
  527. if cmd.NArg() < 1 {
  528. cmd.Usage()
  529. return nil
  530. }
  531. fmt.Fprintf(cli.out, "[")
  532. for i, name := range args {
  533. if i > 0 {
  534. fmt.Fprintf(cli.out, ",")
  535. }
  536. obj, _, err := cli.call("GET", "/containers/"+name+"/json", nil)
  537. if err != nil {
  538. obj, _, err = cli.call("GET", "/images/"+name+"/json", nil)
  539. if err != nil {
  540. fmt.Fprintf(cli.err, "No such image or container: %s\n", name)
  541. continue
  542. }
  543. }
  544. indented := new(bytes.Buffer)
  545. if err = json.Indent(indented, obj, "", " "); err != nil {
  546. fmt.Fprintf(cli.err, "%s\n", err)
  547. continue
  548. }
  549. if _, err := io.Copy(cli.out, indented); err != nil {
  550. fmt.Fprintf(cli.err, "%s\n", err)
  551. }
  552. }
  553. fmt.Fprintf(cli.out, "]")
  554. return nil
  555. }
  556. func (cli *DockerCli) CmdTop(args ...string) error {
  557. cmd := Subcmd("top", "CONTAINER", "Lookup the running processes of a container")
  558. if err := cmd.Parse(args); err != nil {
  559. return nil
  560. }
  561. if cmd.NArg() == 0 {
  562. cmd.Usage()
  563. return nil
  564. }
  565. val := url.Values{}
  566. if cmd.NArg() > 1 {
  567. val.Set("ps_args", strings.Join(cmd.Args()[1:], " "))
  568. }
  569. body, _, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/top?"+val.Encode(), nil)
  570. if err != nil {
  571. return err
  572. }
  573. procs := APITop{}
  574. err = json.Unmarshal(body, &procs)
  575. if err != nil {
  576. return err
  577. }
  578. w := tabwriter.NewWriter(cli.out, 20, 1, 3, ' ', 0)
  579. fmt.Fprintln(w, strings.Join(procs.Titles, "\t"))
  580. for _, proc := range procs.Processes {
  581. fmt.Fprintln(w, strings.Join(proc, "\t"))
  582. }
  583. w.Flush()
  584. return nil
  585. }
  586. func (cli *DockerCli) CmdPort(args ...string) error {
  587. cmd := Subcmd("port", "CONTAINER PRIVATE_PORT", "Lookup the public-facing port which is NAT-ed to PRIVATE_PORT")
  588. if err := cmd.Parse(args); err != nil {
  589. return nil
  590. }
  591. if cmd.NArg() != 2 {
  592. cmd.Usage()
  593. return nil
  594. }
  595. port := cmd.Arg(1)
  596. proto := "Tcp"
  597. parts := strings.SplitN(port, "/", 2)
  598. if len(parts) == 2 && len(parts[1]) != 0 {
  599. port = parts[0]
  600. proto = strings.ToUpper(parts[1][:1]) + strings.ToLower(parts[1][1:])
  601. }
  602. body, _, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/json", nil)
  603. if err != nil {
  604. return err
  605. }
  606. var out Container
  607. err = json.Unmarshal(body, &out)
  608. if err != nil {
  609. return err
  610. }
  611. if frontend, exists := out.NetworkSettings.PortMapping[proto][port]; exists {
  612. fmt.Fprintf(cli.out, "%s\n", frontend)
  613. } else {
  614. return fmt.Errorf("Error: No private port '%s' allocated on %s", cmd.Arg(1), cmd.Arg(0))
  615. }
  616. return nil
  617. }
  618. // 'docker rmi IMAGE' removes all images with the name IMAGE
  619. func (cli *DockerCli) CmdRmi(args ...string) error {
  620. cmd := Subcmd("rmi", "IMAGE [IMAGE...]", "Remove one or more images")
  621. if err := cmd.Parse(args); err != nil {
  622. return nil
  623. }
  624. if cmd.NArg() < 1 {
  625. cmd.Usage()
  626. return nil
  627. }
  628. for _, name := range cmd.Args() {
  629. body, _, err := cli.call("DELETE", "/images/"+name, nil)
  630. if err != nil {
  631. fmt.Fprintf(cli.err, "%s", err)
  632. } else {
  633. var outs []APIRmi
  634. err = json.Unmarshal(body, &outs)
  635. if err != nil {
  636. return err
  637. }
  638. for _, out := range outs {
  639. if out.Deleted != "" {
  640. fmt.Fprintf(cli.out, "Deleted: %s\n", out.Deleted)
  641. } else {
  642. fmt.Fprintf(cli.out, "Untagged: %s\n", out.Untagged)
  643. }
  644. }
  645. }
  646. }
  647. return nil
  648. }
  649. func (cli *DockerCli) CmdHistory(args ...string) error {
  650. cmd := Subcmd("history", "IMAGE", "Show the history of an image")
  651. if err := cmd.Parse(args); err != nil {
  652. return nil
  653. }
  654. if cmd.NArg() != 1 {
  655. cmd.Usage()
  656. return nil
  657. }
  658. body, _, err := cli.call("GET", "/images/"+cmd.Arg(0)+"/history", nil)
  659. if err != nil {
  660. return err
  661. }
  662. var outs []APIHistory
  663. err = json.Unmarshal(body, &outs)
  664. if err != nil {
  665. return err
  666. }
  667. w := tabwriter.NewWriter(cli.out, 20, 1, 3, ' ', 0)
  668. fmt.Fprintln(w, "ID\tCREATED\tCREATED BY")
  669. for _, out := range outs {
  670. if out.Tags != nil {
  671. out.ID = out.Tags[0]
  672. }
  673. fmt.Fprintf(w, "%s \t%s ago\t%s\n", out.ID, utils.HumanDuration(time.Now().Sub(time.Unix(out.Created, 0))), out.CreatedBy)
  674. }
  675. w.Flush()
  676. return nil
  677. }
  678. func (cli *DockerCli) CmdRm(args ...string) error {
  679. cmd := Subcmd("rm", "[OPTIONS] CONTAINER [CONTAINER...]", "Remove one or more containers")
  680. v := cmd.Bool("v", false, "Remove the volumes associated to the container")
  681. if err := cmd.Parse(args); err != nil {
  682. return nil
  683. }
  684. if cmd.NArg() < 1 {
  685. cmd.Usage()
  686. return nil
  687. }
  688. val := url.Values{}
  689. if *v {
  690. val.Set("v", "1")
  691. }
  692. for _, name := range cmd.Args() {
  693. _, _, err := cli.call("DELETE", "/containers/"+name+"?"+val.Encode(), nil)
  694. if err != nil {
  695. fmt.Fprintf(cli.err, "%s\n", err)
  696. } else {
  697. fmt.Fprintf(cli.out, "%s\n", name)
  698. }
  699. }
  700. return nil
  701. }
  702. // 'docker kill NAME' kills a running container
  703. func (cli *DockerCli) CmdKill(args ...string) error {
  704. cmd := Subcmd("kill", "CONTAINER [CONTAINER...]", "Kill a running container")
  705. if err := cmd.Parse(args); err != nil {
  706. return nil
  707. }
  708. if cmd.NArg() < 1 {
  709. cmd.Usage()
  710. return nil
  711. }
  712. for _, name := range args {
  713. _, _, err := cli.call("POST", "/containers/"+name+"/kill", nil)
  714. if err != nil {
  715. fmt.Fprintf(cli.err, "%s\n", err)
  716. } else {
  717. fmt.Fprintf(cli.out, "%s\n", name)
  718. }
  719. }
  720. return nil
  721. }
  722. func (cli *DockerCli) CmdImport(args ...string) error {
  723. cmd := Subcmd("import", "URL|- [REPOSITORY [TAG]]", "Create a new filesystem image from the contents of a tarball(.tar, .tar.gz, .tgz, .bzip, .tar.xz, .txz).")
  724. if err := cmd.Parse(args); err != nil {
  725. return nil
  726. }
  727. if cmd.NArg() < 1 {
  728. cmd.Usage()
  729. return nil
  730. }
  731. src, repository, tag := cmd.Arg(0), cmd.Arg(1), cmd.Arg(2)
  732. v := url.Values{}
  733. v.Set("repo", repository)
  734. v.Set("tag", tag)
  735. v.Set("fromSrc", src)
  736. var in io.Reader
  737. if src == "-" {
  738. in = cli.in
  739. }
  740. return cli.stream("POST", "/images/create?"+v.Encode(), in, cli.out, nil)
  741. }
  742. func (cli *DockerCli) CmdPush(args ...string) error {
  743. cmd := Subcmd("push", "NAME", "Push an image or a repository to the registry")
  744. if err := cmd.Parse(args); err != nil {
  745. return nil
  746. }
  747. name := cmd.Arg(0)
  748. if name == "" {
  749. cmd.Usage()
  750. return nil
  751. }
  752. cli.LoadConfigFile()
  753. // Resolve the Repository name from fqn to endpoint + name
  754. endpoint, _, err := registry.ResolveRepositoryName(name)
  755. if err != nil {
  756. return err
  757. }
  758. // Resolve the Auth config relevant for this server
  759. authConfig := cli.configFile.ResolveAuthConfig(endpoint)
  760. // If we're not using a custom registry, we know the restrictions
  761. // applied to repository names and can warn the user in advance.
  762. // Custom repositories can have different rules, and we must also
  763. // allow pushing by image ID.
  764. if len(strings.SplitN(name, "/", 2)) == 1 {
  765. username := cli.configFile.Configs[auth.IndexServerAddress()].Username
  766. if username == "" {
  767. username = "<user>"
  768. }
  769. return fmt.Errorf("Impossible to push a \"root\" repository. Please rename your repository in <user>/<repo> (ex: %s/%s)", username, name)
  770. }
  771. v := url.Values{}
  772. push := func(authConfig auth.AuthConfig) error {
  773. buf, err := json.Marshal(authConfig)
  774. if err != nil {
  775. return err
  776. }
  777. registryAuthHeader := []string{
  778. base64.URLEncoding.EncodeToString(buf),
  779. }
  780. return cli.stream("POST", "/images/"+name+"/push?"+v.Encode(), nil, cli.out, map[string][]string{
  781. "X-Registry-Auth": registryAuthHeader,
  782. })
  783. }
  784. if err := push(authConfig); err != nil {
  785. if err.Error() == registry.ErrLoginRequired.Error() {
  786. fmt.Fprintln(cli.out, "\nPlease login prior to push:")
  787. if err := cli.CmdLogin(endpoint); err != nil {
  788. return err
  789. }
  790. authConfig := cli.configFile.ResolveAuthConfig(endpoint)
  791. return push(authConfig)
  792. }
  793. return err
  794. }
  795. return nil
  796. }
  797. func (cli *DockerCli) CmdPull(args ...string) error {
  798. cmd := Subcmd("pull", "NAME", "Pull an image or a repository from the registry")
  799. tag := cmd.String("t", "", "Download tagged image in repository")
  800. if err := cmd.Parse(args); err != nil {
  801. return nil
  802. }
  803. if cmd.NArg() != 1 {
  804. cmd.Usage()
  805. return nil
  806. }
  807. remote, parsedTag := utils.ParseRepositoryTag(cmd.Arg(0))
  808. if *tag == "" {
  809. *tag = parsedTag
  810. }
  811. // Resolve the Repository name from fqn to endpoint + name
  812. endpoint, _, err := registry.ResolveRepositoryName(remote)
  813. if err != nil {
  814. return err
  815. }
  816. cli.LoadConfigFile()
  817. // Resolve the Auth config relevant for this server
  818. authConfig := cli.configFile.ResolveAuthConfig(endpoint)
  819. v := url.Values{}
  820. v.Set("fromImage", remote)
  821. v.Set("tag", *tag)
  822. pull := func(authConfig auth.AuthConfig) error {
  823. buf, err := json.Marshal(authConfig)
  824. if err != nil {
  825. return err
  826. }
  827. registryAuthHeader := []string{
  828. base64.URLEncoding.EncodeToString(buf),
  829. }
  830. return cli.stream("POST", "/images/create?"+v.Encode(), nil, cli.out, map[string][]string{
  831. "X-Registry-Auth": registryAuthHeader,
  832. })
  833. }
  834. if err := pull(authConfig); err != nil {
  835. if err.Error() == registry.ErrLoginRequired.Error() {
  836. fmt.Fprintln(cli.out, "\nPlease login prior to push:")
  837. if err := cli.CmdLogin(endpoint); err != nil {
  838. return err
  839. }
  840. authConfig := cli.configFile.ResolveAuthConfig(endpoint)
  841. return pull(authConfig)
  842. }
  843. return err
  844. }
  845. return nil
  846. }
  847. func (cli *DockerCli) CmdImages(args ...string) error {
  848. cmd := Subcmd("images", "[OPTIONS] [NAME]", "List images")
  849. quiet := cmd.Bool("q", false, "only show numeric IDs")
  850. all := cmd.Bool("a", false, "show all images")
  851. noTrunc := cmd.Bool("notrunc", false, "Don't truncate output")
  852. flViz := cmd.Bool("viz", false, "output graph in graphviz format")
  853. if err := cmd.Parse(args); err != nil {
  854. return nil
  855. }
  856. if cmd.NArg() > 1 {
  857. cmd.Usage()
  858. return nil
  859. }
  860. if *flViz {
  861. body, _, err := cli.call("GET", "/images/viz", false)
  862. if err != nil {
  863. return err
  864. }
  865. fmt.Fprintf(cli.out, "%s", body)
  866. } else {
  867. v := url.Values{}
  868. if cmd.NArg() == 1 {
  869. v.Set("filter", cmd.Arg(0))
  870. }
  871. if *all {
  872. v.Set("all", "1")
  873. }
  874. body, _, err := cli.call("GET", "/images/json?"+v.Encode(), nil)
  875. if err != nil {
  876. return err
  877. }
  878. var outs []APIImages
  879. err = json.Unmarshal(body, &outs)
  880. if err != nil {
  881. return err
  882. }
  883. w := tabwriter.NewWriter(cli.out, 20, 1, 3, ' ', 0)
  884. if !*quiet {
  885. fmt.Fprintln(w, "REPOSITORY\tTAG\tID\tCREATED\tSIZE")
  886. }
  887. for _, out := range outs {
  888. if out.Repository == "" {
  889. out.Repository = "<none>"
  890. }
  891. if out.Tag == "" {
  892. out.Tag = "<none>"
  893. }
  894. if !*quiet {
  895. fmt.Fprintf(w, "%s\t%s\t", out.Repository, out.Tag)
  896. if *noTrunc {
  897. fmt.Fprintf(w, "%s\t", out.ID)
  898. } else {
  899. fmt.Fprintf(w, "%s\t", utils.TruncateID(out.ID))
  900. }
  901. fmt.Fprintf(w, "%s ago\t", utils.HumanDuration(time.Now().Sub(time.Unix(out.Created, 0))))
  902. if out.VirtualSize > 0 {
  903. fmt.Fprintf(w, "%s (virtual %s)\n", utils.HumanSize(out.Size), utils.HumanSize(out.VirtualSize))
  904. } else {
  905. fmt.Fprintf(w, "%s\n", utils.HumanSize(out.Size))
  906. }
  907. } else {
  908. if *noTrunc {
  909. fmt.Fprintln(w, out.ID)
  910. } else {
  911. fmt.Fprintln(w, utils.TruncateID(out.ID))
  912. }
  913. }
  914. }
  915. if !*quiet {
  916. w.Flush()
  917. }
  918. }
  919. return nil
  920. }
  921. func displayablePorts(ports []APIPort) string {
  922. result := []string{}
  923. for _, port := range ports {
  924. if port.Type == "tcp" {
  925. result = append(result, fmt.Sprintf("%d->%d", port.PublicPort, port.PrivatePort))
  926. } else {
  927. result = append(result, fmt.Sprintf("%d->%d/%s", port.PublicPort, port.PrivatePort, port.Type))
  928. }
  929. }
  930. sort.Strings(result)
  931. return strings.Join(result, ", ")
  932. }
  933. func (cli *DockerCli) CmdPs(args ...string) error {
  934. cmd := Subcmd("ps", "[OPTIONS]", "List containers")
  935. quiet := cmd.Bool("q", false, "Only display numeric IDs")
  936. size := cmd.Bool("s", false, "Display sizes")
  937. all := cmd.Bool("a", false, "Show all containers. Only running containers are shown by default.")
  938. noTrunc := cmd.Bool("notrunc", false, "Don't truncate output")
  939. nLatest := cmd.Bool("l", false, "Show only the latest created container, include non-running ones.")
  940. since := cmd.String("sinceId", "", "Show only containers created since Id, include non-running ones.")
  941. before := cmd.String("beforeId", "", "Show only container created before Id, include non-running ones.")
  942. last := cmd.Int("n", -1, "Show n last created containers, include non-running ones.")
  943. if err := cmd.Parse(args); err != nil {
  944. return nil
  945. }
  946. v := url.Values{}
  947. if *last == -1 && *nLatest {
  948. *last = 1
  949. }
  950. if *all {
  951. v.Set("all", "1")
  952. }
  953. if *last != -1 {
  954. v.Set("limit", strconv.Itoa(*last))
  955. }
  956. if *since != "" {
  957. v.Set("since", *since)
  958. }
  959. if *before != "" {
  960. v.Set("before", *before)
  961. }
  962. if *size {
  963. v.Set("size", "1")
  964. }
  965. body, _, err := cli.call("GET", "/containers/json?"+v.Encode(), nil)
  966. if err != nil {
  967. return err
  968. }
  969. var outs []APIContainers
  970. err = json.Unmarshal(body, &outs)
  971. if err != nil {
  972. return err
  973. }
  974. w := tabwriter.NewWriter(cli.out, 20, 1, 3, ' ', 0)
  975. if !*quiet {
  976. fmt.Fprint(w, "ID\tIMAGE\tCOMMAND\tCREATED\tSTATUS\tPORTS")
  977. if *size {
  978. fmt.Fprintln(w, "\tSIZE")
  979. } else {
  980. fmt.Fprint(w, "\n")
  981. }
  982. }
  983. for _, out := range outs {
  984. if !*quiet {
  985. if *noTrunc {
  986. fmt.Fprintf(w, "%s\t%s\t%s\t%s ago\t%s\t%s\t", out.ID, out.Image, out.Command, utils.HumanDuration(time.Now().Sub(time.Unix(out.Created, 0))), out.Status, displayablePorts(out.Ports))
  987. } else {
  988. fmt.Fprintf(w, "%s\t%s\t%s\t%s ago\t%s\t%s\t", utils.TruncateID(out.ID), out.Image, utils.Trunc(out.Command, 20), utils.HumanDuration(time.Now().Sub(time.Unix(out.Created, 0))), out.Status, displayablePorts(out.Ports))
  989. }
  990. if *size {
  991. if out.SizeRootFs > 0 {
  992. fmt.Fprintf(w, "%s (virtual %s)\n", utils.HumanSize(out.SizeRw), utils.HumanSize(out.SizeRootFs))
  993. } else {
  994. fmt.Fprintf(w, "%s\n", utils.HumanSize(out.SizeRw))
  995. }
  996. } else {
  997. fmt.Fprint(w, "\n")
  998. }
  999. } else {
  1000. if *noTrunc {
  1001. fmt.Fprintln(w, out.ID)
  1002. } else {
  1003. fmt.Fprintln(w, utils.TruncateID(out.ID))
  1004. }
  1005. }
  1006. }
  1007. if !*quiet {
  1008. w.Flush()
  1009. }
  1010. return nil
  1011. }
  1012. func (cli *DockerCli) CmdCommit(args ...string) error {
  1013. cmd := Subcmd("commit", "[OPTIONS] CONTAINER [REPOSITORY [TAG]]", "Create a new image from a container's changes")
  1014. flComment := cmd.String("m", "", "Commit message")
  1015. flAuthor := cmd.String("author", "", "Author (eg. \"John Hannibal Smith <hannibal@a-team.com>\"")
  1016. flConfig := cmd.String("run", "", "Config automatically applied when the image is run. "+`(ex: {"Cmd": ["cat", "/world"], "PortSpecs": ["22"]}')`)
  1017. if err := cmd.Parse(args); err != nil {
  1018. return nil
  1019. }
  1020. name, repository, tag := cmd.Arg(0), cmd.Arg(1), cmd.Arg(2)
  1021. if name == "" {
  1022. cmd.Usage()
  1023. return nil
  1024. }
  1025. v := url.Values{}
  1026. v.Set("container", name)
  1027. v.Set("repo", repository)
  1028. v.Set("tag", tag)
  1029. v.Set("comment", *flComment)
  1030. v.Set("author", *flAuthor)
  1031. var config *Config
  1032. if *flConfig != "" {
  1033. config = &Config{}
  1034. if err := json.Unmarshal([]byte(*flConfig), config); err != nil {
  1035. return err
  1036. }
  1037. }
  1038. body, _, err := cli.call("POST", "/commit?"+v.Encode(), config)
  1039. if err != nil {
  1040. return err
  1041. }
  1042. apiID := &APIID{}
  1043. err = json.Unmarshal(body, apiID)
  1044. if err != nil {
  1045. return err
  1046. }
  1047. fmt.Fprintf(cli.out, "%s\n", apiID.ID)
  1048. return nil
  1049. }
  1050. func (cli *DockerCli) CmdEvents(args ...string) error {
  1051. cmd := Subcmd("events", "[OPTIONS]", "Get real time events from the server")
  1052. since := cmd.String("since", "", "Show events previously created (used for polling).")
  1053. if err := cmd.Parse(args); err != nil {
  1054. return nil
  1055. }
  1056. if cmd.NArg() != 0 {
  1057. cmd.Usage()
  1058. return nil
  1059. }
  1060. v := url.Values{}
  1061. if *since != "" {
  1062. v.Set("since", *since)
  1063. }
  1064. if err := cli.stream("GET", "/events?"+v.Encode(), nil, cli.out, nil); err != nil {
  1065. return err
  1066. }
  1067. return nil
  1068. }
  1069. func (cli *DockerCli) CmdExport(args ...string) error {
  1070. cmd := Subcmd("export", "CONTAINER", "Export the contents of a filesystem as a tar archive")
  1071. if err := cmd.Parse(args); err != nil {
  1072. return nil
  1073. }
  1074. if cmd.NArg() != 1 {
  1075. cmd.Usage()
  1076. return nil
  1077. }
  1078. if err := cli.stream("GET", "/containers/"+cmd.Arg(0)+"/export", nil, cli.out, nil); err != nil {
  1079. return err
  1080. }
  1081. return nil
  1082. }
  1083. func (cli *DockerCli) CmdDiff(args ...string) error {
  1084. cmd := Subcmd("diff", "CONTAINER", "Inspect changes on a container's filesystem")
  1085. if err := cmd.Parse(args); err != nil {
  1086. return nil
  1087. }
  1088. if cmd.NArg() != 1 {
  1089. cmd.Usage()
  1090. return nil
  1091. }
  1092. body, _, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/changes", nil)
  1093. if err != nil {
  1094. return err
  1095. }
  1096. changes := []Change{}
  1097. err = json.Unmarshal(body, &changes)
  1098. if err != nil {
  1099. return err
  1100. }
  1101. for _, change := range changes {
  1102. fmt.Fprintf(cli.out, "%s\n", change.String())
  1103. }
  1104. return nil
  1105. }
  1106. func (cli *DockerCli) CmdLogs(args ...string) error {
  1107. cmd := Subcmd("logs", "CONTAINER", "Fetch the logs of a container")
  1108. if err := cmd.Parse(args); err != nil {
  1109. return nil
  1110. }
  1111. if cmd.NArg() != 1 {
  1112. cmd.Usage()
  1113. return nil
  1114. }
  1115. if err := cli.hijack("POST", "/containers/"+cmd.Arg(0)+"/attach?logs=1&stdout=1&stderr=1", false, nil, cli.out, cli.err); err != nil {
  1116. return err
  1117. }
  1118. return nil
  1119. }
  1120. func (cli *DockerCli) CmdAttach(args ...string) error {
  1121. cmd := Subcmd("attach", "CONTAINER", "Attach to a running container")
  1122. if err := cmd.Parse(args); err != nil {
  1123. return nil
  1124. }
  1125. if cmd.NArg() != 1 {
  1126. cmd.Usage()
  1127. return nil
  1128. }
  1129. body, _, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/json", nil)
  1130. if err != nil {
  1131. return err
  1132. }
  1133. container := &Container{}
  1134. err = json.Unmarshal(body, container)
  1135. if err != nil {
  1136. return err
  1137. }
  1138. if !container.State.Running {
  1139. return fmt.Errorf("Impossible to attach to a stopped container, start it first")
  1140. }
  1141. if container.Config.Tty {
  1142. if err := cli.monitorTtySize(cmd.Arg(0)); err != nil {
  1143. utils.Debugf("Error monitoring tty size: %s", err)
  1144. }
  1145. }
  1146. v := url.Values{}
  1147. v.Set("stream", "1")
  1148. v.Set("stdin", "1")
  1149. v.Set("stdout", "1")
  1150. v.Set("stderr", "1")
  1151. if err := cli.hijack("POST", "/containers/"+cmd.Arg(0)+"/attach?"+v.Encode(), container.Config.Tty, cli.in, cli.out, cli.err); err != nil {
  1152. return err
  1153. }
  1154. return nil
  1155. }
  1156. func (cli *DockerCli) CmdSearch(args ...string) error {
  1157. cmd := Subcmd("search", "NAME", "Search the docker index for images")
  1158. noTrunc := cmd.Bool("notrunc", false, "Don't truncate output")
  1159. if err := cmd.Parse(args); err != nil {
  1160. return nil
  1161. }
  1162. if cmd.NArg() != 1 {
  1163. cmd.Usage()
  1164. return nil
  1165. }
  1166. v := url.Values{}
  1167. v.Set("term", cmd.Arg(0))
  1168. body, _, err := cli.call("GET", "/images/search?"+v.Encode(), nil)
  1169. if err != nil {
  1170. return err
  1171. }
  1172. outs := []APISearch{}
  1173. err = json.Unmarshal(body, &outs)
  1174. if err != nil {
  1175. return err
  1176. }
  1177. fmt.Fprintf(cli.out, "Found %d results matching your query (\"%s\")\n", len(outs), cmd.Arg(0))
  1178. w := tabwriter.NewWriter(cli.out, 33, 1, 3, ' ', 0)
  1179. fmt.Fprintf(w, "NAME\tDESCRIPTION\n")
  1180. _, width := cli.getTtySize()
  1181. if width == 0 {
  1182. width = 45
  1183. } else {
  1184. width = width - 33 //remote the first column
  1185. }
  1186. for _, out := range outs {
  1187. desc := strings.Replace(out.Description, "\n", " ", -1)
  1188. desc = strings.Replace(desc, "\r", " ", -1)
  1189. if !*noTrunc && len(desc) > width {
  1190. desc = utils.Trunc(desc, width-3) + "..."
  1191. }
  1192. fmt.Fprintf(w, "%s\t%s\n", out.Name, desc)
  1193. }
  1194. w.Flush()
  1195. return nil
  1196. }
  1197. // Ports type - Used to parse multiple -p flags
  1198. type ports []int
  1199. // ListOpts type
  1200. type ListOpts []string
  1201. func (opts *ListOpts) String() string {
  1202. return fmt.Sprint(*opts)
  1203. }
  1204. func (opts *ListOpts) Set(value string) error {
  1205. *opts = append(*opts, value)
  1206. return nil
  1207. }
  1208. // AttachOpts stores arguments to 'docker run -a', eg. which streams to attach to
  1209. type AttachOpts map[string]bool
  1210. func NewAttachOpts() AttachOpts {
  1211. return make(AttachOpts)
  1212. }
  1213. func (opts AttachOpts) String() string {
  1214. // Cast to underlying map type to avoid infinite recursion
  1215. return fmt.Sprintf("%v", map[string]bool(opts))
  1216. }
  1217. func (opts AttachOpts) Set(val string) error {
  1218. if val != "stdin" && val != "stdout" && val != "stderr" {
  1219. return fmt.Errorf("Unsupported stream name: %s", val)
  1220. }
  1221. opts[val] = true
  1222. return nil
  1223. }
  1224. func (opts AttachOpts) Get(val string) bool {
  1225. if res, exists := opts[val]; exists {
  1226. return res
  1227. }
  1228. return false
  1229. }
  1230. // PathOpts stores a unique set of absolute paths
  1231. type PathOpts map[string]struct{}
  1232. func NewPathOpts() PathOpts {
  1233. return make(PathOpts)
  1234. }
  1235. func (opts PathOpts) String() string {
  1236. return fmt.Sprintf("%v", map[string]struct{}(opts))
  1237. }
  1238. func (opts PathOpts) Set(val string) error {
  1239. var containerPath string
  1240. splited := strings.SplitN(val, ":", 2)
  1241. if len(splited) == 1 {
  1242. containerPath = splited[0]
  1243. val = filepath.Clean(splited[0])
  1244. } else {
  1245. containerPath = splited[1]
  1246. val = fmt.Sprintf("%s:%s", splited[0], filepath.Clean(splited[1]))
  1247. }
  1248. if !filepath.IsAbs(containerPath) {
  1249. utils.Debugf("%s is not an absolute path", containerPath)
  1250. return fmt.Errorf("%s is not an absolute path", containerPath)
  1251. }
  1252. opts[val] = struct{}{}
  1253. return nil
  1254. }
  1255. func (cli *DockerCli) CmdTag(args ...string) error {
  1256. cmd := Subcmd("tag", "[OPTIONS] IMAGE REPOSITORY [TAG]", "Tag an image into a repository")
  1257. force := cmd.Bool("f", false, "Force")
  1258. if err := cmd.Parse(args); err != nil {
  1259. return nil
  1260. }
  1261. if cmd.NArg() != 2 && cmd.NArg() != 3 {
  1262. cmd.Usage()
  1263. return nil
  1264. }
  1265. v := url.Values{}
  1266. v.Set("repo", cmd.Arg(1))
  1267. if cmd.NArg() == 3 {
  1268. v.Set("tag", cmd.Arg(2))
  1269. }
  1270. if *force {
  1271. v.Set("force", "1")
  1272. }
  1273. if _, _, err := cli.call("POST", "/images/"+cmd.Arg(0)+"/tag?"+v.Encode(), nil); err != nil {
  1274. return err
  1275. }
  1276. return nil
  1277. }
  1278. func (cli *DockerCli) CmdRun(args ...string) error {
  1279. config, hostConfig, cmd, err := ParseRun(args, nil)
  1280. if err != nil {
  1281. return err
  1282. }
  1283. if config.Image == "" {
  1284. cmd.Usage()
  1285. return nil
  1286. }
  1287. flRm := cmd.Lookup("rm")
  1288. autoRemove, _ := strconv.ParseBool(flRm.Value.String())
  1289. var containerIDFile *os.File
  1290. if len(hostConfig.ContainerIDFile) > 0 {
  1291. if _, err := ioutil.ReadFile(hostConfig.ContainerIDFile); err == nil {
  1292. return fmt.Errorf("cid file found, make sure the other container isn't running or delete %s", hostConfig.ContainerIDFile)
  1293. }
  1294. containerIDFile, err = os.Create(hostConfig.ContainerIDFile)
  1295. if err != nil {
  1296. return fmt.Errorf("failed to create the container ID file: %s", err)
  1297. }
  1298. defer containerIDFile.Close()
  1299. }
  1300. //create the container
  1301. body, statusCode, err := cli.call("POST", "/containers/create", config)
  1302. //if image not found try to pull it
  1303. if statusCode == 404 {
  1304. _, tag := utils.ParseRepositoryTag(config.Image)
  1305. if tag == "" {
  1306. tag = DEFAULTTAG
  1307. }
  1308. fmt.Fprintf(cli.err, "Unable to find image '%s' (tag: %s) locally\n", config.Image, tag)
  1309. v := url.Values{}
  1310. repos, tag := utils.ParseRepositoryTag(config.Image)
  1311. v.Set("fromImage", repos)
  1312. v.Set("tag", tag)
  1313. // Resolve the Repository name from fqn to endpoint + name
  1314. var endpoint string
  1315. endpoint, _, err = registry.ResolveRepositoryName(repos)
  1316. if err != nil {
  1317. return err
  1318. }
  1319. // Load the auth config file, to be able to pull the image
  1320. cli.LoadConfigFile()
  1321. // Resolve the Auth config relevant for this server
  1322. authConfig := cli.configFile.ResolveAuthConfig(endpoint)
  1323. buf, err := json.Marshal(authConfig)
  1324. if err != nil {
  1325. return err
  1326. }
  1327. registryAuthHeader := []string{
  1328. base64.URLEncoding.EncodeToString(buf),
  1329. }
  1330. err = cli.stream("POST", "/images/create?"+v.Encode(), nil, cli.err, map[string][]string{
  1331. "X-Registry-Auth": registryAuthHeader,
  1332. })
  1333. if err != nil {
  1334. return err
  1335. }
  1336. body, _, err = cli.call("POST", "/containers/create", config)
  1337. if err != nil {
  1338. return err
  1339. }
  1340. }
  1341. if err != nil {
  1342. return err
  1343. }
  1344. runResult := &APIRun{}
  1345. err = json.Unmarshal(body, runResult)
  1346. if err != nil {
  1347. return err
  1348. }
  1349. for _, warning := range runResult.Warnings {
  1350. fmt.Fprintf(cli.err, "WARNING: %s\n", warning)
  1351. }
  1352. if len(hostConfig.ContainerIDFile) > 0 {
  1353. if _, err = containerIDFile.WriteString(runResult.ID); err != nil {
  1354. return fmt.Errorf("failed to write the container ID to the file: %s", err)
  1355. }
  1356. }
  1357. //start the container
  1358. if _, _, err = cli.call("POST", "/containers/"+runResult.ID+"/start", hostConfig); err != nil {
  1359. return err
  1360. }
  1361. var wait chan struct{}
  1362. if !config.AttachStdout && !config.AttachStderr {
  1363. // Make this asynchrone in order to let the client write to stdin before having to read the ID
  1364. wait = make(chan struct{})
  1365. go func() {
  1366. defer close(wait)
  1367. fmt.Fprintf(cli.out, "%s\n", runResult.ID)
  1368. }()
  1369. }
  1370. if config.AttachStdin || config.AttachStdout || config.AttachStderr {
  1371. if config.Tty {
  1372. if err := cli.monitorTtySize(runResult.ID); err != nil {
  1373. utils.Errorf("Error monitoring TTY size: %s\n", err)
  1374. }
  1375. }
  1376. v := url.Values{}
  1377. v.Set("logs", "1")
  1378. v.Set("stream", "1")
  1379. var out, stderr io.Writer
  1380. if config.AttachStdin {
  1381. v.Set("stdin", "1")
  1382. }
  1383. if config.AttachStdout {
  1384. v.Set("stdout", "1")
  1385. out = cli.out
  1386. }
  1387. if config.AttachStderr {
  1388. v.Set("stderr", "1")
  1389. if config.Tty {
  1390. stderr = cli.out
  1391. } else {
  1392. stderr = cli.err
  1393. }
  1394. }
  1395. signals := make(chan os.Signal, 1)
  1396. signal.Notify(signals, syscall.SIGINT, syscall.SIGTERM)
  1397. go func() {
  1398. for sig := range signals {
  1399. fmt.Printf("\nReceived signal: %s; cleaning up\n", sig)
  1400. if err := cli.CmdStop("-t", "4", runResult.ID); err != nil {
  1401. fmt.Printf("failed to stop container: %v", err)
  1402. }
  1403. }
  1404. }()
  1405. if err := cli.hijack("POST", "/containers/"+runResult.ID+"/attach?"+v.Encode(), config.Tty, cli.in, out, stderr); err != nil {
  1406. utils.Debugf("Error hijack: %s", err)
  1407. return err
  1408. }
  1409. }
  1410. if !config.AttachStdout && !config.AttachStderr {
  1411. // Detached mode
  1412. <-wait
  1413. } else {
  1414. status, err := getExitCode(cli, runResult.ID)
  1415. if err != nil {
  1416. return err
  1417. }
  1418. if autoRemove {
  1419. _, _, err = cli.call("DELETE", "/containers/"+runResult.ID, nil)
  1420. if err != nil {
  1421. return err
  1422. }
  1423. }
  1424. if status != 0 {
  1425. return &utils.StatusError{Status: status}
  1426. }
  1427. }
  1428. return nil
  1429. }
  1430. func (cli *DockerCli) CmdCp(args ...string) error {
  1431. cmd := Subcmd("cp", "CONTAINER:RESOURCE HOSTPATH", "Copy files/folders from the RESOURCE to the HOSTPATH")
  1432. if err := cmd.Parse(args); err != nil {
  1433. return nil
  1434. }
  1435. if cmd.NArg() != 2 {
  1436. cmd.Usage()
  1437. return nil
  1438. }
  1439. var copyData APICopy
  1440. info := strings.Split(cmd.Arg(0), ":")
  1441. if len(info) != 2 {
  1442. return fmt.Errorf("Error: Resource not specified")
  1443. }
  1444. copyData.Resource = info[1]
  1445. copyData.HostPath = cmd.Arg(1)
  1446. data, statusCode, err := cli.call("POST", "/containers/"+info[0]+"/copy", copyData)
  1447. if err != nil {
  1448. return err
  1449. }
  1450. if statusCode == 200 {
  1451. r := bytes.NewReader(data)
  1452. if err := Untar(r, copyData.HostPath); err != nil {
  1453. return err
  1454. }
  1455. }
  1456. return nil
  1457. }
  1458. func (cli *DockerCli) call(method, path string, data interface{}) ([]byte, int, error) {
  1459. var params io.Reader
  1460. if data != nil {
  1461. buf, err := json.Marshal(data)
  1462. if err != nil {
  1463. return nil, -1, err
  1464. }
  1465. params = bytes.NewBuffer(buf)
  1466. }
  1467. req, err := http.NewRequest(method, fmt.Sprintf("/v%g%s", APIVERSION, path), params)
  1468. if err != nil {
  1469. return nil, -1, err
  1470. }
  1471. req.Header.Set("User-Agent", "Docker-Client/"+VERSION)
  1472. req.Host = cli.addr
  1473. if data != nil {
  1474. req.Header.Set("Content-Type", "application/json")
  1475. } else if method == "POST" {
  1476. req.Header.Set("Content-Type", "plain/text")
  1477. }
  1478. dial, err := net.Dial(cli.proto, cli.addr)
  1479. if err != nil {
  1480. if strings.Contains(err.Error(), "connection refused") {
  1481. return nil, -1, ErrConnectionRefused
  1482. }
  1483. return nil, -1, err
  1484. }
  1485. clientconn := httputil.NewClientConn(dial, nil)
  1486. resp, err := clientconn.Do(req)
  1487. defer clientconn.Close()
  1488. if err != nil {
  1489. if strings.Contains(err.Error(), "connection refused") {
  1490. return nil, -1, ErrConnectionRefused
  1491. }
  1492. return nil, -1, err
  1493. }
  1494. defer resp.Body.Close()
  1495. body, err := ioutil.ReadAll(resp.Body)
  1496. if err != nil {
  1497. return nil, -1, err
  1498. }
  1499. if resp.StatusCode < 200 || resp.StatusCode >= 400 {
  1500. if len(body) == 0 {
  1501. return nil, resp.StatusCode, fmt.Errorf("Error: %s", http.StatusText(resp.StatusCode))
  1502. }
  1503. return nil, resp.StatusCode, fmt.Errorf("Error: %s", body)
  1504. }
  1505. return body, resp.StatusCode, nil
  1506. }
  1507. func (cli *DockerCli) stream(method, path string, in io.Reader, out io.Writer, headers map[string][]string) error {
  1508. if (method == "POST" || method == "PUT") && in == nil {
  1509. in = bytes.NewReader([]byte{})
  1510. }
  1511. req, err := http.NewRequest(method, fmt.Sprintf("/v%g%s", APIVERSION, path), in)
  1512. if err != nil {
  1513. return err
  1514. }
  1515. req.Header.Set("User-Agent", "Docker-Client/"+VERSION)
  1516. req.Host = cli.addr
  1517. if method == "POST" {
  1518. req.Header.Set("Content-Type", "plain/text")
  1519. }
  1520. if headers != nil {
  1521. for k, v := range headers {
  1522. req.Header[k] = v
  1523. }
  1524. }
  1525. dial, err := net.Dial(cli.proto, cli.addr)
  1526. if err != nil {
  1527. if strings.Contains(err.Error(), "connection refused") {
  1528. return fmt.Errorf("Can't connect to docker daemon. Is 'docker -d' running on this host?")
  1529. }
  1530. return err
  1531. }
  1532. clientconn := httputil.NewClientConn(dial, nil)
  1533. resp, err := clientconn.Do(req)
  1534. defer clientconn.Close()
  1535. if err != nil {
  1536. if strings.Contains(err.Error(), "connection refused") {
  1537. return fmt.Errorf("Can't connect to docker daemon. Is 'docker -d' running on this host?")
  1538. }
  1539. return err
  1540. }
  1541. defer resp.Body.Close()
  1542. if resp.StatusCode < 200 || resp.StatusCode >= 400 {
  1543. body, err := ioutil.ReadAll(resp.Body)
  1544. if err != nil {
  1545. return err
  1546. }
  1547. if len(body) == 0 {
  1548. return fmt.Errorf("Error :%s", http.StatusText(resp.StatusCode))
  1549. }
  1550. return fmt.Errorf("Error: %s", body)
  1551. }
  1552. if matchesContentType(resp.Header.Get("Content-Type"), "application/json") {
  1553. return utils.DisplayJSONMessagesStream(resp.Body, out)
  1554. } else {
  1555. if _, err := io.Copy(out, resp.Body); err != nil {
  1556. return err
  1557. }
  1558. }
  1559. return nil
  1560. }
  1561. func (cli *DockerCli) hijack(method, path string, setRawTerminal bool, in io.ReadCloser, stdout, stderr io.Writer) error {
  1562. req, err := http.NewRequest(method, fmt.Sprintf("/v%g%s", APIVERSION, path), nil)
  1563. if err != nil {
  1564. return err
  1565. }
  1566. req.Header.Set("User-Agent", "Docker-Client/"+VERSION)
  1567. req.Header.Set("Content-Type", "plain/text")
  1568. req.Host = cli.addr
  1569. dial, err := net.Dial(cli.proto, cli.addr)
  1570. if err != nil {
  1571. if strings.Contains(err.Error(), "connection refused") {
  1572. return fmt.Errorf("Can't connect to docker daemon. Is 'docker -d' running on this host?")
  1573. }
  1574. return err
  1575. }
  1576. clientconn := httputil.NewClientConn(dial, nil)
  1577. defer clientconn.Close()
  1578. // Server hijacks the connection, error 'connection closed' expected
  1579. clientconn.Do(req)
  1580. rwc, br := clientconn.Hijack()
  1581. defer rwc.Close()
  1582. var receiveStdout chan error
  1583. if stdout != nil {
  1584. receiveStdout = utils.Go(func() (err error) {
  1585. // When TTY is ON, use regular copy
  1586. if setRawTerminal {
  1587. _, err = io.Copy(stdout, br)
  1588. } else {
  1589. _, err = utils.StdCopy(stdout, stderr, br)
  1590. }
  1591. utils.Debugf("[hijack] End of stdout")
  1592. return err
  1593. })
  1594. }
  1595. if in != nil && setRawTerminal && cli.isTerminal && os.Getenv("NORAW") == "" {
  1596. oldState, err := term.SetRawTerminal(cli.terminalFd)
  1597. if err != nil {
  1598. return err
  1599. }
  1600. defer term.RestoreTerminal(cli.terminalFd, oldState)
  1601. }
  1602. sendStdin := utils.Go(func() error {
  1603. if in != nil {
  1604. io.Copy(rwc, in)
  1605. utils.Debugf("[hijack] End of stdin")
  1606. }
  1607. if tcpc, ok := rwc.(*net.TCPConn); ok {
  1608. if err := tcpc.CloseWrite(); err != nil {
  1609. utils.Errorf("Couldn't send EOF: %s\n", err)
  1610. }
  1611. } else if unixc, ok := rwc.(*net.UnixConn); ok {
  1612. if err := unixc.CloseWrite(); err != nil {
  1613. utils.Errorf("Couldn't send EOF: %s\n", err)
  1614. }
  1615. }
  1616. // Discard errors due to pipe interruption
  1617. return nil
  1618. })
  1619. if stdout != nil {
  1620. if err := <-receiveStdout; err != nil {
  1621. utils.Errorf("Error receiveStdout: %s", err)
  1622. return err
  1623. }
  1624. }
  1625. if !cli.isTerminal {
  1626. if err := <-sendStdin; err != nil {
  1627. utils.Errorf("Error sendStdin: %s", err)
  1628. return err
  1629. }
  1630. }
  1631. return nil
  1632. }
  1633. func (cli *DockerCli) getTtySize() (int, int) {
  1634. if !cli.isTerminal {
  1635. return 0, 0
  1636. }
  1637. ws, err := term.GetWinsize(cli.terminalFd)
  1638. if err != nil {
  1639. utils.Errorf("Error getting size: %s", err)
  1640. if ws == nil {
  1641. return 0, 0
  1642. }
  1643. }
  1644. return int(ws.Height), int(ws.Width)
  1645. }
  1646. func (cli *DockerCli) resizeTty(id string) {
  1647. height, width := cli.getTtySize()
  1648. if height == 0 && width == 0 {
  1649. return
  1650. }
  1651. v := url.Values{}
  1652. v.Set("h", strconv.Itoa(height))
  1653. v.Set("w", strconv.Itoa(width))
  1654. if _, _, err := cli.call("POST", "/containers/"+id+"/resize?"+v.Encode(), nil); err != nil {
  1655. utils.Errorf("Error resize: %s", err)
  1656. }
  1657. }
  1658. func (cli *DockerCli) monitorTtySize(id string) error {
  1659. if !cli.isTerminal {
  1660. return fmt.Errorf("Impossible to monitor size on non-tty")
  1661. }
  1662. cli.resizeTty(id)
  1663. sigchan := make(chan os.Signal, 1)
  1664. signal.Notify(sigchan, syscall.SIGWINCH)
  1665. go func() {
  1666. for _ = range sigchan {
  1667. cli.resizeTty(id)
  1668. }
  1669. }()
  1670. return nil
  1671. }
  1672. func Subcmd(name, signature, description string) *flag.FlagSet {
  1673. flags := flag.NewFlagSet(name, flag.ContinueOnError)
  1674. flags.Usage = func() {
  1675. // FIXME: use custom stdout or return error
  1676. fmt.Fprintf(os.Stdout, "\nUsage: docker %s %s\n\n%s\n\n", name, signature, description)
  1677. flags.PrintDefaults()
  1678. }
  1679. return flags
  1680. }
  1681. func (cli *DockerCli) LoadConfigFile() (err error) {
  1682. cli.configFile, err = auth.LoadConfig(os.Getenv("HOME"))
  1683. if err != nil {
  1684. fmt.Fprintf(cli.err, "WARNING: %s\n", err)
  1685. }
  1686. return err
  1687. }
  1688. func waitForExit(cli *DockerCli, containerId string) (int, error) {
  1689. body, _, err := cli.call("POST", "/containers/"+containerId+"/wait", nil)
  1690. if err != nil {
  1691. // If we can't connect, then the daemon probably died.
  1692. if err != ErrConnectionRefused {
  1693. return -1, err
  1694. }
  1695. return -1, nil
  1696. }
  1697. var out APIWait
  1698. if err := json.Unmarshal(body, &out); err != nil {
  1699. return -1, err
  1700. }
  1701. return out.StatusCode, nil
  1702. }
  1703. func getExitCode(cli *DockerCli, containerId string) (int, error) {
  1704. body, _, err := cli.call("GET", "/containers/"+containerId+"/json", nil)
  1705. if err != nil {
  1706. // If we can't connect, then the daemon probably died.
  1707. if err != ErrConnectionRefused {
  1708. return -1, err
  1709. }
  1710. return -1, nil
  1711. }
  1712. c := &Container{}
  1713. if err := json.Unmarshal(body, c); err != nil {
  1714. return -1, err
  1715. }
  1716. return c.State.ExitCode, nil
  1717. }
  1718. func NewDockerCli(in io.ReadCloser, out, err io.Writer, proto, addr string) *DockerCli {
  1719. var (
  1720. isTerminal = false
  1721. terminalFd uintptr
  1722. )
  1723. if in != nil {
  1724. if file, ok := in.(*os.File); ok {
  1725. terminalFd = file.Fd()
  1726. isTerminal = term.IsTerminal(terminalFd)
  1727. }
  1728. }
  1729. if err == nil {
  1730. err = out
  1731. }
  1732. return &DockerCli{
  1733. proto: proto,
  1734. addr: addr,
  1735. in: in,
  1736. out: out,
  1737. err: err,
  1738. isTerminal: isTerminal,
  1739. terminalFd: terminalFd,
  1740. }
  1741. }
  1742. type DockerCli struct {
  1743. proto string
  1744. addr string
  1745. configFile *auth.ConfigFile
  1746. in io.ReadCloser
  1747. out io.Writer
  1748. err io.Writer
  1749. isTerminal bool
  1750. terminalFd uintptr
  1751. }