client.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. /*
  2. Package client is a Go client for the Docker Engine API.
  3. The "docker" command uses this package to communicate with the daemon. It can also
  4. be used by your own Go applications to do anything the command-line interface does
  5. - running containers, pulling images, managing swarms, etc.
  6. For more information about the Engine API, see the documentation:
  7. https://docs.docker.com/engine/reference/api/
  8. Usage
  9. You use the library by creating a client object and calling methods on it. The
  10. client can be created either from environment variables with NewEnvClient, or
  11. configured manually with NewClient.
  12. For example, to list running containers (the equivalent of "docker ps"):
  13. package main
  14. import (
  15. "context"
  16. "fmt"
  17. "github.com/docker/docker/api/types"
  18. "github.com/docker/docker/client"
  19. )
  20. func main() {
  21. cli, err := client.NewEnvClient()
  22. if err != nil {
  23. panic(err)
  24. }
  25. containers, err := cli.ContainerList(context.Background(), types.ContainerListOptions{})
  26. if err != nil {
  27. panic(err)
  28. }
  29. for _, container := range containers {
  30. fmt.Printf("%s %s\n", container.ID[:10], container.Image)
  31. }
  32. }
  33. */
  34. package client
  35. import (
  36. "fmt"
  37. "net/http"
  38. "net/url"
  39. "os"
  40. "path/filepath"
  41. "strings"
  42. "github.com/docker/go-connections/sockets"
  43. "github.com/docker/go-connections/tlsconfig"
  44. )
  45. // DefaultVersion is the version of the current stable API
  46. const DefaultVersion string = "1.26"
  47. // Client is the API client that performs all operations
  48. // against a docker server.
  49. type Client struct {
  50. // scheme sets the scheme for the client
  51. scheme string
  52. // host holds the server address to connect to
  53. host string
  54. // proto holds the client protocol i.e. unix.
  55. proto string
  56. // addr holds the client address.
  57. addr string
  58. // basePath holds the path to prepend to the requests.
  59. basePath string
  60. // client used to send and receive http requests.
  61. client *http.Client
  62. // version of the server to talk to.
  63. version string
  64. // custom http headers configured by users.
  65. customHTTPHeaders map[string]string
  66. // manualOverride is set to true when the version was set by users.
  67. manualOverride bool
  68. }
  69. // NewEnvClient initializes a new API client based on environment variables.
  70. // Use DOCKER_HOST to set the url to the docker server.
  71. // Use DOCKER_API_VERSION to set the version of the API to reach, leave empty for latest.
  72. // Use DOCKER_CERT_PATH to load the tls certificates from.
  73. // Use DOCKER_TLS_VERIFY to enable or disable TLS verification, off by default.
  74. func NewEnvClient() (*Client, error) {
  75. var client *http.Client
  76. if dockerCertPath := os.Getenv("DOCKER_CERT_PATH"); dockerCertPath != "" {
  77. options := tlsconfig.Options{
  78. CAFile: filepath.Join(dockerCertPath, "ca.pem"),
  79. CertFile: filepath.Join(dockerCertPath, "cert.pem"),
  80. KeyFile: filepath.Join(dockerCertPath, "key.pem"),
  81. InsecureSkipVerify: os.Getenv("DOCKER_TLS_VERIFY") == "",
  82. }
  83. tlsc, err := tlsconfig.Client(options)
  84. if err != nil {
  85. return nil, err
  86. }
  87. client = &http.Client{
  88. Transport: &http.Transport{
  89. TLSClientConfig: tlsc,
  90. },
  91. }
  92. }
  93. host := os.Getenv("DOCKER_HOST")
  94. if host == "" {
  95. host = DefaultDockerHost
  96. }
  97. version := os.Getenv("DOCKER_API_VERSION")
  98. if version == "" {
  99. version = DefaultVersion
  100. }
  101. cli, err := NewClient(host, version, client, nil)
  102. if err != nil {
  103. return cli, err
  104. }
  105. if os.Getenv("DOCKER_API_VERSION") != "" {
  106. cli.manualOverride = true
  107. }
  108. return cli, nil
  109. }
  110. // NewClient initializes a new API client for the given host and API version.
  111. // It uses the given http client as transport.
  112. // It also initializes the custom http headers to add to each request.
  113. //
  114. // It won't send any version information if the version number is empty. It is
  115. // highly recommended that you set a version or your client may break if the
  116. // server is upgraded.
  117. func NewClient(host string, version string, client *http.Client, httpHeaders map[string]string) (*Client, error) {
  118. proto, addr, basePath, err := ParseHost(host)
  119. if err != nil {
  120. return nil, err
  121. }
  122. if client != nil {
  123. if _, ok := client.Transport.(*http.Transport); !ok {
  124. return nil, fmt.Errorf("unable to verify TLS configuration, invalid transport %v", client.Transport)
  125. }
  126. } else {
  127. transport := new(http.Transport)
  128. sockets.ConfigureTransport(transport, proto, addr)
  129. client = &http.Client{
  130. Transport: transport,
  131. }
  132. }
  133. scheme := "http"
  134. tlsConfig := resolveTLSConfig(client.Transport)
  135. if tlsConfig != nil {
  136. // TODO(stevvooe): This isn't really the right way to write clients in Go.
  137. // `NewClient` should probably only take an `*http.Client` and work from there.
  138. // Unfortunately, the model of having a host-ish/url-thingy as the connection
  139. // string has us confusing protocol and transport layers. We continue doing
  140. // this to avoid breaking existing clients but this should be addressed.
  141. scheme = "https"
  142. }
  143. return &Client{
  144. scheme: scheme,
  145. host: host,
  146. proto: proto,
  147. addr: addr,
  148. basePath: basePath,
  149. client: client,
  150. version: version,
  151. customHTTPHeaders: httpHeaders,
  152. }, nil
  153. }
  154. // Close ensures that transport.Client is closed
  155. // especially needed while using NewClient with *http.Client = nil
  156. // for example
  157. // client.NewClient("unix:///var/run/docker.sock", nil, "v1.18", map[string]string{"User-Agent": "engine-api-cli-1.0"})
  158. func (cli *Client) Close() error {
  159. if t, ok := cli.client.Transport.(*http.Transport); ok {
  160. t.CloseIdleConnections()
  161. }
  162. return nil
  163. }
  164. // getAPIPath returns the versioned request path to call the api.
  165. // It appends the query parameters to the path if they are not empty.
  166. func (cli *Client) getAPIPath(p string, query url.Values) string {
  167. var apiPath string
  168. if cli.version != "" {
  169. v := strings.TrimPrefix(cli.version, "v")
  170. apiPath = fmt.Sprintf("%s/v%s%s", cli.basePath, v, p)
  171. } else {
  172. apiPath = fmt.Sprintf("%s%s", cli.basePath, p)
  173. }
  174. u := &url.URL{
  175. Path: apiPath,
  176. }
  177. if len(query) > 0 {
  178. u.RawQuery = query.Encode()
  179. }
  180. return u.String()
  181. }
  182. // ClientVersion returns the version string associated with this
  183. // instance of the Client. Note that this value can be changed
  184. // via the DOCKER_API_VERSION env var.
  185. // This operation doesn't acquire a mutex.
  186. func (cli *Client) ClientVersion() string {
  187. return cli.version
  188. }
  189. // UpdateClientVersion updates the version string associated with this
  190. // instance of the Client. This operation doesn't acquire a mutex.
  191. func (cli *Client) UpdateClientVersion(v string) {
  192. if !cli.manualOverride {
  193. cli.version = v
  194. }
  195. }
  196. // ParseHost verifies that the given host strings is valid.
  197. func ParseHost(host string) (string, string, string, error) {
  198. protoAddrParts := strings.SplitN(host, "://", 2)
  199. if len(protoAddrParts) == 1 {
  200. return "", "", "", fmt.Errorf("unable to parse docker host `%s`", host)
  201. }
  202. var basePath string
  203. proto, addr := protoAddrParts[0], protoAddrParts[1]
  204. if proto == "tcp" {
  205. parsed, err := url.Parse("tcp://" + addr)
  206. if err != nil {
  207. return "", "", "", err
  208. }
  209. addr = parsed.Host
  210. basePath = parsed.Path
  211. }
  212. return proto, addr, basePath, nil
  213. }
  214. // CustomHTTPHeaders returns the custom http headers associated with this
  215. // instance of the Client. This operation doesn't acquire a mutex.
  216. func (cli *Client) CustomHTTPHeaders() map[string]string {
  217. m := make(map[string]string)
  218. for k, v := range cli.customHTTPHeaders {
  219. m[k] = v
  220. }
  221. return m
  222. }
  223. // SetCustomHTTPHeaders updates the custom http headers associated with this
  224. // instance of the Client. This operation doesn't acquire a mutex.
  225. func (cli *Client) SetCustomHTTPHeaders(headers map[string]string) {
  226. cli.customHTTPHeaders = headers
  227. }