cli.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. package client
  2. import (
  3. "errors"
  4. "fmt"
  5. "io"
  6. "net/http"
  7. "os"
  8. "path/filepath"
  9. "runtime"
  10. "github.com/docker/docker/api"
  11. cliflags "github.com/docker/docker/cli/flags"
  12. "github.com/docker/docker/cliconfig"
  13. "github.com/docker/docker/cliconfig/configfile"
  14. "github.com/docker/docker/cliconfig/credentials"
  15. "github.com/docker/docker/dockerversion"
  16. dopts "github.com/docker/docker/opts"
  17. "github.com/docker/docker/pkg/term"
  18. "github.com/docker/engine-api/client"
  19. "github.com/docker/go-connections/sockets"
  20. "github.com/docker/go-connections/tlsconfig"
  21. )
  22. // DockerCli represents the docker command line client.
  23. // Instances of the client can be returned from NewDockerCli.
  24. type DockerCli struct {
  25. // initializing closure
  26. init func() error
  27. // configFile has the client configuration file
  28. configFile *configfile.ConfigFile
  29. // in holds the input stream and closer (io.ReadCloser) for the client.
  30. in io.ReadCloser
  31. // out holds the output stream (io.Writer) for the client.
  32. out io.Writer
  33. // err holds the error stream (io.Writer) for the client.
  34. err io.Writer
  35. // keyFile holds the key file as a string.
  36. keyFile string
  37. // inFd holds the file descriptor of the client's STDIN (if valid).
  38. inFd uintptr
  39. // outFd holds file descriptor of the client's STDOUT (if valid).
  40. outFd uintptr
  41. // isTerminalIn indicates whether the client's STDIN is a TTY
  42. isTerminalIn bool
  43. // isTerminalOut indicates whether the client's STDOUT is a TTY
  44. isTerminalOut bool
  45. // client is the http client that performs all API operations
  46. client client.APIClient
  47. // inState holds the terminal input state
  48. inState *term.State
  49. // outState holds the terminal output state
  50. outState *term.State
  51. }
  52. // Client returns the APIClient
  53. func (cli *DockerCli) Client() client.APIClient {
  54. return cli.client
  55. }
  56. // Out returns the writer used for stdout
  57. func (cli *DockerCli) Out() io.Writer {
  58. return cli.out
  59. }
  60. // Err returns the writer used for stderr
  61. func (cli *DockerCli) Err() io.Writer {
  62. return cli.err
  63. }
  64. // In returns the reader used for stdin
  65. func (cli *DockerCli) In() io.ReadCloser {
  66. return cli.in
  67. }
  68. // ConfigFile returns the ConfigFile
  69. func (cli *DockerCli) ConfigFile() *configfile.ConfigFile {
  70. return cli.configFile
  71. }
  72. // IsTerminalIn returns true if the clients stdin is a TTY
  73. func (cli *DockerCli) IsTerminalIn() bool {
  74. return cli.isTerminalIn
  75. }
  76. // IsTerminalOut returns true if the clients stdout is a TTY
  77. func (cli *DockerCli) IsTerminalOut() bool {
  78. return cli.isTerminalOut
  79. }
  80. // OutFd returns the fd for the stdout stream
  81. func (cli *DockerCli) OutFd() uintptr {
  82. return cli.outFd
  83. }
  84. // CheckTtyInput checks if we are trying to attach to a container tty
  85. // from a non-tty client input stream, and if so, returns an error.
  86. func (cli *DockerCli) CheckTtyInput(attachStdin, ttyMode bool) error {
  87. // In order to attach to a container tty, input stream for the client must
  88. // be a tty itself: redirecting or piping the client standard input is
  89. // incompatible with `docker run -t`, `docker exec -t` or `docker attach`.
  90. if ttyMode && attachStdin && !cli.isTerminalIn {
  91. eText := "the input device is not a TTY"
  92. if runtime.GOOS == "windows" {
  93. return errors.New(eText + ". If you are using mintty, try prefixing the command with 'winpty'")
  94. }
  95. return errors.New(eText)
  96. }
  97. return nil
  98. }
  99. func (cli *DockerCli) setRawTerminal() error {
  100. if os.Getenv("NORAW") == "" {
  101. if cli.isTerminalIn {
  102. state, err := term.SetRawTerminal(cli.inFd)
  103. if err != nil {
  104. return err
  105. }
  106. cli.inState = state
  107. }
  108. if cli.isTerminalOut {
  109. state, err := term.SetRawTerminalOutput(cli.outFd)
  110. if err != nil {
  111. return err
  112. }
  113. cli.outState = state
  114. }
  115. }
  116. return nil
  117. }
  118. func (cli *DockerCli) restoreTerminal(in io.Closer) error {
  119. if cli.inState != nil {
  120. term.RestoreTerminal(cli.inFd, cli.inState)
  121. }
  122. if cli.outState != nil {
  123. term.RestoreTerminal(cli.outFd, cli.outState)
  124. }
  125. // WARNING: DO NOT REMOVE THE OS CHECK !!!
  126. // For some reason this Close call blocks on darwin..
  127. // As the client exists right after, simply discard the close
  128. // until we find a better solution.
  129. if in != nil && runtime.GOOS != "darwin" {
  130. return in.Close()
  131. }
  132. return nil
  133. }
  134. // Initialize the dockerCli runs initialization that must happen after command
  135. // line flags are parsed.
  136. func (cli *DockerCli) Initialize(opts *cliflags.ClientOptions) error {
  137. cli.configFile = LoadDefaultConfigFile(cli.err)
  138. client, err := NewAPIClientFromFlags(opts.Common, cli.configFile)
  139. if err != nil {
  140. return err
  141. }
  142. cli.client = client
  143. if cli.in != nil {
  144. cli.inFd, cli.isTerminalIn = term.GetFdInfo(cli.in)
  145. }
  146. if cli.out != nil {
  147. cli.outFd, cli.isTerminalOut = term.GetFdInfo(cli.out)
  148. }
  149. if opts.Common.TrustKey == "" {
  150. cli.keyFile = filepath.Join(cliconfig.ConfigDir(), cliflags.DefaultTrustKeyFile)
  151. } else {
  152. cli.keyFile = opts.Common.TrustKey
  153. }
  154. return nil
  155. }
  156. // NewDockerCli returns a DockerCli instance with IO output and error streams set by in, out and err.
  157. func NewDockerCli(in io.ReadCloser, out, err io.Writer) *DockerCli {
  158. return &DockerCli{
  159. in: in,
  160. out: out,
  161. err: err,
  162. }
  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. }