cli.go 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  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 state
  47. state *term.State
  48. }
  49. // Initialize calls the init function that will setup the configuration for the client
  50. // such as the TLS, tcp and other parameters used to run the client.
  51. func (cli *DockerCli) Initialize() error {
  52. if cli.init == nil {
  53. return nil
  54. }
  55. return cli.init()
  56. }
  57. // CheckTtyInput checks if we are trying to attach to a container tty
  58. // from a non-tty client input stream, and if so, returns an error.
  59. func (cli *DockerCli) CheckTtyInput(attachStdin, ttyMode bool) error {
  60. // In order to attach to a container tty, input stream for the client must
  61. // be a tty itself: redirecting or piping the client standard input is
  62. // incompatible with `docker run -t`, `docker exec -t` or `docker attach`.
  63. if ttyMode && attachStdin && !cli.isTerminalIn {
  64. eText := "the input device is not a TTY"
  65. if runtime.GOOS == "windows" {
  66. return errors.New(eText + ". If you are using mintty, try prefixing the command with 'winpty'")
  67. }
  68. return errors.New(eText)
  69. }
  70. return nil
  71. }
  72. // PsFormat returns the format string specified in the configuration.
  73. // String contains columns and format specification, for example {{ID}}\t{{Name}}.
  74. func (cli *DockerCli) PsFormat() string {
  75. return cli.configFile.PsFormat
  76. }
  77. // ImagesFormat returns the format string specified in the configuration.
  78. // String contains columns and format specification, for example {{ID}}\t{{Name}}.
  79. func (cli *DockerCli) ImagesFormat() string {
  80. return cli.configFile.ImagesFormat
  81. }
  82. func (cli *DockerCli) setRawTerminal() error {
  83. if cli.isTerminalIn && os.Getenv("NORAW") == "" {
  84. state, err := term.SetRawTerminal(cli.inFd)
  85. if err != nil {
  86. return err
  87. }
  88. cli.state = state
  89. }
  90. return nil
  91. }
  92. func (cli *DockerCli) restoreTerminal(in io.Closer) error {
  93. if cli.state != nil {
  94. term.RestoreTerminal(cli.inFd, cli.state)
  95. }
  96. // WARNING: DO NOT REMOVE THE OS CHECK !!!
  97. // For some reason this Close call blocks on darwin..
  98. // As the client exists right after, simply discard the close
  99. // until we find a better solution.
  100. if in != nil && runtime.GOOS != "darwin" {
  101. return in.Close()
  102. }
  103. return nil
  104. }
  105. // NewDockerCli returns a DockerCli instance with IO output and error streams set by in, out and err.
  106. // The key file, protocol (i.e. unix) and address are passed in as strings, along with the tls.Config. If the tls.Config
  107. // is set the client scheme will be set to https.
  108. // The client will be given a 32-second timeout (see https://github.com/docker/docker/pull/8035).
  109. func NewDockerCli(in io.ReadCloser, out, err io.Writer, clientFlags *cliflags.ClientFlags) *DockerCli {
  110. cli := &DockerCli{
  111. in: in,
  112. out: out,
  113. err: err,
  114. keyFile: clientFlags.Common.TrustKey,
  115. }
  116. cli.init = func() error {
  117. clientFlags.PostParse()
  118. configFile, e := cliconfig.Load(cliconfig.ConfigDir())
  119. if e != nil {
  120. fmt.Fprintf(cli.err, "WARNING: Error loading config file:%v\n", e)
  121. }
  122. if !configFile.ContainsAuth() {
  123. credentials.DetectDefaultStore(configFile)
  124. }
  125. cli.configFile = configFile
  126. host, err := getServerHost(clientFlags.Common.Hosts, clientFlags.Common.TLSOptions)
  127. if err != nil {
  128. return err
  129. }
  130. customHeaders := cli.configFile.HTTPHeaders
  131. if customHeaders == nil {
  132. customHeaders = map[string]string{}
  133. }
  134. customHeaders["User-Agent"] = clientUserAgent()
  135. verStr := api.DefaultVersion
  136. if tmpStr := os.Getenv("DOCKER_API_VERSION"); tmpStr != "" {
  137. verStr = tmpStr
  138. }
  139. httpClient, err := newHTTPClient(host, clientFlags.Common.TLSOptions)
  140. if err != nil {
  141. return err
  142. }
  143. client, err := client.NewClient(host, verStr, httpClient, customHeaders)
  144. if err != nil {
  145. return err
  146. }
  147. cli.client = client
  148. if cli.in != nil {
  149. cli.inFd, cli.isTerminalIn = term.GetFdInfo(cli.in)
  150. }
  151. if cli.out != nil {
  152. cli.outFd, cli.isTerminalOut = term.GetFdInfo(cli.out)
  153. }
  154. return nil
  155. }
  156. return cli
  157. }
  158. func getServerHost(hosts []string, tlsOptions *tlsconfig.Options) (host string, err error) {
  159. switch len(hosts) {
  160. case 0:
  161. host = os.Getenv("DOCKER_HOST")
  162. case 1:
  163. host = hosts[0]
  164. default:
  165. return "", errors.New("Please specify only one -H")
  166. }
  167. host, err = opts.ParseHost(tlsOptions != nil, host)
  168. return
  169. }
  170. func newHTTPClient(host string, tlsOptions *tlsconfig.Options) (*http.Client, error) {
  171. if tlsOptions == nil {
  172. // let the api client configure the default transport.
  173. return nil, nil
  174. }
  175. config, err := tlsconfig.Client(*tlsOptions)
  176. if err != nil {
  177. return nil, err
  178. }
  179. tr := &http.Transport{
  180. TLSClientConfig: config,
  181. }
  182. proto, addr, _, err := client.ParseHost(host)
  183. if err != nil {
  184. return nil, err
  185. }
  186. sockets.ConfigureTransport(tr, proto, addr)
  187. return &http.Client{
  188. Transport: tr,
  189. }, nil
  190. }
  191. func clientUserAgent() string {
  192. return "Docker-Client/" + dockerversion.Version + " (" + runtime.GOOS + ")"
  193. }