cli.go 8.3 KB

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