cli.go 7.5 KB

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