cli.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. package command
  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. "github.com/docker/docker/api/types/versions"
  12. cliflags "github.com/docker/docker/cli/flags"
  13. "github.com/docker/docker/cliconfig"
  14. "github.com/docker/docker/cliconfig/configfile"
  15. "github.com/docker/docker/cliconfig/credentials"
  16. "github.com/docker/docker/client"
  17. "github.com/docker/docker/dockerversion"
  18. dopts "github.com/docker/docker/opts"
  19. "github.com/docker/go-connections/sockets"
  20. "github.com/docker/go-connections/tlsconfig"
  21. "golang.org/x/net/context"
  22. )
  23. // Streams is an interface which exposes the standard input and output streams
  24. type Streams interface {
  25. In() *InStream
  26. Out() *OutStream
  27. Err() io.Writer
  28. }
  29. // DockerCli represents the docker command line client.
  30. // Instances of the client can be returned from NewDockerCli.
  31. type DockerCli struct {
  32. configFile *configfile.ConfigFile
  33. in *InStream
  34. out *OutStream
  35. err io.Writer
  36. keyFile string
  37. client client.APIClient
  38. hasExperimental bool
  39. defaultVersion string
  40. }
  41. // HasExperimental returns true if experimental features are accessible.
  42. func (cli *DockerCli) HasExperimental() bool {
  43. return cli.hasExperimental
  44. }
  45. // DefaultVersion returns api.defaultVersion of DOCKER_API_VERSION if specified.
  46. func (cli *DockerCli) DefaultVersion() string {
  47. return cli.defaultVersion
  48. }
  49. // Client returns the APIClient
  50. func (cli *DockerCli) Client() client.APIClient {
  51. return cli.client
  52. }
  53. // Out returns the writer used for stdout
  54. func (cli *DockerCli) Out() *OutStream {
  55. return cli.out
  56. }
  57. // Err returns the writer used for stderr
  58. func (cli *DockerCli) Err() io.Writer {
  59. return cli.err
  60. }
  61. // In returns the reader used for stdin
  62. func (cli *DockerCli) In() *InStream {
  63. return cli.in
  64. }
  65. // ConfigFile returns the ConfigFile
  66. func (cli *DockerCli) ConfigFile() *configfile.ConfigFile {
  67. return cli.configFile
  68. }
  69. // CredentialsStore returns a new credentials store based
  70. // on the settings provided in the configuration file.
  71. func (cli *DockerCli) CredentialsStore() credentials.Store {
  72. if cli.configFile.CredentialsStore != "" {
  73. return credentials.NewNativeStore(cli.configFile)
  74. }
  75. return credentials.NewFileStore(cli.configFile)
  76. }
  77. // Initialize the dockerCli runs initialization that must happen after command
  78. // line flags are parsed.
  79. func (cli *DockerCli) Initialize(opts *cliflags.ClientOptions) error {
  80. cli.configFile = LoadDefaultConfigFile(cli.err)
  81. var err error
  82. cli.client, err = NewAPIClientFromFlags(opts.Common, cli.configFile)
  83. if err != nil {
  84. return err
  85. }
  86. cli.defaultVersion = cli.client.ClientVersion()
  87. if opts.Common.TrustKey == "" {
  88. cli.keyFile = filepath.Join(cliconfig.ConfigDir(), cliflags.DefaultTrustKeyFile)
  89. } else {
  90. cli.keyFile = opts.Common.TrustKey
  91. }
  92. if ping, err := cli.client.Ping(context.Background()); err == nil {
  93. cli.hasExperimental = ping.Experimental
  94. // since the new header was added in 1.25, assume server is 1.24 if header is not present.
  95. if ping.APIVersion == "" {
  96. ping.APIVersion = "1.24"
  97. }
  98. // if server version is lower than the current cli, downgrade
  99. if versions.LessThan(ping.APIVersion, cli.client.ClientVersion()) {
  100. cli.client.UpdateClientVersion(ping.APIVersion)
  101. }
  102. }
  103. return nil
  104. }
  105. // NewDockerCli returns a DockerCli instance with IO output and error streams set by in, out and err.
  106. func NewDockerCli(in io.ReadCloser, out, err io.Writer) *DockerCli {
  107. return &DockerCli{in: NewInStream(in), out: NewOutStream(out), err: err}
  108. }
  109. // LoadDefaultConfigFile attempts to load the default config file and returns
  110. // an initialized ConfigFile struct if none is found.
  111. func LoadDefaultConfigFile(err io.Writer) *configfile.ConfigFile {
  112. configFile, e := cliconfig.Load(cliconfig.ConfigDir())
  113. if e != nil {
  114. fmt.Fprintf(err, "WARNING: Error loading config file:%v\n", e)
  115. }
  116. if !configFile.ContainsAuth() {
  117. credentials.DetectDefaultStore(configFile)
  118. }
  119. return configFile
  120. }
  121. // NewAPIClientFromFlags creates a new APIClient from command line flags
  122. func NewAPIClientFromFlags(opts *cliflags.CommonOptions, configFile *configfile.ConfigFile) (client.APIClient, error) {
  123. host, err := getServerHost(opts.Hosts, opts.TLSOptions)
  124. if err != nil {
  125. return &client.Client{}, err
  126. }
  127. customHeaders := configFile.HTTPHeaders
  128. if customHeaders == nil {
  129. customHeaders = map[string]string{}
  130. }
  131. customHeaders["User-Agent"] = UserAgent()
  132. verStr := api.DefaultVersion
  133. if tmpStr := os.Getenv("DOCKER_API_VERSION"); tmpStr != "" {
  134. verStr = tmpStr
  135. }
  136. httpClient, err := newHTTPClient(host, opts.TLSOptions)
  137. if err != nil {
  138. return &client.Client{}, err
  139. }
  140. return client.NewClient(host, verStr, httpClient, customHeaders)
  141. }
  142. func getServerHost(hosts []string, tlsOptions *tlsconfig.Options) (host string, err error) {
  143. switch len(hosts) {
  144. case 0:
  145. host = os.Getenv("DOCKER_HOST")
  146. case 1:
  147. host = hosts[0]
  148. default:
  149. return "", errors.New("Please specify only one -H")
  150. }
  151. host, err = dopts.ParseHost(tlsOptions != nil, host)
  152. return
  153. }
  154. func newHTTPClient(host string, tlsOptions *tlsconfig.Options) (*http.Client, error) {
  155. if tlsOptions == nil {
  156. // let the api client configure the default transport.
  157. return nil, nil
  158. }
  159. config, err := tlsconfig.Client(*tlsOptions)
  160. if err != nil {
  161. return nil, err
  162. }
  163. tr := &http.Transport{
  164. TLSClientConfig: config,
  165. }
  166. proto, addr, _, err := client.ParseHost(host)
  167. if err != nil {
  168. return nil, err
  169. }
  170. sockets.ConfigureTransport(tr, proto, addr)
  171. return &http.Client{
  172. Transport: tr,
  173. }, nil
  174. }
  175. // UserAgent returns the user agent string used for making API requests
  176. func UserAgent() string {
  177. return "Docker-Client/" + dockerversion.Version + " (" + runtime.GOOS + ")"
  178. }