cli.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  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. "github.com/docker/docker/cli"
  11. "github.com/docker/docker/cliconfig"
  12. "github.com/docker/docker/dockerversion"
  13. "github.com/docker/docker/opts"
  14. "github.com/docker/docker/pkg/term"
  15. "github.com/docker/engine-api/client"
  16. "github.com/docker/go-connections/sockets"
  17. "github.com/docker/go-connections/tlsconfig"
  18. )
  19. // DockerCli represents the docker command line client.
  20. // Instances of the client can be returned from NewDockerCli.
  21. type DockerCli struct {
  22. // initializing closure
  23. init func() error
  24. // configFile has the client configuration file
  25. configFile *cliconfig.ConfigFile
  26. // in holds the input stream and closer (io.ReadCloser) for the client.
  27. in io.ReadCloser
  28. // out holds the output stream (io.Writer) for the client.
  29. out io.Writer
  30. // err holds the error stream (io.Writer) for the client.
  31. err io.Writer
  32. // keyFile holds the key file as a string.
  33. keyFile string
  34. // inFd holds the file descriptor of the client's STDIN (if valid).
  35. inFd uintptr
  36. // outFd holds file descriptor of the client's STDOUT (if valid).
  37. outFd uintptr
  38. // isTerminalIn indicates whether the client's STDIN is a TTY
  39. isTerminalIn bool
  40. // isTerminalOut indicates whether the client's STDOUT is a TTY
  41. isTerminalOut bool
  42. // client is the http client that performs all API operations
  43. client client.APIClient
  44. // state holds the terminal state
  45. state *term.State
  46. }
  47. // Initialize calls the init function that will setup the configuration for the client
  48. // such as the TLS, tcp and other parameters used to run the client.
  49. func (cli *DockerCli) Initialize() error {
  50. if cli.init == nil {
  51. return nil
  52. }
  53. return cli.init()
  54. }
  55. // CheckTtyInput checks if we are trying to attach to a container tty
  56. // from a non-tty client input stream, and if so, returns an error.
  57. func (cli *DockerCli) CheckTtyInput(attachStdin, ttyMode bool) error {
  58. // In order to attach to a container tty, input stream for the client must
  59. // be a tty itself: redirecting or piping the client standard input is
  60. // incompatible with `docker run -t`, `docker exec -t` or `docker attach`.
  61. if ttyMode && attachStdin && !cli.isTerminalIn {
  62. return errors.New("cannot enable tty mode on non tty input")
  63. }
  64. return nil
  65. }
  66. // PsFormat returns the format string specified in the configuration.
  67. // String contains columns and format specification, for example {{ID}}\t{{Name}}.
  68. func (cli *DockerCli) PsFormat() string {
  69. return cli.configFile.PsFormat
  70. }
  71. // ImagesFormat returns the format string specified in the configuration.
  72. // String contains columns and format specification, for example {{ID}}\t{{Name}}.
  73. func (cli *DockerCli) ImagesFormat() string {
  74. return cli.configFile.ImagesFormat
  75. }
  76. func (cli *DockerCli) setRawTerminal() error {
  77. if cli.isTerminalIn && os.Getenv("NORAW") == "" {
  78. state, err := term.SetRawTerminal(cli.inFd)
  79. if err != nil {
  80. return err
  81. }
  82. cli.state = state
  83. }
  84. return nil
  85. }
  86. func (cli *DockerCli) restoreTerminal(in io.Closer) error {
  87. if cli.state != nil {
  88. term.RestoreTerminal(cli.inFd, cli.state)
  89. }
  90. // WARNING: DO NOT REMOVE THE OS CHECK !!!
  91. // For some reason this Close call blocks on darwin..
  92. // As the client exists right after, simply discard the close
  93. // until we find a better solution.
  94. if in != nil && runtime.GOOS != "darwin" {
  95. return in.Close()
  96. }
  97. return nil
  98. }
  99. // NewDockerCli returns a DockerCli instance with IO output and error streams set by in, out and err.
  100. // The key file, protocol (i.e. unix) and address are passed in as strings, along with the tls.Config. If the tls.Config
  101. // is set the client scheme will be set to https.
  102. // The client will be given a 32-second timeout (see https://github.com/docker/docker/pull/8035).
  103. func NewDockerCli(in io.ReadCloser, out, err io.Writer, clientFlags *cli.ClientFlags) *DockerCli {
  104. cli := &DockerCli{
  105. in: in,
  106. out: out,
  107. err: err,
  108. keyFile: clientFlags.Common.TrustKey,
  109. }
  110. cli.init = func() error {
  111. clientFlags.PostParse()
  112. configFile, e := cliconfig.Load(cliconfig.ConfigDir())
  113. if e != nil {
  114. fmt.Fprintf(cli.err, "WARNING: Error loading config file:%v\n", e)
  115. }
  116. cli.configFile = configFile
  117. host, err := getServerHost(clientFlags.Common.Hosts, clientFlags.Common.TLSOptions)
  118. if err != nil {
  119. return err
  120. }
  121. customHeaders := cli.configFile.HTTPHeaders
  122. if customHeaders == nil {
  123. customHeaders = map[string]string{}
  124. }
  125. customHeaders["User-Agent"] = "Docker-Client/" + dockerversion.Version + " (" + runtime.GOOS + ")"
  126. verStr := api.DefaultVersion.String()
  127. if tmpStr := os.Getenv("DOCKER_API_VERSION"); tmpStr != "" {
  128. verStr = tmpStr
  129. }
  130. httpClient, err := newHTTPClient(host, clientFlags.Common.TLSOptions)
  131. if err != nil {
  132. return err
  133. }
  134. client, err := client.NewClient(host, verStr, httpClient, customHeaders)
  135. if err != nil {
  136. return err
  137. }
  138. cli.client = client
  139. if cli.in != nil {
  140. cli.inFd, cli.isTerminalIn = term.GetFdInfo(cli.in)
  141. }
  142. if cli.out != nil {
  143. cli.outFd, cli.isTerminalOut = term.GetFdInfo(cli.out)
  144. }
  145. return nil
  146. }
  147. return cli
  148. }
  149. func getServerHost(hosts []string, tlsOptions *tlsconfig.Options) (host string, err error) {
  150. switch len(hosts) {
  151. case 0:
  152. host = os.Getenv("DOCKER_HOST")
  153. case 1:
  154. host = hosts[0]
  155. default:
  156. return "", errors.New("Please specify only one -H")
  157. }
  158. host, err = opts.ParseHost(tlsOptions != nil, host)
  159. return
  160. }
  161. func newHTTPClient(host string, tlsOptions *tlsconfig.Options) (*http.Client, error) {
  162. if tlsOptions == nil {
  163. // let the api client configure the default transport.
  164. return nil, nil
  165. }
  166. config, err := tlsconfig.Client(*tlsOptions)
  167. if err != nil {
  168. return nil, err
  169. }
  170. tr := &http.Transport{
  171. TLSClientConfig: config,
  172. }
  173. proto, addr, _, err := client.ParseHost(host)
  174. if err != nil {
  175. return nil, err
  176. }
  177. sockets.ConfigureTransport(tr, proto, addr)
  178. return &http.Client{
  179. Transport: tr,
  180. }, nil
  181. }