cli.go 7.9 KB

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