cli.go 7.3 KB

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