cli.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. package client
  2. import (
  3. "errors"
  4. "fmt"
  5. "io"
  6. "net/http"
  7. "os"
  8. "runtime"
  9. "github.com/docker/docker/api"
  10. cliflags "github.com/docker/docker/cli/flags"
  11. "github.com/docker/docker/cliconfig"
  12. "github.com/docker/docker/cliconfig/configfile"
  13. "github.com/docker/docker/cliconfig/credentials"
  14. "github.com/docker/docker/dockerversion"
  15. "github.com/docker/docker/opts"
  16. "github.com/docker/docker/pkg/term"
  17. "github.com/docker/engine-api/client"
  18. "github.com/docker/go-connections/sockets"
  19. "github.com/docker/go-connections/tlsconfig"
  20. )
  21. // DockerCli represents the docker command line client.
  22. // Instances of the client can be returned from NewDockerCli.
  23. type DockerCli struct {
  24. // initializing closure
  25. init func() error
  26. // configFile has the client configuration file
  27. configFile *configfile.ConfigFile
  28. // in holds the input stream and closer (io.ReadCloser) for the client.
  29. in io.ReadCloser
  30. // out holds the output stream (io.Writer) for the client.
  31. out io.Writer
  32. // err holds the error stream (io.Writer) for the client.
  33. err io.Writer
  34. // keyFile holds the key file as a string.
  35. keyFile string
  36. // inFd holds the file descriptor of the client's STDIN (if valid).
  37. inFd uintptr
  38. // outFd holds file descriptor of the client's STDOUT (if valid).
  39. outFd uintptr
  40. // isTerminalIn indicates whether the client's STDIN is a TTY
  41. isTerminalIn bool
  42. // isTerminalOut indicates whether the client's STDOUT is a TTY
  43. isTerminalOut bool
  44. // client is the http client that performs all API operations
  45. client client.APIClient
  46. // state holds the terminal input state
  47. inState *term.State
  48. // outState holds the terminal output state
  49. outState *term.State
  50. }
  51. // Initialize calls the init function that will setup the configuration for the client
  52. // such as the TLS, tcp and other parameters used to run the client.
  53. func (cli *DockerCli) Initialize() error {
  54. if cli.init == nil {
  55. return nil
  56. }
  57. return cli.init()
  58. }
  59. // Client returns the APIClient
  60. func (cli *DockerCli) Client() client.APIClient {
  61. return cli.client
  62. }
  63. // Out returns the writer used for stdout
  64. func (cli *DockerCli) Out() io.Writer {
  65. return cli.out
  66. }
  67. // Err returns the writer used for stderr
  68. func (cli *DockerCli) Err() io.Writer {
  69. return cli.err
  70. }
  71. // In returns the reader used for stdin
  72. func (cli *DockerCli) In() io.ReadCloser {
  73. return cli.in
  74. }
  75. // ConfigFile returns the ConfigFile
  76. func (cli *DockerCli) ConfigFile() *configfile.ConfigFile {
  77. return cli.configFile
  78. }
  79. // IsTerminalIn returns true if the clients stdin is a TTY
  80. func (cli *DockerCli) IsTerminalIn() bool {
  81. return cli.isTerminalIn
  82. }
  83. // IsTerminalOut returns true if the clients stdout is a TTY
  84. func (cli *DockerCli) IsTerminalOut() bool {
  85. return cli.isTerminalOut
  86. }
  87. // OutFd returns the fd for the stdout stream
  88. func (cli *DockerCli) OutFd() uintptr {
  89. return cli.outFd
  90. }
  91. // CheckTtyInput checks if we are trying to attach to a container tty
  92. // from a non-tty client input stream, and if so, returns an error.
  93. func (cli *DockerCli) CheckTtyInput(attachStdin, ttyMode bool) error {
  94. // In order to attach to a container tty, input stream for the client must
  95. // be a tty itself: redirecting or piping the client standard input is
  96. // incompatible with `docker run -t`, `docker exec -t` or `docker attach`.
  97. if ttyMode && attachStdin && !cli.isTerminalIn {
  98. eText := "the input device is not a TTY"
  99. if runtime.GOOS == "windows" {
  100. return errors.New(eText + ". If you are using mintty, try prefixing the command with 'winpty'")
  101. }
  102. return errors.New(eText)
  103. }
  104. return nil
  105. }
  106. // PsFormat returns the format string specified in the configuration.
  107. // String contains columns and format specification, for example {{ID}}\t{{Name}}.
  108. func (cli *DockerCli) PsFormat() string {
  109. return cli.configFile.PsFormat
  110. }
  111. // ImagesFormat returns the format string specified in the configuration.
  112. // String contains columns and format specification, for example {{ID}}\t{{Name}}.
  113. func (cli *DockerCli) ImagesFormat() string {
  114. return cli.configFile.ImagesFormat
  115. }
  116. // NetworksFormat returns the format string specified in the configuration.
  117. // String contains columns and format specification, for example {{ID}}\t{{Name}}
  118. func (cli *DockerCli) NetworksFormat() string {
  119. return cli.configFile.NetworksFormat
  120. }
  121. func (cli *DockerCli) setRawTerminal() error {
  122. if os.Getenv("NORAW") == "" {
  123. if cli.isTerminalIn {
  124. state, err := term.SetRawTerminal(cli.inFd)
  125. if err != nil {
  126. return err
  127. }
  128. cli.inState = state
  129. }
  130. if cli.isTerminalOut {
  131. state, err := term.SetRawTerminalOutput(cli.outFd)
  132. if err != nil {
  133. return err
  134. }
  135. cli.outState = state
  136. }
  137. }
  138. return nil
  139. }
  140. func (cli *DockerCli) restoreTerminal(in io.Closer) error {
  141. if cli.inState != nil {
  142. term.RestoreTerminal(cli.inFd, cli.inState)
  143. }
  144. if cli.outState != nil {
  145. term.RestoreTerminal(cli.outFd, cli.outState)
  146. }
  147. // WARNING: DO NOT REMOVE THE OS CHECK !!!
  148. // For some reason this Close call blocks on darwin..
  149. // As the client exists right after, simply discard the close
  150. // until we find a better solution.
  151. if in != nil && runtime.GOOS != "darwin" {
  152. return in.Close()
  153. }
  154. return nil
  155. }
  156. // NewDockerCli returns a DockerCli instance with IO output and error streams set by in, out and err.
  157. // The key file, protocol (i.e. unix) and address are passed in as strings, along with the tls.Config. If the tls.Config
  158. // is set the client scheme will be set to https.
  159. // The client will be given a 32-second timeout (see https://github.com/docker/docker/pull/8035).
  160. func NewDockerCli(in io.ReadCloser, out, err io.Writer, clientFlags *cliflags.ClientFlags) *DockerCli {
  161. cli := &DockerCli{
  162. in: in,
  163. out: out,
  164. err: err,
  165. keyFile: clientFlags.Common.TrustKey,
  166. }
  167. cli.init = func() error {
  168. clientFlags.PostParse()
  169. cli.configFile = LoadDefaultConfigFile(err)
  170. client, err := NewAPIClientFromFlags(clientFlags, cli.configFile)
  171. if err != nil {
  172. return err
  173. }
  174. cli.client = client
  175. if cli.in != nil {
  176. cli.inFd, cli.isTerminalIn = term.GetFdInfo(cli.in)
  177. }
  178. if cli.out != nil {
  179. cli.outFd, cli.isTerminalOut = term.GetFdInfo(cli.out)
  180. }
  181. return nil
  182. }
  183. return cli
  184. }
  185. // LoadDefaultConfigFile attempts to load the default config file and returns
  186. // an initialized ConfigFile struct if none is found.
  187. func LoadDefaultConfigFile(err io.Writer) *configfile.ConfigFile {
  188. configFile, e := cliconfig.Load(cliconfig.ConfigDir())
  189. if e != nil {
  190. fmt.Fprintf(err, "WARNING: Error loading config file:%v\n", e)
  191. }
  192. if !configFile.ContainsAuth() {
  193. credentials.DetectDefaultStore(configFile)
  194. }
  195. return configFile
  196. }
  197. // NewAPIClientFromFlags creates a new APIClient from command line flags
  198. func NewAPIClientFromFlags(clientFlags *cliflags.ClientFlags, configFile *configfile.ConfigFile) (client.APIClient, error) {
  199. host, err := getServerHost(clientFlags.Common.Hosts, clientFlags.Common.TLSOptions)
  200. if err != nil {
  201. return &client.Client{}, err
  202. }
  203. customHeaders := configFile.HTTPHeaders
  204. if customHeaders == nil {
  205. customHeaders = map[string]string{}
  206. }
  207. customHeaders["User-Agent"] = clientUserAgent()
  208. verStr := api.DefaultVersion
  209. if tmpStr := os.Getenv("DOCKER_API_VERSION"); tmpStr != "" {
  210. verStr = tmpStr
  211. }
  212. httpClient, err := newHTTPClient(host, clientFlags.Common.TLSOptions)
  213. if err != nil {
  214. return &client.Client{}, err
  215. }
  216. return client.NewClient(host, verStr, httpClient, customHeaders)
  217. }
  218. func getServerHost(hosts []string, tlsOptions *tlsconfig.Options) (host string, err error) {
  219. switch len(hosts) {
  220. case 0:
  221. host = os.Getenv("DOCKER_HOST")
  222. case 1:
  223. host = hosts[0]
  224. default:
  225. return "", errors.New("Please specify only one -H")
  226. }
  227. host, err = opts.ParseHost(tlsOptions != nil, host)
  228. return
  229. }
  230. func newHTTPClient(host string, tlsOptions *tlsconfig.Options) (*http.Client, error) {
  231. if tlsOptions == nil {
  232. // let the api client configure the default transport.
  233. return nil, nil
  234. }
  235. config, err := tlsconfig.Client(*tlsOptions)
  236. if err != nil {
  237. return nil, err
  238. }
  239. tr := &http.Transport{
  240. TLSClientConfig: config,
  241. }
  242. proto, addr, _, err := client.ParseHost(host)
  243. if err != nil {
  244. return nil, err
  245. }
  246. sockets.ConfigureTransport(tr, proto, addr)
  247. return &http.Client{
  248. Transport: tr,
  249. }, nil
  250. }
  251. func clientUserAgent() string {
  252. return "Docker-Client/" + dockerversion.Version + " (" + runtime.GOOS + ")"
  253. }