client.go 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  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. "errors"
  37. "fmt"
  38. "net/http"
  39. "net/url"
  40. "os"
  41. "path/filepath"
  42. "strings"
  43. "github.com/docker/docker/api"
  44. "github.com/docker/docker/api/types"
  45. "github.com/docker/docker/api/types/versions"
  46. "github.com/docker/go-connections/sockets"
  47. "github.com/docker/go-connections/tlsconfig"
  48. "golang.org/x/net/context"
  49. )
  50. // ErrRedirect is the error returned by checkRedirect when the request is non-GET.
  51. var ErrRedirect = errors.New("unexpected redirect in response")
  52. // Client is the API client that performs all operations
  53. // against a docker server.
  54. type Client struct {
  55. // scheme sets the scheme for the client
  56. scheme string
  57. // host holds the server address to connect to
  58. host string
  59. // proto holds the client protocol i.e. unix.
  60. proto string
  61. // addr holds the client address.
  62. addr string
  63. // basePath holds the path to prepend to the requests.
  64. basePath string
  65. // client used to send and receive http requests.
  66. client *http.Client
  67. // version of the server to talk to.
  68. version string
  69. // custom http headers configured by users.
  70. customHTTPHeaders map[string]string
  71. // manualOverride is set to true when the version was set by users.
  72. manualOverride bool
  73. }
  74. // CheckRedirect specifies the policy for dealing with redirect responses:
  75. // If the request is non-GET return `ErrRedirect`. Otherwise use the last response.
  76. //
  77. // Go 1.8 changes behavior for HTTP redirects (specifically 301, 307, and 308) in the client .
  78. // The Docker client (and by extension docker API client) can be made to to send a request
  79. // like POST /containers//start where what would normally be in the name section of the URL is empty.
  80. // This triggers an HTTP 301 from the daemon.
  81. // In go 1.8 this 301 will be converted to a GET request, and ends up getting a 404 from the daemon.
  82. // This behavior change manifests in the client in that before the 301 was not followed and
  83. // the client did not generate an error, but now results in a message like Error response from daemon: page not found.
  84. func CheckRedirect(req *http.Request, via []*http.Request) error {
  85. if via[0].Method == http.MethodGet {
  86. return http.ErrUseLastResponse
  87. }
  88. return ErrRedirect
  89. }
  90. // NewEnvClient initializes a new API client based on environment variables.
  91. // Use DOCKER_HOST to set the url to the docker server.
  92. // Use DOCKER_API_VERSION to set the version of the API to reach, leave empty for latest.
  93. // Use DOCKER_CERT_PATH to load the TLS certificates from.
  94. // Use DOCKER_TLS_VERIFY to enable or disable TLS verification, off by default.
  95. func NewEnvClient() (*Client, error) {
  96. var client *http.Client
  97. if dockerCertPath := os.Getenv("DOCKER_CERT_PATH"); dockerCertPath != "" {
  98. options := tlsconfig.Options{
  99. CAFile: filepath.Join(dockerCertPath, "ca.pem"),
  100. CertFile: filepath.Join(dockerCertPath, "cert.pem"),
  101. KeyFile: filepath.Join(dockerCertPath, "key.pem"),
  102. InsecureSkipVerify: os.Getenv("DOCKER_TLS_VERIFY") == "",
  103. }
  104. tlsc, err := tlsconfig.Client(options)
  105. if err != nil {
  106. return nil, err
  107. }
  108. client = &http.Client{
  109. Transport: &http.Transport{
  110. TLSClientConfig: tlsc,
  111. },
  112. CheckRedirect: CheckRedirect,
  113. }
  114. }
  115. host := os.Getenv("DOCKER_HOST")
  116. if host == "" {
  117. host = DefaultDockerHost
  118. }
  119. version := os.Getenv("DOCKER_API_VERSION")
  120. if version == "" {
  121. version = api.DefaultVersion
  122. }
  123. cli, err := NewClient(host, version, client, nil)
  124. if err != nil {
  125. return cli, err
  126. }
  127. if os.Getenv("DOCKER_API_VERSION") != "" {
  128. cli.manualOverride = true
  129. }
  130. return cli, nil
  131. }
  132. // NewClient initializes a new API client for the given host and API version.
  133. // It uses the given http client as transport.
  134. // It also initializes the custom http headers to add to each request.
  135. //
  136. // It won't send any version information if the version number is empty. It is
  137. // highly recommended that you set a version or your client may break if the
  138. // server is upgraded.
  139. func NewClient(host string, version string, client *http.Client, httpHeaders map[string]string) (*Client, error) {
  140. proto, addr, basePath, err := ParseHost(host)
  141. if err != nil {
  142. return nil, err
  143. }
  144. if client != nil {
  145. if _, ok := client.Transport.(*http.Transport); !ok {
  146. return nil, fmt.Errorf("unable to verify TLS configuration, invalid transport %v", client.Transport)
  147. }
  148. } else {
  149. transport := new(http.Transport)
  150. sockets.ConfigureTransport(transport, proto, addr)
  151. client = &http.Client{
  152. Transport: transport,
  153. CheckRedirect: CheckRedirect,
  154. }
  155. }
  156. scheme := "http"
  157. tlsConfig := resolveTLSConfig(client.Transport)
  158. if tlsConfig != nil {
  159. // TODO(stevvooe): This isn't really the right way to write clients in Go.
  160. // `NewClient` should probably only take an `*http.Client` and work from there.
  161. // Unfortunately, the model of having a host-ish/url-thingy as the connection
  162. // string has us confusing protocol and transport layers. We continue doing
  163. // this to avoid breaking existing clients but this should be addressed.
  164. scheme = "https"
  165. }
  166. return &Client{
  167. scheme: scheme,
  168. host: host,
  169. proto: proto,
  170. addr: addr,
  171. basePath: basePath,
  172. client: client,
  173. version: version,
  174. customHTTPHeaders: httpHeaders,
  175. }, nil
  176. }
  177. // Close ensures that transport.Client is closed
  178. // especially needed while using NewClient with *http.Client = nil
  179. // for example
  180. // client.NewClient("unix:///var/run/docker.sock", nil, "v1.18", map[string]string{"User-Agent": "engine-api-cli-1.0"})
  181. func (cli *Client) Close() error {
  182. if t, ok := cli.client.Transport.(*http.Transport); ok {
  183. t.CloseIdleConnections()
  184. }
  185. return nil
  186. }
  187. // getAPIPath returns the versioned request path to call the api.
  188. // It appends the query parameters to the path if they are not empty.
  189. func (cli *Client) getAPIPath(p string, query url.Values) string {
  190. var apiPath string
  191. if cli.version != "" {
  192. v := strings.TrimPrefix(cli.version, "v")
  193. apiPath = cli.basePath + "/v" + v + p
  194. } else {
  195. apiPath = cli.basePath + p
  196. }
  197. u := &url.URL{
  198. Path: apiPath,
  199. }
  200. if len(query) > 0 {
  201. u.RawQuery = query.Encode()
  202. }
  203. return u.String()
  204. }
  205. // ClientVersion returns the version string associated with this
  206. // instance of the Client. Note that this value can be changed
  207. // via the DOCKER_API_VERSION env var.
  208. // This operation doesn't acquire a mutex.
  209. func (cli *Client) ClientVersion() string {
  210. return cli.version
  211. }
  212. // NegotiateAPIVersion updates the version string associated with this
  213. // instance of the Client to match the latest version the server supports
  214. func (cli *Client) NegotiateAPIVersion(ctx context.Context) {
  215. ping, _ := cli.Ping(ctx)
  216. cli.NegotiateAPIVersionPing(ping)
  217. }
  218. // NegotiateAPIVersionPing updates the version string associated with this
  219. // instance of the Client to match the latest version the server supports
  220. func (cli *Client) NegotiateAPIVersionPing(p types.Ping) {
  221. if cli.manualOverride {
  222. return
  223. }
  224. // try the latest version before versioning headers existed
  225. if p.APIVersion == "" {
  226. p.APIVersion = "1.24"
  227. }
  228. // if the client is not initialized with a version, start with the latest supported version
  229. if cli.version == "" {
  230. cli.version = api.DefaultVersion
  231. }
  232. // if server version is lower than the maximum version supported by the Client, downgrade
  233. if versions.LessThan(p.APIVersion, api.DefaultVersion) {
  234. cli.version = p.APIVersion
  235. }
  236. }
  237. // DaemonHost returns the host associated with this instance of the Client.
  238. // This operation doesn't acquire a mutex.
  239. func (cli *Client) DaemonHost() string {
  240. return cli.host
  241. }
  242. // ParseHost verifies that the given host strings is valid.
  243. func ParseHost(host string) (string, string, string, error) {
  244. protoAddrParts := strings.SplitN(host, "://", 2)
  245. if len(protoAddrParts) == 1 {
  246. return "", "", "", fmt.Errorf("unable to parse docker host `%s`", host)
  247. }
  248. var basePath string
  249. proto, addr := protoAddrParts[0], protoAddrParts[1]
  250. if proto == "tcp" {
  251. parsed, err := url.Parse("tcp://" + addr)
  252. if err != nil {
  253. return "", "", "", err
  254. }
  255. addr = parsed.Host
  256. basePath = parsed.Path
  257. }
  258. return proto, addr, basePath, nil
  259. }
  260. // CustomHTTPHeaders returns the custom http headers associated with this
  261. // instance of the Client. This operation doesn't acquire a mutex.
  262. func (cli *Client) CustomHTTPHeaders() map[string]string {
  263. m := make(map[string]string)
  264. for k, v := range cli.customHTTPHeaders {
  265. m[k] = v
  266. }
  267. return m
  268. }
  269. // SetCustomHTTPHeaders updates the custom http headers associated with this
  270. // instance of the Client. This operation doesn't acquire a mutex.
  271. func (cli *Client) SetCustomHTTPHeaders(headers map[string]string) {
  272. cli.customHTTPHeaders = headers
  273. }