cli.go 6.1 KB

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