request.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. package client
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "fmt"
  6. "io"
  7. "io/ioutil"
  8. "net/http"
  9. "net/url"
  10. "strings"
  11. "github.com/docker/engine-api/client/transport/cancellable"
  12. "golang.org/x/net/context"
  13. )
  14. // serverResponse is a wrapper for http API responses.
  15. type serverResponse struct {
  16. body io.ReadCloser
  17. header http.Header
  18. statusCode int
  19. }
  20. // head sends an http request to the docker API using the method HEAD.
  21. func (cli *Client) head(ctx context.Context, path string, query url.Values, headers map[string][]string) (*serverResponse, error) {
  22. return cli.sendRequest(ctx, "HEAD", path, query, nil, headers)
  23. }
  24. // getWithContext sends an http request to the docker API using the method GET with a specific go context.
  25. func (cli *Client) get(ctx context.Context, path string, query url.Values, headers map[string][]string) (*serverResponse, error) {
  26. return cli.sendRequest(ctx, "GET", path, query, nil, headers)
  27. }
  28. // postWithContext sends an http request to the docker API using the method POST with a specific go context.
  29. func (cli *Client) post(ctx context.Context, path string, query url.Values, obj interface{}, headers map[string][]string) (*serverResponse, error) {
  30. return cli.sendRequest(ctx, "POST", path, query, obj, headers)
  31. }
  32. func (cli *Client) postRaw(ctx context.Context, path string, query url.Values, body io.Reader, headers map[string][]string) (*serverResponse, error) {
  33. return cli.sendClientRequest(ctx, "POST", path, query, body, headers)
  34. }
  35. // put sends an http request to the docker API using the method PUT.
  36. func (cli *Client) put(ctx context.Context, path string, query url.Values, obj interface{}, headers map[string][]string) (*serverResponse, error) {
  37. return cli.sendRequest(ctx, "PUT", path, query, obj, headers)
  38. }
  39. // put sends an http request to the docker API using the method PUT.
  40. func (cli *Client) putRaw(ctx context.Context, path string, query url.Values, body io.Reader, headers map[string][]string) (*serverResponse, error) {
  41. return cli.sendClientRequest(ctx, "PUT", path, query, body, headers)
  42. }
  43. // delete sends an http request to the docker API using the method DELETE.
  44. func (cli *Client) delete(ctx context.Context, path string, query url.Values, headers map[string][]string) (*serverResponse, error) {
  45. return cli.sendRequest(ctx, "DELETE", path, query, nil, headers)
  46. }
  47. func (cli *Client) sendRequest(ctx context.Context, method, path string, query url.Values, obj interface{}, headers map[string][]string) (*serverResponse, error) {
  48. var body io.Reader
  49. if obj != nil {
  50. var err error
  51. body, err = encodeData(obj)
  52. if err != nil {
  53. return nil, err
  54. }
  55. if headers == nil {
  56. headers = make(map[string][]string)
  57. }
  58. headers["Content-Type"] = []string{"application/json"}
  59. }
  60. return cli.sendClientRequest(ctx, method, path, query, body, headers)
  61. }
  62. func (cli *Client) sendClientRequest(ctx context.Context, method, path string, query url.Values, body io.Reader, headers map[string][]string) (*serverResponse, error) {
  63. serverResp := &serverResponse{
  64. body: nil,
  65. statusCode: -1,
  66. }
  67. expectedPayload := (method == "POST" || method == "PUT")
  68. if expectedPayload && body == nil {
  69. body = bytes.NewReader([]byte{})
  70. }
  71. req, err := cli.newRequest(method, path, query, body, headers)
  72. req.URL.Host = cli.addr
  73. req.URL.Scheme = cli.transport.Scheme()
  74. if expectedPayload && req.Header.Get("Content-Type") == "" {
  75. req.Header.Set("Content-Type", "text/plain")
  76. }
  77. resp, err := cancellable.Do(ctx, cli.transport, req)
  78. if resp != nil {
  79. serverResp.statusCode = resp.StatusCode
  80. }
  81. if err != nil {
  82. if isTimeout(err) || strings.Contains(err.Error(), "connection refused") || strings.Contains(err.Error(), "dial unix") {
  83. return serverResp, ErrConnectionFailed
  84. }
  85. if !cli.transport.Secure() && strings.Contains(err.Error(), "malformed HTTP response") {
  86. return serverResp, fmt.Errorf("%v.\n* Are you trying to connect to a TLS-enabled daemon without TLS?", err)
  87. }
  88. if cli.transport.Secure() && strings.Contains(err.Error(), "remote error: bad certificate") {
  89. return serverResp, fmt.Errorf("The server probably has client authentication (--tlsverify) enabled. Please check your TLS client certification settings: %v", err)
  90. }
  91. return serverResp, fmt.Errorf("An error occurred trying to connect: %v", err)
  92. }
  93. if serverResp.statusCode < 200 || serverResp.statusCode >= 400 {
  94. body, err := ioutil.ReadAll(resp.Body)
  95. if err != nil {
  96. return serverResp, err
  97. }
  98. if len(body) == 0 {
  99. return serverResp, fmt.Errorf("Error: request returned %s for API route and version %s, check if the server supports the requested API version", http.StatusText(serverResp.statusCode), req.URL)
  100. }
  101. return serverResp, fmt.Errorf("Error response from daemon: %s", bytes.TrimSpace(body))
  102. }
  103. serverResp.body = resp.Body
  104. serverResp.header = resp.Header
  105. return serverResp, nil
  106. }
  107. func (cli *Client) newRequest(method, path string, query url.Values, body io.Reader, headers map[string][]string) (*http.Request, error) {
  108. apiPath := cli.getAPIPath(path, query)
  109. req, err := http.NewRequest(method, apiPath, body)
  110. if err != nil {
  111. return nil, err
  112. }
  113. // Add CLI Config's HTTP Headers BEFORE we set the Docker headers
  114. // then the user can't change OUR headers
  115. for k, v := range cli.customHTTPHeaders {
  116. req.Header.Set(k, v)
  117. }
  118. if headers != nil {
  119. for k, v := range headers {
  120. req.Header[k] = v
  121. }
  122. }
  123. return req, nil
  124. }
  125. func encodeData(data interface{}) (*bytes.Buffer, error) {
  126. params := bytes.NewBuffer(nil)
  127. if data != nil {
  128. if err := json.NewEncoder(params).Encode(data); err != nil {
  129. return nil, err
  130. }
  131. }
  132. return params, nil
  133. }
  134. func ensureReaderClosed(response *serverResponse) {
  135. if response != nil && response.body != nil {
  136. response.body.Close()
  137. }
  138. }
  139. func isTimeout(err error) bool {
  140. type timeout interface {
  141. Timeout() bool
  142. }
  143. e := err
  144. switch urlErr := err.(type) {
  145. case *url.Error:
  146. e = urlErr.Err
  147. }
  148. t, ok := e.(timeout)
  149. return ok && t.Timeout()
  150. }