commands.go 49 KB

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