cli.go 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  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. dopts "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. // Client returns the APIClient
  52. func (cli *DockerCli) Client() client.APIClient {
  53. return cli.client
  54. }
  55. // Out returns the writer used for stdout
  56. func (cli *DockerCli) Out() io.Writer {
  57. return cli.out
  58. }
  59. // Err returns the writer used for stderr
  60. func (cli *DockerCli) Err() io.Writer {
  61. return cli.err
  62. }
  63. // In returns the reader used for stdin
  64. func (cli *DockerCli) In() io.ReadCloser {
  65. return cli.in
  66. }
  67. // ConfigFile returns the ConfigFile
  68. func (cli *DockerCli) ConfigFile() *configfile.ConfigFile {
  69. return cli.configFile
  70. }
  71. // IsTerminalIn returns true if the clients stdin is a TTY
  72. func (cli *DockerCli) IsTerminalIn() bool {
  73. return cli.isTerminalIn
  74. }
  75. // IsTerminalOut returns true if the clients stdout is a TTY
  76. func (cli *DockerCli) IsTerminalOut() bool {
  77. return cli.isTerminalOut
  78. }
  79. // OutFd returns the fd for the stdout stream
  80. func (cli *DockerCli) OutFd() uintptr {
  81. return cli.outFd
  82. }
  83. // CheckTtyInput checks if we are trying to attach to a container tty
  84. // from a non-tty client input stream, and if so, returns an error.
  85. func (cli *DockerCli) CheckTtyInput(attachStdin, ttyMode bool) error {
  86. // In order to attach to a container tty, input stream for the client must
  87. // be a tty itself: redirecting or piping the client standard input is
  88. // incompatible with `docker run -t`, `docker exec -t` or `docker attach`.
  89. if ttyMode && attachStdin && !cli.isTerminalIn {
  90. eText := "the input device is not a TTY"
  91. if runtime.GOOS == "windows" {
  92. return errors.New(eText + ". If you are using mintty, try prefixing the command with 'winpty'")
  93. }
  94. return errors.New(eText)
  95. }
  96. return nil
  97. }
  98. func (cli *DockerCli) setRawTerminal() error {
  99. if os.Getenv("NORAW") == "" {
  100. if cli.isTerminalIn {
  101. state, err := term.SetRawTerminal(cli.inFd)
  102. if err != nil {
  103. return err
  104. }
  105. cli.inState = state
  106. }
  107. if cli.isTerminalOut {
  108. state, err := term.SetRawTerminalOutput(cli.outFd)
  109. if err != nil {
  110. return err
  111. }
  112. cli.outState = state
  113. }
  114. }
  115. return nil
  116. }
  117. func (cli *DockerCli) restoreTerminal(in io.Closer) error {
  118. if cli.inState != nil {
  119. term.RestoreTerminal(cli.inFd, cli.inState)
  120. }
  121. if cli.outState != nil {
  122. term.RestoreTerminal(cli.outFd, cli.outState)
  123. }
  124. // WARNING: DO NOT REMOVE THE OS CHECK !!!
  125. // For some reason this Close call blocks on darwin..
  126. // As the client exists right after, simply discard the close
  127. // until we find a better solution.
  128. if in != nil && runtime.GOOS != "darwin" {
  129. return in.Close()
  130. }
  131. return nil
  132. }
  133. // Initialize the dockerCli runs initialization that must happen after command
  134. // line flags are parsed.
  135. func (cli *DockerCli) Initialize(opts *cliflags.ClientOptions) error {
  136. cli.configFile = LoadDefaultConfigFile(cli.err)
  137. client, err := NewAPIClientFromFlags(opts.Common, cli.configFile)
  138. if err != nil {
  139. return err
  140. }
  141. cli.client = client
  142. if cli.in != nil {
  143. cli.inFd, cli.isTerminalIn = term.GetFdInfo(cli.in)
  144. }
  145. if cli.out != nil {
  146. cli.outFd, cli.isTerminalOut = term.GetFdInfo(cli.out)
  147. }
  148. return nil
  149. }
  150. // NewDockerCli returns a DockerCli instance with IO output and error streams set by in, out and err.
  151. // The key file, protocol (i.e. unix) and address are passed in as strings, along with the tls.Config. If the tls.Config
  152. // is set the client scheme will be set to https.
  153. // The client will be given a 32-second timeout (see https://github.com/docker/docker/pull/8035).
  154. func NewDockerCli(in io.ReadCloser, out, err io.Writer, clientOpts *cliflags.ClientOptions) *DockerCli {
  155. cli := &DockerCli{
  156. in: in,
  157. out: out,
  158. err: err,
  159. // TODO: just pass trustKey, not the entire opts struct
  160. keyFile: clientOpts.Common.TrustKey,
  161. }
  162. return cli
  163. }
  164. // LoadDefaultConfigFile attempts to load the default config file and returns
  165. // an initialized ConfigFile struct if none is found.
  166. func LoadDefaultConfigFile(err io.Writer) *configfile.ConfigFile {
  167. configFile, e := cliconfig.Load(cliconfig.ConfigDir())
  168. if e != nil {
  169. fmt.Fprintf(err, "WARNING: Error loading config file:%v\n", e)
  170. }
  171. if !configFile.ContainsAuth() {
  172. credentials.DetectDefaultStore(configFile)
  173. }
  174. return configFile
  175. }
  176. // NewAPIClientFromFlags creates a new APIClient from command line flags
  177. func NewAPIClientFromFlags(opts *cliflags.CommonOptions, configFile *configfile.ConfigFile) (client.APIClient, error) {
  178. host, err := getServerHost(opts.Hosts, opts.TLSOptions)
  179. if err != nil {
  180. return &client.Client{}, err
  181. }
  182. customHeaders := configFile.HTTPHeaders
  183. if customHeaders == nil {
  184. customHeaders = map[string]string{}
  185. }
  186. customHeaders["User-Agent"] = clientUserAgent()
  187. verStr := api.DefaultVersion
  188. if tmpStr := os.Getenv("DOCKER_API_VERSION"); tmpStr != "" {
  189. verStr = tmpStr
  190. }
  191. httpClient, err := newHTTPClient(host, opts.TLSOptions)
  192. if err != nil {
  193. return &client.Client{}, err
  194. }
  195. return client.NewClient(host, verStr, httpClient, customHeaders)
  196. }
  197. func getServerHost(hosts []string, tlsOptions *tlsconfig.Options) (host string, err error) {
  198. switch len(hosts) {
  199. case 0:
  200. host = os.Getenv("DOCKER_HOST")
  201. case 1:
  202. host = hosts[0]
  203. default:
  204. return "", errors.New("Please specify only one -H")
  205. }
  206. host, err = dopts.ParseHost(tlsOptions != nil, host)
  207. return
  208. }
  209. func newHTTPClient(host string, tlsOptions *tlsconfig.Options) (*http.Client, error) {
  210. if tlsOptions == nil {
  211. // let the api client configure the default transport.
  212. return nil, nil
  213. }
  214. config, err := tlsconfig.Client(*tlsOptions)
  215. if err != nil {
  216. return nil, err
  217. }
  218. tr := &http.Transport{
  219. TLSClientConfig: config,
  220. }
  221. proto, addr, _, err := client.ParseHost(host)
  222. if err != nil {
  223. return nil, err
  224. }
  225. sockets.ConfigureTransport(tr, proto, addr)
  226. return &http.Client{
  227. Transport: tr,
  228. }, nil
  229. }
  230. func clientUserAgent() string {
  231. return "Docker-Client/" + dockerversion.Version + " (" + runtime.GOOS + ")"
  232. }