cli.go 7.0 KB

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