cli.go 7.7 KB

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