cli.go 7.4 KB

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