cli.go 7.1 KB

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