request.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. package client
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "fmt"
  6. "io"
  7. "io/ioutil"
  8. "net"
  9. "net/http"
  10. "net/url"
  11. "os"
  12. "strings"
  13. "github.com/docker/docker/api/types"
  14. "github.com/docker/docker/api/types/versions"
  15. "github.com/pkg/errors"
  16. "golang.org/x/net/context"
  17. "golang.org/x/net/context/ctxhttp"
  18. )
  19. // serverResponse is a wrapper for http API responses.
  20. type serverResponse struct {
  21. body io.ReadCloser
  22. header http.Header
  23. statusCode int
  24. }
  25. // head sends an http request to the docker API using the method HEAD.
  26. func (cli *Client) head(ctx context.Context, path string, query url.Values, headers map[string][]string) (serverResponse, error) {
  27. return cli.sendRequest(ctx, "HEAD", path, query, nil, headers)
  28. }
  29. // getWithContext sends an http request to the docker API using the method GET with a specific go context.
  30. func (cli *Client) get(ctx context.Context, path string, query url.Values, headers map[string][]string) (serverResponse, error) {
  31. return cli.sendRequest(ctx, "GET", path, query, nil, headers)
  32. }
  33. // postWithContext sends an http request to the docker API using the method POST with a specific go context.
  34. func (cli *Client) post(ctx context.Context, path string, query url.Values, obj interface{}, headers map[string][]string) (serverResponse, error) {
  35. return cli.sendRequest(ctx, "POST", path, query, obj, headers)
  36. }
  37. func (cli *Client) postRaw(ctx context.Context, path string, query url.Values, body io.Reader, headers map[string][]string) (serverResponse, error) {
  38. return cli.sendClientRequest(ctx, "POST", path, query, body, headers)
  39. }
  40. // put sends an http request to the docker API using the method PUT.
  41. func (cli *Client) put(ctx context.Context, path string, query url.Values, obj interface{}, headers map[string][]string) (serverResponse, error) {
  42. return cli.sendRequest(ctx, "PUT", path, query, obj, headers)
  43. }
  44. // put sends an http request to the docker API using the method PUT.
  45. func (cli *Client) putRaw(ctx context.Context, path string, query url.Values, body io.Reader, headers map[string][]string) (serverResponse, error) {
  46. return cli.sendClientRequest(ctx, "PUT", path, query, body, headers)
  47. }
  48. // delete sends an http request to the docker API using the method DELETE.
  49. func (cli *Client) delete(ctx context.Context, path string, query url.Values, headers map[string][]string) (serverResponse, error) {
  50. return cli.sendRequest(ctx, "DELETE", path, query, nil, headers)
  51. }
  52. func (cli *Client) sendRequest(ctx context.Context, method, path string, query url.Values, obj interface{}, headers map[string][]string) (serverResponse, error) {
  53. var body io.Reader
  54. if obj != nil {
  55. var err error
  56. body, err = encodeData(obj)
  57. if err != nil {
  58. return serverResponse{}, err
  59. }
  60. if headers == nil {
  61. headers = make(map[string][]string)
  62. }
  63. headers["Content-Type"] = []string{"application/json"}
  64. }
  65. return cli.sendClientRequest(ctx, method, path, query, body, headers)
  66. }
  67. func (cli *Client) sendClientRequest(ctx context.Context, method, path string, query url.Values, body io.Reader, headers map[string][]string) (serverResponse, error) {
  68. serverResp := serverResponse{
  69. body: nil,
  70. statusCode: -1,
  71. }
  72. expectedPayload := (method == "POST" || method == "PUT")
  73. if expectedPayload && body == nil {
  74. body = bytes.NewReader([]byte{})
  75. }
  76. req, err := cli.newRequest(method, path, query, body, headers)
  77. if err != nil {
  78. return serverResp, err
  79. }
  80. if cli.proto == "unix" || cli.proto == "npipe" {
  81. // For local communications, it doesn't matter what the host is. We just
  82. // need a valid and meaningful host name. (See #189)
  83. req.Host = "docker"
  84. }
  85. req.URL.Host = cli.addr
  86. req.URL.Scheme = cli.scheme
  87. if expectedPayload && req.Header.Get("Content-Type") == "" {
  88. req.Header.Set("Content-Type", "text/plain")
  89. }
  90. resp, err := ctxhttp.Do(ctx, cli.client, req)
  91. if err != nil {
  92. if cli.scheme != "https" && strings.Contains(err.Error(), "malformed HTTP response") {
  93. return serverResp, fmt.Errorf("%v.\n* Are you trying to connect to a TLS-enabled daemon without TLS?", err)
  94. }
  95. if cli.scheme == "https" && strings.Contains(err.Error(), "bad certificate") {
  96. return serverResp, fmt.Errorf("The server probably has client authentication (--tlsverify) enabled. Please check your TLS client certification settings: %v", err)
  97. }
  98. // Don't decorate context sentinel errors; users may be comparing to
  99. // them directly.
  100. switch err {
  101. case context.Canceled, context.DeadlineExceeded:
  102. return serverResp, err
  103. }
  104. if nErr, ok := err.(*url.Error); ok {
  105. if nErr, ok := nErr.Err.(*net.OpError); ok {
  106. if os.IsPermission(nErr.Err) {
  107. return serverResp, errors.Wrapf(err, "Got permission denied while trying to connect to the Docker daemon socket at %v", cli.host)
  108. }
  109. }
  110. }
  111. if err, ok := err.(net.Error); ok {
  112. if err.Timeout() {
  113. return serverResp, ErrorConnectionFailed(cli.host)
  114. }
  115. if !err.Temporary() {
  116. if strings.Contains(err.Error(), "connection refused") || strings.Contains(err.Error(), "dial unix") {
  117. return serverResp, ErrorConnectionFailed(cli.host)
  118. }
  119. }
  120. }
  121. // Although there's not a strongly typed error for this in go-winio,
  122. // lots of people are using the default configuration for the docker
  123. // daemon on Windows where the daemon is listening on a named pipe
  124. // `//./pipe/docker_engine, and the client must be running elevated.
  125. // Give users a clue rather than the not-overly useful message
  126. // such as `error during connect: Get http://%2F%2F.%2Fpipe%2Fdocker_engine/v1.25/info:
  127. // open //./pipe/docker_engine: The system cannot find the file specified.`.
  128. // Note we can't string compare "The system cannot find the file specified" as
  129. // this is localised - for example in French the error would be
  130. // `open //./pipe/docker_engine: Le fichier spécifié est introuvable.`
  131. if strings.Contains(err.Error(), `open //./pipe/docker_engine`) {
  132. err = errors.New(err.Error() + " In the default daemon configuration on Windows, the docker client must be run elevated to connect. This error may also indicate that the docker daemon is not running.")
  133. }
  134. return serverResp, errors.Wrap(err, "error during connect")
  135. }
  136. if resp != nil {
  137. serverResp.statusCode = resp.StatusCode
  138. }
  139. if serverResp.statusCode < 200 || serverResp.statusCode >= 400 {
  140. body, err := ioutil.ReadAll(resp.Body)
  141. if err != nil {
  142. return serverResp, err
  143. }
  144. if len(body) == 0 {
  145. 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)
  146. }
  147. var errorMessage string
  148. if (cli.version == "" || versions.GreaterThan(cli.version, "1.23")) &&
  149. resp.Header.Get("Content-Type") == "application/json" {
  150. var errorResponse types.ErrorResponse
  151. if err := json.Unmarshal(body, &errorResponse); err != nil {
  152. return serverResp, fmt.Errorf("Error reading JSON: %v", err)
  153. }
  154. errorMessage = errorResponse.Message
  155. } else {
  156. errorMessage = string(body)
  157. }
  158. return serverResp, fmt.Errorf("Error response from daemon: %s", strings.TrimSpace(errorMessage))
  159. }
  160. serverResp.body = resp.Body
  161. serverResp.header = resp.Header
  162. return serverResp, nil
  163. }
  164. func (cli *Client) newRequest(method, path string, query url.Values, body io.Reader, headers map[string][]string) (*http.Request, error) {
  165. apiPath := cli.getAPIPath(path, query)
  166. req, err := http.NewRequest(method, apiPath, body)
  167. if err != nil {
  168. return nil, err
  169. }
  170. // Add CLI Config's HTTP Headers BEFORE we set the Docker headers
  171. // then the user can't change OUR headers
  172. for k, v := range cli.customHTTPHeaders {
  173. req.Header.Set(k, v)
  174. }
  175. if headers != nil {
  176. for k, v := range headers {
  177. req.Header[k] = v
  178. }
  179. }
  180. return req, nil
  181. }
  182. func encodeData(data interface{}) (*bytes.Buffer, error) {
  183. params := bytes.NewBuffer(nil)
  184. if data != nil {
  185. if err := json.NewEncoder(params).Encode(data); err != nil {
  186. return nil, err
  187. }
  188. }
  189. return params, nil
  190. }
  191. func ensureReaderClosed(response serverResponse) {
  192. if body := response.body; body != nil {
  193. // Drain up to 512 bytes and close the body to let the Transport reuse the connection
  194. io.CopyN(ioutil.Discard, body, 512)
  195. response.body.Close()
  196. }
  197. }