request.go 8.4 KB

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