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