commands.go 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965
  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.DevmapperDataTotal != 0 {
  430. fmt.Fprintf(cli.out, "Devmapper disk use: Data: %.1f/%.1f Metadata: %.1f/%.1f\n",
  431. float64(out.DevmapperDataUsed)/(1024*1024), float64(out.DevmapperDataTotal)/(1024*1024),
  432. float64(out.DevmapperMetadataUsed)/(1024*1024), float64(out.DevmapperMetadataTotal)/(1024*1024))
  433. }
  434. if out.Debug || os.Getenv("DEBUG") != "" {
  435. fmt.Fprintf(cli.out, "Debug mode (server): %v\n", out.Debug)
  436. fmt.Fprintf(cli.out, "Debug mode (client): %v\n", os.Getenv("DEBUG") != "")
  437. fmt.Fprintf(cli.out, "Fds: %d\n", out.NFd)
  438. fmt.Fprintf(cli.out, "Goroutines: %d\n", out.NGoroutines)
  439. fmt.Fprintf(cli.out, "LXC Version: %s\n", out.LXCVersion)
  440. fmt.Fprintf(cli.out, "EventsListeners: %d\n", out.NEventsListener)
  441. fmt.Fprintf(cli.out, "Kernel Version: %s\n", out.KernelVersion)
  442. fmt.Fprintf(cli.out, "Devmapper pool: %s\n", out.DevmapperPool)
  443. }
  444. if len(out.IndexServerAddress) != 0 {
  445. cli.LoadConfigFile()
  446. u := cli.configFile.Configs[out.IndexServerAddress].Username
  447. if len(u) > 0 {
  448. fmt.Fprintf(cli.out, "Username: %v\n", u)
  449. fmt.Fprintf(cli.out, "Registry: %v\n", out.IndexServerAddress)
  450. }
  451. }
  452. if !out.MemoryLimit {
  453. fmt.Fprintf(cli.err, "WARNING: No memory limit support\n")
  454. }
  455. if !out.SwapLimit {
  456. fmt.Fprintf(cli.err, "WARNING: No swap limit support\n")
  457. }
  458. if !out.IPv4Forwarding {
  459. fmt.Fprintf(cli.err, "WARNING: IPv4 forwarding is disabled.\n")
  460. }
  461. return nil
  462. }
  463. func (cli *DockerCli) CmdStop(args ...string) error {
  464. cmd := Subcmd("stop", "[OPTIONS] CONTAINER [CONTAINER...]", "Stop a running container")
  465. nSeconds := cmd.Int("t", 10, "Number of seconds to wait for the container to stop before killing it.")
  466. if err := cmd.Parse(args); err != nil {
  467. return nil
  468. }
  469. if cmd.NArg() < 1 {
  470. cmd.Usage()
  471. return nil
  472. }
  473. v := url.Values{}
  474. v.Set("t", strconv.Itoa(*nSeconds))
  475. for _, name := range cmd.Args() {
  476. _, _, err := cli.call("POST", "/containers/"+name+"/stop?"+v.Encode(), nil)
  477. if err != nil {
  478. fmt.Fprintf(cli.err, "%s\n", err)
  479. } else {
  480. fmt.Fprintf(cli.out, "%s\n", name)
  481. }
  482. }
  483. return nil
  484. }
  485. func (cli *DockerCli) CmdRestart(args ...string) error {
  486. cmd := Subcmd("restart", "[OPTIONS] CONTAINER [CONTAINER...]", "Restart a running container")
  487. 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")
  488. if err := cmd.Parse(args); err != nil {
  489. return nil
  490. }
  491. if cmd.NArg() < 1 {
  492. cmd.Usage()
  493. return nil
  494. }
  495. v := url.Values{}
  496. v.Set("t", strconv.Itoa(*nSeconds))
  497. for _, name := range cmd.Args() {
  498. _, _, err := cli.call("POST", "/containers/"+name+"/restart?"+v.Encode(), nil)
  499. if err != nil {
  500. fmt.Fprintf(cli.err, "%s\n", err)
  501. } else {
  502. fmt.Fprintf(cli.out, "%s\n", name)
  503. }
  504. }
  505. return nil
  506. }
  507. func (cli *DockerCli) CmdStart(args ...string) error {
  508. cmd := Subcmd("start", "CONTAINER [CONTAINER...]", "Restart a stopped container")
  509. if err := cmd.Parse(args); err != nil {
  510. return nil
  511. }
  512. if cmd.NArg() < 1 {
  513. cmd.Usage()
  514. return nil
  515. }
  516. var encounteredError error
  517. for _, name := range args {
  518. _, _, err := cli.call("POST", "/containers/"+name+"/start", nil)
  519. if err != nil {
  520. fmt.Fprintf(cli.err, "%s\n", err)
  521. encounteredError = fmt.Errorf("Error: failed to start one or more containers")
  522. } else {
  523. fmt.Fprintf(cli.out, "%s\n", name)
  524. }
  525. }
  526. return encounteredError
  527. }
  528. func (cli *DockerCli) CmdInspect(args ...string) error {
  529. cmd := Subcmd("inspect", "CONTAINER|IMAGE [CONTAINER|IMAGE...]", "Return low-level information on a container/image")
  530. if err := cmd.Parse(args); err != nil {
  531. return nil
  532. }
  533. if cmd.NArg() < 1 {
  534. cmd.Usage()
  535. return nil
  536. }
  537. fmt.Fprintf(cli.out, "[")
  538. for i, name := range args {
  539. if i > 0 {
  540. fmt.Fprintf(cli.out, ",")
  541. }
  542. obj, _, err := cli.call("GET", "/containers/"+name+"/json", nil)
  543. if err != nil {
  544. obj, _, err = cli.call("GET", "/images/"+name+"/json", nil)
  545. if err != nil {
  546. fmt.Fprintf(cli.err, "No such image or container: %s\n", name)
  547. continue
  548. }
  549. }
  550. indented := new(bytes.Buffer)
  551. if err = json.Indent(indented, obj, "", " "); err != nil {
  552. fmt.Fprintf(cli.err, "%s\n", err)
  553. continue
  554. }
  555. if _, err := io.Copy(cli.out, indented); err != nil {
  556. fmt.Fprintf(cli.err, "%s\n", err)
  557. }
  558. }
  559. fmt.Fprintf(cli.out, "]")
  560. return nil
  561. }
  562. func (cli *DockerCli) CmdTop(args ...string) error {
  563. cmd := Subcmd("top", "CONTAINER", "Lookup the running processes of a container")
  564. if err := cmd.Parse(args); err != nil {
  565. return nil
  566. }
  567. if cmd.NArg() == 0 {
  568. cmd.Usage()
  569. return nil
  570. }
  571. val := url.Values{}
  572. if cmd.NArg() > 1 {
  573. val.Set("ps_args", strings.Join(cmd.Args()[1:], " "))
  574. }
  575. body, _, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/top?"+val.Encode(), nil)
  576. if err != nil {
  577. return err
  578. }
  579. procs := APITop{}
  580. err = json.Unmarshal(body, &procs)
  581. if err != nil {
  582. return err
  583. }
  584. w := tabwriter.NewWriter(cli.out, 20, 1, 3, ' ', 0)
  585. fmt.Fprintln(w, strings.Join(procs.Titles, "\t"))
  586. for _, proc := range procs.Processes {
  587. fmt.Fprintln(w, strings.Join(proc, "\t"))
  588. }
  589. w.Flush()
  590. return nil
  591. }
  592. func (cli *DockerCli) CmdPort(args ...string) error {
  593. cmd := Subcmd("port", "CONTAINER PRIVATE_PORT", "Lookup the public-facing port which is NAT-ed to PRIVATE_PORT")
  594. if err := cmd.Parse(args); err != nil {
  595. return nil
  596. }
  597. if cmd.NArg() != 2 {
  598. cmd.Usage()
  599. return nil
  600. }
  601. port := cmd.Arg(1)
  602. proto := "Tcp"
  603. parts := strings.SplitN(port, "/", 2)
  604. if len(parts) == 2 && len(parts[1]) != 0 {
  605. port = parts[0]
  606. proto = strings.ToUpper(parts[1][:1]) + strings.ToLower(parts[1][1:])
  607. }
  608. body, _, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/json", nil)
  609. if err != nil {
  610. return err
  611. }
  612. var out Container
  613. err = json.Unmarshal(body, &out)
  614. if err != nil {
  615. return err
  616. }
  617. if frontend, exists := out.NetworkSettings.PortMapping[proto][port]; exists {
  618. fmt.Fprintf(cli.out, "%s\n", frontend)
  619. } else {
  620. return fmt.Errorf("Error: No private port '%s' allocated on %s", cmd.Arg(1), cmd.Arg(0))
  621. }
  622. return nil
  623. }
  624. // 'docker rmi IMAGE' removes all images with the name IMAGE
  625. func (cli *DockerCli) CmdRmi(args ...string) error {
  626. cmd := Subcmd("rmi", "IMAGE [IMAGE...]", "Remove one or more images")
  627. if err := cmd.Parse(args); err != nil {
  628. return nil
  629. }
  630. if cmd.NArg() < 1 {
  631. cmd.Usage()
  632. return nil
  633. }
  634. for _, name := range cmd.Args() {
  635. body, _, err := cli.call("DELETE", "/images/"+name, nil)
  636. if err != nil {
  637. fmt.Fprintf(cli.err, "%s", err)
  638. } else {
  639. var outs []APIRmi
  640. err = json.Unmarshal(body, &outs)
  641. if err != nil {
  642. return err
  643. }
  644. for _, out := range outs {
  645. if out.Deleted != "" {
  646. fmt.Fprintf(cli.out, "Deleted: %s\n", out.Deleted)
  647. } else {
  648. fmt.Fprintf(cli.out, "Untagged: %s\n", out.Untagged)
  649. }
  650. }
  651. }
  652. }
  653. return nil
  654. }
  655. func (cli *DockerCli) CmdHistory(args ...string) error {
  656. cmd := Subcmd("history", "IMAGE", "Show the history of an image")
  657. if err := cmd.Parse(args); err != nil {
  658. return nil
  659. }
  660. if cmd.NArg() != 1 {
  661. cmd.Usage()
  662. return nil
  663. }
  664. body, _, err := cli.call("GET", "/images/"+cmd.Arg(0)+"/history", nil)
  665. if err != nil {
  666. return err
  667. }
  668. var outs []APIHistory
  669. err = json.Unmarshal(body, &outs)
  670. if err != nil {
  671. return err
  672. }
  673. w := tabwriter.NewWriter(cli.out, 20, 1, 3, ' ', 0)
  674. fmt.Fprintln(w, "ID\tCREATED\tCREATED BY")
  675. for _, out := range outs {
  676. if out.Tags != nil {
  677. out.ID = out.Tags[0]
  678. }
  679. fmt.Fprintf(w, "%s \t%s ago\t%s\n", out.ID, utils.HumanDuration(time.Now().Sub(time.Unix(out.Created, 0))), out.CreatedBy)
  680. }
  681. w.Flush()
  682. return nil
  683. }
  684. func (cli *DockerCli) CmdRm(args ...string) error {
  685. cmd := Subcmd("rm", "[OPTIONS] CONTAINER [CONTAINER...]", "Remove one or more containers")
  686. v := cmd.Bool("v", false, "Remove the volumes associated to the container")
  687. if err := cmd.Parse(args); err != nil {
  688. return nil
  689. }
  690. if cmd.NArg() < 1 {
  691. cmd.Usage()
  692. return nil
  693. }
  694. val := url.Values{}
  695. if *v {
  696. val.Set("v", "1")
  697. }
  698. for _, name := range cmd.Args() {
  699. _, _, err := cli.call("DELETE", "/containers/"+name+"?"+val.Encode(), nil)
  700. if err != nil {
  701. fmt.Fprintf(cli.err, "%s\n", err)
  702. } else {
  703. fmt.Fprintf(cli.out, "%s\n", name)
  704. }
  705. }
  706. return nil
  707. }
  708. // 'docker kill NAME' kills a running container
  709. func (cli *DockerCli) CmdKill(args ...string) error {
  710. cmd := Subcmd("kill", "CONTAINER [CONTAINER...]", "Kill a running container")
  711. if err := cmd.Parse(args); err != nil {
  712. return nil
  713. }
  714. if cmd.NArg() < 1 {
  715. cmd.Usage()
  716. return nil
  717. }
  718. for _, name := range args {
  719. _, _, err := cli.call("POST", "/containers/"+name+"/kill", nil)
  720. if err != nil {
  721. fmt.Fprintf(cli.err, "%s\n", err)
  722. } else {
  723. fmt.Fprintf(cli.out, "%s\n", name)
  724. }
  725. }
  726. return nil
  727. }
  728. func (cli *DockerCli) CmdImport(args ...string) error {
  729. 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).")
  730. if err := cmd.Parse(args); err != nil {
  731. return nil
  732. }
  733. if cmd.NArg() < 1 {
  734. cmd.Usage()
  735. return nil
  736. }
  737. src, repository, tag := cmd.Arg(0), cmd.Arg(1), cmd.Arg(2)
  738. v := url.Values{}
  739. v.Set("repo", repository)
  740. v.Set("tag", tag)
  741. v.Set("fromSrc", src)
  742. var in io.Reader
  743. if src == "-" {
  744. in = cli.in
  745. }
  746. return cli.stream("POST", "/images/create?"+v.Encode(), in, cli.out, nil)
  747. }
  748. func (cli *DockerCli) CmdPush(args ...string) error {
  749. cmd := Subcmd("push", "NAME", "Push an image or a repository to the registry")
  750. if err := cmd.Parse(args); err != nil {
  751. return nil
  752. }
  753. name := cmd.Arg(0)
  754. if name == "" {
  755. cmd.Usage()
  756. return nil
  757. }
  758. cli.LoadConfigFile()
  759. // Resolve the Repository name from fqn to endpoint + name
  760. endpoint, _, err := registry.ResolveRepositoryName(name)
  761. if err != nil {
  762. return err
  763. }
  764. // Resolve the Auth config relevant for this server
  765. authConfig := cli.configFile.ResolveAuthConfig(endpoint)
  766. // If we're not using a custom registry, we know the restrictions
  767. // applied to repository names and can warn the user in advance.
  768. // Custom repositories can have different rules, and we must also
  769. // allow pushing by image ID.
  770. if len(strings.SplitN(name, "/", 2)) == 1 {
  771. username := cli.configFile.Configs[auth.IndexServerAddress()].Username
  772. if username == "" {
  773. username = "<user>"
  774. }
  775. return fmt.Errorf("Impossible to push a \"root\" repository. Please rename your repository in <user>/<repo> (ex: %s/%s)", username, name)
  776. }
  777. v := url.Values{}
  778. push := func(authConfig auth.AuthConfig) error {
  779. buf, err := json.Marshal(authConfig)
  780. if err != nil {
  781. return err
  782. }
  783. registryAuthHeader := []string{
  784. base64.URLEncoding.EncodeToString(buf),
  785. }
  786. return cli.stream("POST", "/images/"+name+"/push?"+v.Encode(), nil, cli.out, map[string][]string{
  787. "X-Registry-Auth": registryAuthHeader,
  788. })
  789. }
  790. if err := push(authConfig); err != nil {
  791. if err.Error() == registry.ErrLoginRequired.Error() {
  792. fmt.Fprintln(cli.out, "\nPlease login prior to push:")
  793. if err := cli.CmdLogin(endpoint); err != nil {
  794. return err
  795. }
  796. authConfig := cli.configFile.ResolveAuthConfig(endpoint)
  797. return push(authConfig)
  798. }
  799. return err
  800. }
  801. return nil
  802. }
  803. func (cli *DockerCli) CmdPull(args ...string) error {
  804. cmd := Subcmd("pull", "NAME", "Pull an image or a repository from the registry")
  805. tag := cmd.String("t", "", "Download tagged image in repository")
  806. if err := cmd.Parse(args); err != nil {
  807. return nil
  808. }
  809. if cmd.NArg() != 1 {
  810. cmd.Usage()
  811. return nil
  812. }
  813. remote, parsedTag := utils.ParseRepositoryTag(cmd.Arg(0))
  814. if *tag == "" {
  815. *tag = parsedTag
  816. }
  817. // Resolve the Repository name from fqn to endpoint + name
  818. endpoint, _, err := registry.ResolveRepositoryName(remote)
  819. if err != nil {
  820. return err
  821. }
  822. cli.LoadConfigFile()
  823. // Resolve the Auth config relevant for this server
  824. authConfig := cli.configFile.ResolveAuthConfig(endpoint)
  825. v := url.Values{}
  826. v.Set("fromImage", remote)
  827. v.Set("tag", *tag)
  828. pull := func(authConfig auth.AuthConfig) error {
  829. buf, err := json.Marshal(authConfig)
  830. if err != nil {
  831. return err
  832. }
  833. registryAuthHeader := []string{
  834. base64.URLEncoding.EncodeToString(buf),
  835. }
  836. return cli.stream("POST", "/images/create?"+v.Encode(), nil, cli.out, map[string][]string{
  837. "X-Registry-Auth": registryAuthHeader,
  838. })
  839. }
  840. if err := pull(authConfig); err != nil {
  841. if err.Error() == registry.ErrLoginRequired.Error() {
  842. fmt.Fprintln(cli.out, "\nPlease login prior to push:")
  843. if err := cli.CmdLogin(endpoint); err != nil {
  844. return err
  845. }
  846. authConfig := cli.configFile.ResolveAuthConfig(endpoint)
  847. return pull(authConfig)
  848. }
  849. return err
  850. }
  851. return nil
  852. }
  853. func (cli *DockerCli) CmdImages(args ...string) error {
  854. cmd := Subcmd("images", "[OPTIONS] [NAME]", "List images")
  855. quiet := cmd.Bool("q", false, "only show numeric IDs")
  856. all := cmd.Bool("a", false, "show all images")
  857. noTrunc := cmd.Bool("notrunc", false, "Don't truncate output")
  858. flViz := cmd.Bool("viz", false, "output graph in graphviz format")
  859. if err := cmd.Parse(args); err != nil {
  860. return nil
  861. }
  862. if cmd.NArg() > 1 {
  863. cmd.Usage()
  864. return nil
  865. }
  866. if *flViz {
  867. body, _, err := cli.call("GET", "/images/viz", false)
  868. if err != nil {
  869. return err
  870. }
  871. fmt.Fprintf(cli.out, "%s", body)
  872. } else {
  873. v := url.Values{}
  874. if cmd.NArg() == 1 {
  875. v.Set("filter", cmd.Arg(0))
  876. }
  877. if *all {
  878. v.Set("all", "1")
  879. }
  880. body, _, err := cli.call("GET", "/images/json?"+v.Encode(), nil)
  881. if err != nil {
  882. return err
  883. }
  884. var outs []APIImages
  885. err = json.Unmarshal(body, &outs)
  886. if err != nil {
  887. return err
  888. }
  889. w := tabwriter.NewWriter(cli.out, 20, 1, 3, ' ', 0)
  890. if !*quiet {
  891. fmt.Fprintln(w, "REPOSITORY\tTAG\tID\tCREATED\tSIZE")
  892. }
  893. for _, out := range outs {
  894. if out.Repository == "" {
  895. out.Repository = "<none>"
  896. }
  897. if out.Tag == "" {
  898. out.Tag = "<none>"
  899. }
  900. if !*quiet {
  901. fmt.Fprintf(w, "%s\t%s\t", out.Repository, out.Tag)
  902. if *noTrunc {
  903. fmt.Fprintf(w, "%s\t", out.ID)
  904. } else {
  905. fmt.Fprintf(w, "%s\t", utils.TruncateID(out.ID))
  906. }
  907. fmt.Fprintf(w, "%s ago\t", utils.HumanDuration(time.Now().Sub(time.Unix(out.Created, 0))))
  908. if out.VirtualSize > 0 {
  909. fmt.Fprintf(w, "%s (virtual %s)\n", utils.HumanSize(out.Size), utils.HumanSize(out.VirtualSize))
  910. } else {
  911. fmt.Fprintf(w, "%s\n", utils.HumanSize(out.Size))
  912. }
  913. } else {
  914. if *noTrunc {
  915. fmt.Fprintln(w, out.ID)
  916. } else {
  917. fmt.Fprintln(w, utils.TruncateID(out.ID))
  918. }
  919. }
  920. }
  921. if !*quiet {
  922. w.Flush()
  923. }
  924. }
  925. return nil
  926. }
  927. func displayablePorts(ports []APIPort) string {
  928. result := []string{}
  929. for _, port := range ports {
  930. if port.Type == "tcp" {
  931. result = append(result, fmt.Sprintf("%d->%d", port.PublicPort, port.PrivatePort))
  932. } else {
  933. result = append(result, fmt.Sprintf("%d->%d/%s", port.PublicPort, port.PrivatePort, port.Type))
  934. }
  935. }
  936. sort.Strings(result)
  937. return strings.Join(result, ", ")
  938. }
  939. func (cli *DockerCli) CmdPs(args ...string) error {
  940. cmd := Subcmd("ps", "[OPTIONS]", "List containers")
  941. quiet := cmd.Bool("q", false, "Only display numeric IDs")
  942. size := cmd.Bool("s", false, "Display sizes")
  943. all := cmd.Bool("a", false, "Show all containers. Only running containers are shown by default.")
  944. noTrunc := cmd.Bool("notrunc", false, "Don't truncate output")
  945. nLatest := cmd.Bool("l", false, "Show only the latest created container, include non-running ones.")
  946. since := cmd.String("sinceId", "", "Show only containers created since Id, include non-running ones.")
  947. before := cmd.String("beforeId", "", "Show only container created before Id, include non-running ones.")
  948. last := cmd.Int("n", -1, "Show n last created containers, include non-running ones.")
  949. if err := cmd.Parse(args); err != nil {
  950. return nil
  951. }
  952. v := url.Values{}
  953. if *last == -1 && *nLatest {
  954. *last = 1
  955. }
  956. if *all {
  957. v.Set("all", "1")
  958. }
  959. if *last != -1 {
  960. v.Set("limit", strconv.Itoa(*last))
  961. }
  962. if *since != "" {
  963. v.Set("since", *since)
  964. }
  965. if *before != "" {
  966. v.Set("before", *before)
  967. }
  968. if *size {
  969. v.Set("size", "1")
  970. }
  971. body, _, err := cli.call("GET", "/containers/json?"+v.Encode(), nil)
  972. if err != nil {
  973. return err
  974. }
  975. var outs []APIContainers
  976. err = json.Unmarshal(body, &outs)
  977. if err != nil {
  978. return err
  979. }
  980. w := tabwriter.NewWriter(cli.out, 20, 1, 3, ' ', 0)
  981. if !*quiet {
  982. fmt.Fprint(w, "ID\tIMAGE\tCOMMAND\tCREATED\tSTATUS\tPORTS")
  983. if *size {
  984. fmt.Fprintln(w, "\tSIZE")
  985. } else {
  986. fmt.Fprint(w, "\n")
  987. }
  988. }
  989. for _, out := range outs {
  990. if !*quiet {
  991. if *noTrunc {
  992. 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))
  993. } else {
  994. 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))
  995. }
  996. if *size {
  997. if out.SizeRootFs > 0 {
  998. fmt.Fprintf(w, "%s (virtual %s)\n", utils.HumanSize(out.SizeRw), utils.HumanSize(out.SizeRootFs))
  999. } else {
  1000. fmt.Fprintf(w, "%s\n", utils.HumanSize(out.SizeRw))
  1001. }
  1002. } else {
  1003. fmt.Fprint(w, "\n")
  1004. }
  1005. } else {
  1006. if *noTrunc {
  1007. fmt.Fprintln(w, out.ID)
  1008. } else {
  1009. fmt.Fprintln(w, utils.TruncateID(out.ID))
  1010. }
  1011. }
  1012. }
  1013. if !*quiet {
  1014. w.Flush()
  1015. }
  1016. return nil
  1017. }
  1018. func (cli *DockerCli) CmdCommit(args ...string) error {
  1019. cmd := Subcmd("commit", "[OPTIONS] CONTAINER [REPOSITORY [TAG]]", "Create a new image from a container's changes")
  1020. flComment := cmd.String("m", "", "Commit message")
  1021. flAuthor := cmd.String("author", "", "Author (eg. \"John Hannibal Smith <hannibal@a-team.com>\"")
  1022. flConfig := cmd.String("run", "", "Config automatically applied when the image is run. "+`(ex: {"Cmd": ["cat", "/world"], "PortSpecs": ["22"]}')`)
  1023. if err := cmd.Parse(args); err != nil {
  1024. return nil
  1025. }
  1026. name, repository, tag := cmd.Arg(0), cmd.Arg(1), cmd.Arg(2)
  1027. if name == "" {
  1028. cmd.Usage()
  1029. return nil
  1030. }
  1031. v := url.Values{}
  1032. v.Set("container", name)
  1033. v.Set("repo", repository)
  1034. v.Set("tag", tag)
  1035. v.Set("comment", *flComment)
  1036. v.Set("author", *flAuthor)
  1037. var config *Config
  1038. if *flConfig != "" {
  1039. config = &Config{}
  1040. if err := json.Unmarshal([]byte(*flConfig), config); err != nil {
  1041. return err
  1042. }
  1043. }
  1044. body, _, err := cli.call("POST", "/commit?"+v.Encode(), config)
  1045. if err != nil {
  1046. return err
  1047. }
  1048. apiID := &APIID{}
  1049. err = json.Unmarshal(body, apiID)
  1050. if err != nil {
  1051. return err
  1052. }
  1053. fmt.Fprintf(cli.out, "%s\n", apiID.ID)
  1054. return nil
  1055. }
  1056. func (cli *DockerCli) CmdEvents(args ...string) error {
  1057. cmd := Subcmd("events", "[OPTIONS]", "Get real time events from the server")
  1058. since := cmd.String("since", "", "Show events previously created (used for polling).")
  1059. if err := cmd.Parse(args); err != nil {
  1060. return nil
  1061. }
  1062. if cmd.NArg() != 0 {
  1063. cmd.Usage()
  1064. return nil
  1065. }
  1066. v := url.Values{}
  1067. if *since != "" {
  1068. v.Set("since", *since)
  1069. }
  1070. if err := cli.stream("GET", "/events?"+v.Encode(), nil, cli.out, nil); err != nil {
  1071. return err
  1072. }
  1073. return nil
  1074. }
  1075. func (cli *DockerCli) CmdExport(args ...string) error {
  1076. cmd := Subcmd("export", "CONTAINER", "Export the contents of a filesystem as a tar archive")
  1077. if err := cmd.Parse(args); err != nil {
  1078. return nil
  1079. }
  1080. if cmd.NArg() != 1 {
  1081. cmd.Usage()
  1082. return nil
  1083. }
  1084. if err := cli.stream("GET", "/containers/"+cmd.Arg(0)+"/export", nil, cli.out, nil); err != nil {
  1085. return err
  1086. }
  1087. return nil
  1088. }
  1089. func (cli *DockerCli) CmdDiff(args ...string) error {
  1090. cmd := Subcmd("diff", "CONTAINER", "Inspect changes on a container's filesystem")
  1091. if err := cmd.Parse(args); err != nil {
  1092. return nil
  1093. }
  1094. if cmd.NArg() != 1 {
  1095. cmd.Usage()
  1096. return nil
  1097. }
  1098. body, _, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/changes", nil)
  1099. if err != nil {
  1100. return err
  1101. }
  1102. changes := []Change{}
  1103. err = json.Unmarshal(body, &changes)
  1104. if err != nil {
  1105. return err
  1106. }
  1107. for _, change := range changes {
  1108. fmt.Fprintf(cli.out, "%s\n", change.String())
  1109. }
  1110. return nil
  1111. }
  1112. func (cli *DockerCli) CmdLogs(args ...string) error {
  1113. cmd := Subcmd("logs", "CONTAINER", "Fetch the logs of a container")
  1114. if err := cmd.Parse(args); err != nil {
  1115. return nil
  1116. }
  1117. if cmd.NArg() != 1 {
  1118. cmd.Usage()
  1119. return nil
  1120. }
  1121. if err := cli.hijack("POST", "/containers/"+cmd.Arg(0)+"/attach?logs=1&stdout=1&stderr=1", false, nil, cli.out, cli.err); err != nil {
  1122. return err
  1123. }
  1124. return nil
  1125. }
  1126. func (cli *DockerCli) CmdAttach(args ...string) error {
  1127. cmd := Subcmd("attach", "CONTAINER", "Attach to a running container")
  1128. if err := cmd.Parse(args); err != nil {
  1129. return nil
  1130. }
  1131. if cmd.NArg() != 1 {
  1132. cmd.Usage()
  1133. return nil
  1134. }
  1135. body, _, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/json", nil)
  1136. if err != nil {
  1137. return err
  1138. }
  1139. container := &Container{}
  1140. err = json.Unmarshal(body, container)
  1141. if err != nil {
  1142. return err
  1143. }
  1144. if !container.State.Running {
  1145. return fmt.Errorf("Impossible to attach to a stopped container, start it first")
  1146. }
  1147. if container.Config.Tty {
  1148. if err := cli.monitorTtySize(cmd.Arg(0)); err != nil {
  1149. utils.Debugf("Error monitoring tty size: %s", err)
  1150. }
  1151. }
  1152. v := url.Values{}
  1153. v.Set("stream", "1")
  1154. v.Set("stdin", "1")
  1155. v.Set("stdout", "1")
  1156. v.Set("stderr", "1")
  1157. if err := cli.hijack("POST", "/containers/"+cmd.Arg(0)+"/attach?"+v.Encode(), container.Config.Tty, cli.in, cli.out, cli.err); err != nil {
  1158. return err
  1159. }
  1160. return nil
  1161. }
  1162. func (cli *DockerCli) CmdSearch(args ...string) error {
  1163. cmd := Subcmd("search", "NAME", "Search the docker index for images")
  1164. noTrunc := cmd.Bool("notrunc", false, "Don't truncate output")
  1165. if err := cmd.Parse(args); err != nil {
  1166. return nil
  1167. }
  1168. if cmd.NArg() != 1 {
  1169. cmd.Usage()
  1170. return nil
  1171. }
  1172. v := url.Values{}
  1173. v.Set("term", cmd.Arg(0))
  1174. body, _, err := cli.call("GET", "/images/search?"+v.Encode(), nil)
  1175. if err != nil {
  1176. return err
  1177. }
  1178. outs := []APISearch{}
  1179. err = json.Unmarshal(body, &outs)
  1180. if err != nil {
  1181. return err
  1182. }
  1183. fmt.Fprintf(cli.out, "Found %d results matching your query (\"%s\")\n", len(outs), cmd.Arg(0))
  1184. w := tabwriter.NewWriter(cli.out, 33, 1, 3, ' ', 0)
  1185. fmt.Fprintf(w, "NAME\tDESCRIPTION\n")
  1186. _, width := cli.getTtySize()
  1187. if width == 0 {
  1188. width = 45
  1189. } else {
  1190. width = width - 33 //remote the first column
  1191. }
  1192. for _, out := range outs {
  1193. desc := strings.Replace(out.Description, "\n", " ", -1)
  1194. desc = strings.Replace(desc, "\r", " ", -1)
  1195. if !*noTrunc && len(desc) > width {
  1196. desc = utils.Trunc(desc, width-3) + "..."
  1197. }
  1198. fmt.Fprintf(w, "%s\t%s\n", out.Name, desc)
  1199. }
  1200. w.Flush()
  1201. return nil
  1202. }
  1203. // Ports type - Used to parse multiple -p flags
  1204. type ports []int
  1205. // ListOpts type
  1206. type ListOpts []string
  1207. func (opts *ListOpts) String() string {
  1208. return fmt.Sprint(*opts)
  1209. }
  1210. func (opts *ListOpts) Set(value string) error {
  1211. *opts = append(*opts, value)
  1212. return nil
  1213. }
  1214. // AttachOpts stores arguments to 'docker run -a', eg. which streams to attach to
  1215. type AttachOpts map[string]bool
  1216. func NewAttachOpts() AttachOpts {
  1217. return make(AttachOpts)
  1218. }
  1219. func (opts AttachOpts) String() string {
  1220. // Cast to underlying map type to avoid infinite recursion
  1221. return fmt.Sprintf("%v", map[string]bool(opts))
  1222. }
  1223. func (opts AttachOpts) Set(val string) error {
  1224. if val != "stdin" && val != "stdout" && val != "stderr" {
  1225. return fmt.Errorf("Unsupported stream name: %s", val)
  1226. }
  1227. opts[val] = true
  1228. return nil
  1229. }
  1230. func (opts AttachOpts) Get(val string) bool {
  1231. if res, exists := opts[val]; exists {
  1232. return res
  1233. }
  1234. return false
  1235. }
  1236. // PathOpts stores a unique set of absolute paths
  1237. type PathOpts map[string]struct{}
  1238. func NewPathOpts() PathOpts {
  1239. return make(PathOpts)
  1240. }
  1241. func (opts PathOpts) String() string {
  1242. return fmt.Sprintf("%v", map[string]struct{}(opts))
  1243. }
  1244. func (opts PathOpts) Set(val string) error {
  1245. var containerPath string
  1246. splited := strings.SplitN(val, ":", 2)
  1247. if len(splited) == 1 {
  1248. containerPath = splited[0]
  1249. val = filepath.Clean(splited[0])
  1250. } else {
  1251. containerPath = splited[1]
  1252. val = fmt.Sprintf("%s:%s", splited[0], filepath.Clean(splited[1]))
  1253. }
  1254. if !filepath.IsAbs(containerPath) {
  1255. utils.Debugf("%s is not an absolute path", containerPath)
  1256. return fmt.Errorf("%s is not an absolute path", containerPath)
  1257. }
  1258. opts[val] = struct{}{}
  1259. return nil
  1260. }
  1261. func (cli *DockerCli) CmdTag(args ...string) error {
  1262. cmd := Subcmd("tag", "[OPTIONS] IMAGE REPOSITORY [TAG]", "Tag an image into a repository")
  1263. force := cmd.Bool("f", false, "Force")
  1264. if err := cmd.Parse(args); err != nil {
  1265. return nil
  1266. }
  1267. if cmd.NArg() != 2 && cmd.NArg() != 3 {
  1268. cmd.Usage()
  1269. return nil
  1270. }
  1271. v := url.Values{}
  1272. v.Set("repo", cmd.Arg(1))
  1273. if cmd.NArg() == 3 {
  1274. v.Set("tag", cmd.Arg(2))
  1275. }
  1276. if *force {
  1277. v.Set("force", "1")
  1278. }
  1279. if _, _, err := cli.call("POST", "/images/"+cmd.Arg(0)+"/tag?"+v.Encode(), nil); err != nil {
  1280. return err
  1281. }
  1282. return nil
  1283. }
  1284. func (cli *DockerCli) CmdRun(args ...string) error {
  1285. config, hostConfig, cmd, err := ParseRun(args, nil)
  1286. if err != nil {
  1287. return err
  1288. }
  1289. if config.Image == "" {
  1290. cmd.Usage()
  1291. return nil
  1292. }
  1293. flRm := cmd.Lookup("rm")
  1294. autoRemove, _ := strconv.ParseBool(flRm.Value.String())
  1295. var containerIDFile *os.File
  1296. if len(hostConfig.ContainerIDFile) > 0 {
  1297. if _, err := ioutil.ReadFile(hostConfig.ContainerIDFile); err == nil {
  1298. return fmt.Errorf("cid file found, make sure the other container isn't running or delete %s", hostConfig.ContainerIDFile)
  1299. }
  1300. containerIDFile, err = os.Create(hostConfig.ContainerIDFile)
  1301. if err != nil {
  1302. return fmt.Errorf("failed to create the container ID file: %s", err)
  1303. }
  1304. defer containerIDFile.Close()
  1305. }
  1306. //create the container
  1307. body, statusCode, err := cli.call("POST", "/containers/create", config)
  1308. //if image not found try to pull it
  1309. if statusCode == 404 {
  1310. _, tag := utils.ParseRepositoryTag(config.Image)
  1311. if tag == "" {
  1312. tag = DEFAULTTAG
  1313. }
  1314. fmt.Fprintf(cli.err, "Unable to find image '%s' (tag: %s) locally\n", config.Image, tag)
  1315. v := url.Values{}
  1316. repos, tag := utils.ParseRepositoryTag(config.Image)
  1317. v.Set("fromImage", repos)
  1318. v.Set("tag", tag)
  1319. // Resolve the Repository name from fqn to endpoint + name
  1320. var endpoint string
  1321. endpoint, _, err = registry.ResolveRepositoryName(repos)
  1322. if err != nil {
  1323. return err
  1324. }
  1325. // Load the auth config file, to be able to pull the image
  1326. cli.LoadConfigFile()
  1327. // Resolve the Auth config relevant for this server
  1328. authConfig := cli.configFile.ResolveAuthConfig(endpoint)
  1329. buf, err := json.Marshal(authConfig)
  1330. if err != nil {
  1331. return err
  1332. }
  1333. registryAuthHeader := []string{
  1334. base64.URLEncoding.EncodeToString(buf),
  1335. }
  1336. err = cli.stream("POST", "/images/create?"+v.Encode(), nil, cli.err, map[string][]string{
  1337. "X-Registry-Auth": registryAuthHeader,
  1338. })
  1339. if err != nil {
  1340. return err
  1341. }
  1342. body, _, err = cli.call("POST", "/containers/create", config)
  1343. if err != nil {
  1344. return err
  1345. }
  1346. }
  1347. if err != nil {
  1348. return err
  1349. }
  1350. runResult := &APIRun{}
  1351. err = json.Unmarshal(body, runResult)
  1352. if err != nil {
  1353. return err
  1354. }
  1355. for _, warning := range runResult.Warnings {
  1356. fmt.Fprintf(cli.err, "WARNING: %s\n", warning)
  1357. }
  1358. if len(hostConfig.ContainerIDFile) > 0 {
  1359. if _, err = containerIDFile.WriteString(runResult.ID); err != nil {
  1360. return fmt.Errorf("failed to write the container ID to the file: %s", err)
  1361. }
  1362. }
  1363. //start the container
  1364. if _, _, err = cli.call("POST", "/containers/"+runResult.ID+"/start", hostConfig); err != nil {
  1365. return err
  1366. }
  1367. var wait chan struct{}
  1368. if !config.AttachStdout && !config.AttachStderr {
  1369. // Make this asynchrone in order to let the client write to stdin before having to read the ID
  1370. wait = make(chan struct{})
  1371. go func() {
  1372. defer close(wait)
  1373. fmt.Fprintf(cli.out, "%s\n", runResult.ID)
  1374. }()
  1375. }
  1376. if config.AttachStdin || config.AttachStdout || config.AttachStderr {
  1377. if config.Tty {
  1378. if err := cli.monitorTtySize(runResult.ID); err != nil {
  1379. utils.Errorf("Error monitoring TTY size: %s\n", err)
  1380. }
  1381. }
  1382. v := url.Values{}
  1383. v.Set("logs", "1")
  1384. v.Set("stream", "1")
  1385. var out, stderr io.Writer
  1386. if config.AttachStdin {
  1387. v.Set("stdin", "1")
  1388. }
  1389. if config.AttachStdout {
  1390. v.Set("stdout", "1")
  1391. out = cli.out
  1392. }
  1393. if config.AttachStderr {
  1394. v.Set("stderr", "1")
  1395. if config.Tty {
  1396. stderr = cli.out
  1397. } else {
  1398. stderr = cli.err
  1399. }
  1400. }
  1401. signals := make(chan os.Signal, 1)
  1402. signal.Notify(signals, syscall.SIGINT, syscall.SIGTERM)
  1403. go func() {
  1404. for sig := range signals {
  1405. fmt.Printf("\nReceived signal: %s; cleaning up\n", sig)
  1406. if err := cli.CmdStop("-t", "4", runResult.ID); err != nil {
  1407. fmt.Printf("failed to stop container: %v", err)
  1408. }
  1409. }
  1410. }()
  1411. if err := cli.hijack("POST", "/containers/"+runResult.ID+"/attach?"+v.Encode(), config.Tty, cli.in, out, stderr); err != nil {
  1412. utils.Debugf("Error hijack: %s", err)
  1413. return err
  1414. }
  1415. }
  1416. if !config.AttachStdout && !config.AttachStderr {
  1417. // Detached mode
  1418. <-wait
  1419. } else {
  1420. status, err := getExitCode(cli, runResult.ID)
  1421. if err != nil {
  1422. return err
  1423. }
  1424. if autoRemove {
  1425. _, _, err = cli.call("DELETE", "/containers/"+runResult.ID, nil)
  1426. if err != nil {
  1427. return err
  1428. }
  1429. }
  1430. if status != 0 {
  1431. return &utils.StatusError{Status: status}
  1432. }
  1433. }
  1434. return nil
  1435. }
  1436. func (cli *DockerCli) CmdCp(args ...string) error {
  1437. cmd := Subcmd("cp", "CONTAINER:RESOURCE HOSTPATH", "Copy files/folders from the RESOURCE to the HOSTPATH")
  1438. if err := cmd.Parse(args); err != nil {
  1439. return nil
  1440. }
  1441. if cmd.NArg() != 2 {
  1442. cmd.Usage()
  1443. return nil
  1444. }
  1445. var copyData APICopy
  1446. info := strings.Split(cmd.Arg(0), ":")
  1447. if len(info) != 2 {
  1448. return fmt.Errorf("Error: Resource not specified")
  1449. }
  1450. copyData.Resource = info[1]
  1451. copyData.HostPath = cmd.Arg(1)
  1452. data, statusCode, err := cli.call("POST", "/containers/"+info[0]+"/copy", copyData)
  1453. if err != nil {
  1454. return err
  1455. }
  1456. if statusCode == 200 {
  1457. r := bytes.NewReader(data)
  1458. if err := Untar(r, copyData.HostPath); err != nil {
  1459. return err
  1460. }
  1461. }
  1462. return nil
  1463. }
  1464. func (cli *DockerCli) call(method, path string, data interface{}) ([]byte, int, error) {
  1465. var params io.Reader
  1466. if data != nil {
  1467. buf, err := json.Marshal(data)
  1468. if err != nil {
  1469. return nil, -1, err
  1470. }
  1471. params = bytes.NewBuffer(buf)
  1472. }
  1473. req, err := http.NewRequest(method, fmt.Sprintf("/v%g%s", APIVERSION, path), params)
  1474. if err != nil {
  1475. return nil, -1, err
  1476. }
  1477. req.Header.Set("User-Agent", "Docker-Client/"+VERSION)
  1478. req.Host = cli.addr
  1479. if data != nil {
  1480. req.Header.Set("Content-Type", "application/json")
  1481. } else if method == "POST" {
  1482. req.Header.Set("Content-Type", "plain/text")
  1483. }
  1484. dial, err := net.Dial(cli.proto, cli.addr)
  1485. if err != nil {
  1486. if strings.Contains(err.Error(), "connection refused") {
  1487. return nil, -1, ErrConnectionRefused
  1488. }
  1489. return nil, -1, err
  1490. }
  1491. clientconn := httputil.NewClientConn(dial, nil)
  1492. resp, err := clientconn.Do(req)
  1493. defer clientconn.Close()
  1494. if err != nil {
  1495. if strings.Contains(err.Error(), "connection refused") {
  1496. return nil, -1, ErrConnectionRefused
  1497. }
  1498. return nil, -1, err
  1499. }
  1500. defer resp.Body.Close()
  1501. body, err := ioutil.ReadAll(resp.Body)
  1502. if err != nil {
  1503. return nil, -1, err
  1504. }
  1505. if resp.StatusCode < 200 || resp.StatusCode >= 400 {
  1506. if len(body) == 0 {
  1507. return nil, resp.StatusCode, fmt.Errorf("Error: %s", http.StatusText(resp.StatusCode))
  1508. }
  1509. return nil, resp.StatusCode, fmt.Errorf("Error: %s", body)
  1510. }
  1511. return body, resp.StatusCode, nil
  1512. }
  1513. func (cli *DockerCli) stream(method, path string, in io.Reader, out io.Writer, headers map[string][]string) error {
  1514. if (method == "POST" || method == "PUT") && in == nil {
  1515. in = bytes.NewReader([]byte{})
  1516. }
  1517. req, err := http.NewRequest(method, fmt.Sprintf("/v%g%s", APIVERSION, path), in)
  1518. if err != nil {
  1519. return err
  1520. }
  1521. req.Header.Set("User-Agent", "Docker-Client/"+VERSION)
  1522. req.Host = cli.addr
  1523. if method == "POST" {
  1524. req.Header.Set("Content-Type", "plain/text")
  1525. }
  1526. if headers != nil {
  1527. for k, v := range headers {
  1528. req.Header[k] = v
  1529. }
  1530. }
  1531. dial, err := net.Dial(cli.proto, cli.addr)
  1532. if err != nil {
  1533. if strings.Contains(err.Error(), "connection refused") {
  1534. return fmt.Errorf("Can't connect to docker daemon. Is 'docker -d' running on this host?")
  1535. }
  1536. return err
  1537. }
  1538. clientconn := httputil.NewClientConn(dial, nil)
  1539. resp, err := clientconn.Do(req)
  1540. defer clientconn.Close()
  1541. if err != nil {
  1542. if strings.Contains(err.Error(), "connection refused") {
  1543. return fmt.Errorf("Can't connect to docker daemon. Is 'docker -d' running on this host?")
  1544. }
  1545. return err
  1546. }
  1547. defer resp.Body.Close()
  1548. if resp.StatusCode < 200 || resp.StatusCode >= 400 {
  1549. body, err := ioutil.ReadAll(resp.Body)
  1550. if err != nil {
  1551. return err
  1552. }
  1553. if len(body) == 0 {
  1554. return fmt.Errorf("Error :%s", http.StatusText(resp.StatusCode))
  1555. }
  1556. return fmt.Errorf("Error: %s", body)
  1557. }
  1558. if matchesContentType(resp.Header.Get("Content-Type"), "application/json") {
  1559. return utils.DisplayJSONMessagesStream(resp.Body, out)
  1560. } else {
  1561. if _, err := io.Copy(out, resp.Body); err != nil {
  1562. return err
  1563. }
  1564. }
  1565. return nil
  1566. }
  1567. func (cli *DockerCli) hijack(method, path string, setRawTerminal bool, in io.ReadCloser, stdout, stderr io.Writer) error {
  1568. req, err := http.NewRequest(method, fmt.Sprintf("/v%g%s", APIVERSION, path), nil)
  1569. if err != nil {
  1570. return err
  1571. }
  1572. req.Header.Set("User-Agent", "Docker-Client/"+VERSION)
  1573. req.Header.Set("Content-Type", "plain/text")
  1574. req.Host = cli.addr
  1575. dial, err := net.Dial(cli.proto, cli.addr)
  1576. if err != nil {
  1577. if strings.Contains(err.Error(), "connection refused") {
  1578. return fmt.Errorf("Can't connect to docker daemon. Is 'docker -d' running on this host?")
  1579. }
  1580. return err
  1581. }
  1582. clientconn := httputil.NewClientConn(dial, nil)
  1583. defer clientconn.Close()
  1584. // Server hijacks the connection, error 'connection closed' expected
  1585. clientconn.Do(req)
  1586. rwc, br := clientconn.Hijack()
  1587. defer rwc.Close()
  1588. var receiveStdout chan error
  1589. if stdout != nil {
  1590. receiveStdout = utils.Go(func() (err error) {
  1591. // When TTY is ON, use regular copy
  1592. if setRawTerminal {
  1593. _, err = io.Copy(stdout, br)
  1594. } else {
  1595. _, err = utils.StdCopy(stdout, stderr, br)
  1596. }
  1597. utils.Debugf("[hijack] End of stdout")
  1598. return err
  1599. })
  1600. }
  1601. if in != nil && setRawTerminal && cli.isTerminal && os.Getenv("NORAW") == "" {
  1602. oldState, err := term.SetRawTerminal(cli.terminalFd)
  1603. if err != nil {
  1604. return err
  1605. }
  1606. defer term.RestoreTerminal(cli.terminalFd, oldState)
  1607. }
  1608. sendStdin := utils.Go(func() error {
  1609. if in != nil {
  1610. io.Copy(rwc, in)
  1611. utils.Debugf("[hijack] End of stdin")
  1612. }
  1613. if tcpc, ok := rwc.(*net.TCPConn); ok {
  1614. if err := tcpc.CloseWrite(); err != nil {
  1615. utils.Errorf("Couldn't send EOF: %s\n", err)
  1616. }
  1617. } else if unixc, ok := rwc.(*net.UnixConn); ok {
  1618. if err := unixc.CloseWrite(); err != nil {
  1619. utils.Errorf("Couldn't send EOF: %s\n", err)
  1620. }
  1621. }
  1622. // Discard errors due to pipe interruption
  1623. return nil
  1624. })
  1625. if stdout != nil {
  1626. if err := <-receiveStdout; err != nil {
  1627. utils.Errorf("Error receiveStdout: %s", err)
  1628. return err
  1629. }
  1630. }
  1631. if !cli.isTerminal {
  1632. if err := <-sendStdin; err != nil {
  1633. utils.Errorf("Error sendStdin: %s", err)
  1634. return err
  1635. }
  1636. }
  1637. return nil
  1638. }
  1639. func (cli *DockerCli) getTtySize() (int, int) {
  1640. if !cli.isTerminal {
  1641. return 0, 0
  1642. }
  1643. ws, err := term.GetWinsize(cli.terminalFd)
  1644. if err != nil {
  1645. utils.Errorf("Error getting size: %s", err)
  1646. if ws == nil {
  1647. return 0, 0
  1648. }
  1649. }
  1650. return int(ws.Height), int(ws.Width)
  1651. }
  1652. func (cli *DockerCli) resizeTty(id string) {
  1653. height, width := cli.getTtySize()
  1654. if height == 0 && width == 0 {
  1655. return
  1656. }
  1657. v := url.Values{}
  1658. v.Set("h", strconv.Itoa(height))
  1659. v.Set("w", strconv.Itoa(width))
  1660. if _, _, err := cli.call("POST", "/containers/"+id+"/resize?"+v.Encode(), nil); err != nil {
  1661. utils.Errorf("Error resize: %s", err)
  1662. }
  1663. }
  1664. func (cli *DockerCli) monitorTtySize(id string) error {
  1665. if !cli.isTerminal {
  1666. return fmt.Errorf("Impossible to monitor size on non-tty")
  1667. }
  1668. cli.resizeTty(id)
  1669. sigchan := make(chan os.Signal, 1)
  1670. signal.Notify(sigchan, syscall.SIGWINCH)
  1671. go func() {
  1672. for _ = range sigchan {
  1673. cli.resizeTty(id)
  1674. }
  1675. }()
  1676. return nil
  1677. }
  1678. func Subcmd(name, signature, description string) *flag.FlagSet {
  1679. flags := flag.NewFlagSet(name, flag.ContinueOnError)
  1680. flags.Usage = func() {
  1681. // FIXME: use custom stdout or return error
  1682. fmt.Fprintf(os.Stdout, "\nUsage: docker %s %s\n\n%s\n\n", name, signature, description)
  1683. flags.PrintDefaults()
  1684. }
  1685. return flags
  1686. }
  1687. func (cli *DockerCli) LoadConfigFile() (err error) {
  1688. cli.configFile, err = auth.LoadConfig(os.Getenv("HOME"))
  1689. if err != nil {
  1690. fmt.Fprintf(cli.err, "WARNING: %s\n", err)
  1691. }
  1692. return err
  1693. }
  1694. func waitForExit(cli *DockerCli, containerId string) (int, error) {
  1695. body, _, err := cli.call("POST", "/containers/"+containerId+"/wait", nil)
  1696. if err != nil {
  1697. // If we can't connect, then the daemon probably died.
  1698. if err != ErrConnectionRefused {
  1699. return -1, err
  1700. }
  1701. return -1, nil
  1702. }
  1703. var out APIWait
  1704. if err := json.Unmarshal(body, &out); err != nil {
  1705. return -1, err
  1706. }
  1707. return out.StatusCode, nil
  1708. }
  1709. func getExitCode(cli *DockerCli, containerId string) (int, error) {
  1710. body, _, err := cli.call("GET", "/containers/"+containerId+"/json", nil)
  1711. if err != nil {
  1712. // If we can't connect, then the daemon probably died.
  1713. if err != ErrConnectionRefused {
  1714. return -1, err
  1715. }
  1716. return -1, nil
  1717. }
  1718. c := &Container{}
  1719. if err := json.Unmarshal(body, c); err != nil {
  1720. return -1, err
  1721. }
  1722. return c.State.ExitCode, nil
  1723. }
  1724. func NewDockerCli(in io.ReadCloser, out, err io.Writer, proto, addr string) *DockerCli {
  1725. var (
  1726. isTerminal = false
  1727. terminalFd uintptr
  1728. )
  1729. if in != nil {
  1730. if file, ok := in.(*os.File); ok {
  1731. terminalFd = file.Fd()
  1732. isTerminal = term.IsTerminal(terminalFd)
  1733. }
  1734. }
  1735. if err == nil {
  1736. err = out
  1737. }
  1738. return &DockerCli{
  1739. proto: proto,
  1740. addr: addr,
  1741. in: in,
  1742. out: out,
  1743. err: err,
  1744. isTerminal: isTerminal,
  1745. terminalFd: terminalFd,
  1746. }
  1747. }
  1748. type DockerCli struct {
  1749. proto string
  1750. addr string
  1751. configFile *auth.ConfigFile
  1752. in io.ReadCloser
  1753. out io.Writer
  1754. err io.Writer
  1755. isTerminal bool
  1756. terminalFd uintptr
  1757. }