cli.go 4.9 KB

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