cli.go 7.3 KB

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