1
0
Fork 0
mirror of https://github.com/moby/moby.git synced 2022-11-09 12:21:53 -05:00
moby--moby/testutil/request/request.go

216 lines
6.6 KiB
Go
Raw Normal View History

package request // import "github.com/docker/docker/testutil/request"
import (
"context"
"crypto/tls"
"fmt"
"io"
"net"
"net/http"
"net/url"
"os"
"path/filepath"
"testing"
"time"
"github.com/docker/docker/client"
"github.com/docker/docker/pkg/ioutils"
"github.com/docker/docker/testutil/environment"
"github.com/docker/go-connections/sockets"
"github.com/docker/go-connections/tlsconfig"
"github.com/pkg/errors"
"gotest.tools/v3/assert"
)
// NewAPIClient returns a docker API client configured from environment variables
func NewAPIClient(t testing.TB, ops ...client.Opt) client.APIClient {
t.Helper()
ops = append([]client.Opt{client.FromEnv}, ops...)
clt, err := client.NewClientWithOpts(ops...)
assert.NilError(t, err)
return clt
}
// DaemonTime provides the current time on the daemon host
func DaemonTime(ctx context.Context, t testing.TB, client client.APIClient, testEnv *environment.Execution) time.Time {
t.Helper()
if testEnv.IsLocalDaemon() {
return time.Now()
}
info, err := client.Info(ctx)
assert.NilError(t, err)
dt, err := time.Parse(time.RFC3339Nano, info.SystemTime)
assert.NilError(t, err, "invalid time format in GET /info response")
return dt
}
// DaemonUnixTime returns the current time on the daemon host with nanoseconds precision.
// It return the time formatted how the client sends timestamps to the server.
func DaemonUnixTime(ctx context.Context, t testing.TB, client client.APIClient, testEnv *environment.Execution) string {
t.Helper()
dt := DaemonTime(ctx, t, client, testEnv)
return fmt.Sprintf("%d.%09d", dt.Unix(), int64(dt.Nanosecond()))
}
// Post creates and execute a POST request on the specified host and endpoint, with the specified request modifiers
func Post(endpoint string, modifiers ...func(*Options)) (*http.Response, io.ReadCloser, error) {
return Do(endpoint, append(modifiers, Method(http.MethodPost))...)
}
// Delete creates and execute a DELETE request on the specified host and endpoint, with the specified request modifiers
func Delete(endpoint string, modifiers ...func(*Options)) (*http.Response, io.ReadCloser, error) {
return Do(endpoint, append(modifiers, Method(http.MethodDelete))...)
}
// Get creates and execute a GET request on the specified host and endpoint, with the specified request modifiers
func Get(endpoint string, modifiers ...func(*Options)) (*http.Response, io.ReadCloser, error) {
return Do(endpoint, modifiers...)
}
Add HEAD support for /_ping endpoint Monitoring systems and load balancers are usually configured to use HEAD requests for health monitoring. The /_ping endpoint currently does not support this type of request, which means that those systems have fallback to GET requests. This patch adds support for HEAD requests on the /_ping endpoint. Although optional, this patch also returns `Content-Type` and `Content-Length` headers in case of a HEAD request; Refering to RFC 7231, section 4.3.2: The HEAD method is identical to GET except that the server MUST NOT send a message body in the response (i.e., the response terminates at the end of the header section). The server SHOULD send the same header fields in response to a HEAD request as it would have sent if the request had been a GET, except that the payload header fields (Section 3.3) MAY be omitted. This method can be used for obtaining metadata about the selected representation without transferring the representation data and is often used for testing hypertext links for validity, accessibility, and recent modification. A payload within a HEAD request message has no defined semantics; sending a payload body on a HEAD request might cause some existing implementations to reject the request. The response to a HEAD request is cacheable; a cache MAY use it to satisfy subsequent HEAD requests unless otherwise indicated by the Cache-Control header field (Section 5.2 of [RFC7234]). A HEAD response might also have an effect on previously cached responses to GET; see Section 4.3.5 of [RFC7234]. With this patch applied, either `GET` or `HEAD` requests work; the only difference is that the body is empty in case of a `HEAD` request; curl -i --unix-socket /var/run/docker.sock http://localhost/_ping HTTP/1.1 200 OK Api-Version: 1.40 Cache-Control: no-cache, no-store, must-revalidate Docker-Experimental: false Ostype: linux Pragma: no-cache Server: Docker/dev (linux) Date: Mon, 14 Jan 2019 12:35:16 GMT Content-Length: 2 Content-Type: text/plain; charset=utf-8 OK curl --head -i --unix-socket /var/run/docker.sock http://localhost/_ping HTTP/1.1 200 OK Api-Version: 1.40 Cache-Control: no-cache, no-store, must-revalidate Content-Length: 0 Content-Type: text/plain; charset=utf-8 Docker-Experimental: false Ostype: linux Pragma: no-cache Server: Docker/dev (linux) Date: Mon, 14 Jan 2019 12:34:15 GMT The client is also updated to use `HEAD` by default, but fallback to `GET` if the daemon does not support this method. Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2019-01-14 12:08:49 -05:00
// Head creates and execute a HEAD request on the specified host and endpoint, with the specified request modifiers
func Head(endpoint string, modifiers ...func(*Options)) (*http.Response, io.ReadCloser, error) {
return Do(endpoint, append(modifiers, Method(http.MethodHead))...)
}
// Do creates and execute a request on the specified endpoint, with the specified request modifiers
func Do(endpoint string, modifiers ...func(*Options)) (*http.Response, io.ReadCloser, error) {
opts := &Options{
host: DaemonHost(),
}
for _, mod := range modifiers {
mod(opts)
}
req, err := newRequest(endpoint, opts)
if err != nil {
return nil, nil, err
}
client, err := newHTTPClient(opts.host)
if err != nil {
return nil, nil, err
}
resp, err := client.Do(req)
var body io.ReadCloser
if resp != nil {
body = ioutils.NewReadCloserWrapper(resp.Body, func() error {
defer resp.Body.Close()
return nil
})
}
return resp, body, err
}
// ReadBody read the specified ReadCloser content and returns it
func ReadBody(b io.ReadCloser) ([]byte, error) {
defer b.Close()
return io.ReadAll(b)
}
// newRequest creates a new http Request to the specified host and endpoint, with the specified request modifiers
func newRequest(endpoint string, opts *Options) (*http.Request, error) {
hostURL, err := client.ParseHostURL(opts.host)
if err != nil {
return nil, errors.Wrapf(err, "failed parsing url %q", opts.host)
}
req, err := http.NewRequest(http.MethodGet, endpoint, nil)
if err != nil {
return nil, errors.Wrap(err, "failed to create request")
}
if os.Getenv("DOCKER_TLS_VERIFY") != "" {
req.URL.Scheme = "https"
} else {
req.URL.Scheme = "http"
}
req.URL.Host = hostURL.Host
for _, config := range opts.requestModifiers {
if err := config(req); err != nil {
return nil, err
}
}
return req, nil
}
// newHTTPClient creates an http client for the specific host
// TODO: Share more code with client.defaultHTTPClient
func newHTTPClient(host string) (*http.Client, error) {
// FIXME(vdemeester) 10*time.Second timeout of SockRequest… ?
hostURL, err := client.ParseHostURL(host)
if err != nil {
return nil, err
}
transport := new(http.Transport)
if hostURL.Scheme == "tcp" && os.Getenv("DOCKER_TLS_VERIFY") != "" {
// Setup the socket TLS configuration.
tlsConfig, err := getTLSConfig()
if err != nil {
return nil, err
}
transport = &http.Transport{TLSClientConfig: tlsConfig}
}
transport.DisableKeepAlives = true
err = sockets.ConfigureTransport(transport, hostURL.Scheme, hostURL.Host)
return &http.Client{Transport: transport}, err
}
func getTLSConfig() (*tls.Config, error) {
dockerCertPath := os.Getenv("DOCKER_CERT_PATH")
if dockerCertPath == "" {
return nil, errors.New("DOCKER_TLS_VERIFY specified, but no DOCKER_CERT_PATH environment variable")
}
option := &tlsconfig.Options{
CAFile: filepath.Join(dockerCertPath, "ca.pem"),
CertFile: filepath.Join(dockerCertPath, "cert.pem"),
KeyFile: filepath.Join(dockerCertPath, "key.pem"),
}
tlsConfig, err := tlsconfig.Client(*option)
if err != nil {
return nil, err
}
return tlsConfig, nil
}
// DaemonHost return the daemon host string for this test execution
func DaemonHost() string {
daemonURLStr := client.DefaultDockerHost
if daemonHostVar := os.Getenv("DOCKER_HOST"); daemonHostVar != "" {
daemonURLStr = daemonHostVar
}
return daemonURLStr
}
// SockConn opens a connection on the specified socket
func SockConn(timeout time.Duration, daemon string) (net.Conn, error) {
daemonURL, err := url.Parse(daemon)
if err != nil {
return nil, errors.Wrapf(err, "could not parse url %q", daemon)
}
var c net.Conn
switch daemonURL.Scheme {
case "npipe":
return npipeDial(daemonURL.Path, timeout)
case "unix":
return net.DialTimeout(daemonURL.Scheme, daemonURL.Path, timeout)
case "tcp":
if os.Getenv("DOCKER_TLS_VERIFY") != "" {
// Setup the socket TLS configuration.
tlsConfig, err := getTLSConfig()
if err != nil {
return nil, err
}
dialer := &net.Dialer{Timeout: timeout}
return tls.DialWithDialer(dialer, daemonURL.Scheme, daemonURL.Host, tlsConfig)
}
return net.DialTimeout(daemonURL.Scheme, daemonURL.Host, timeout)
default:
return c, errors.Errorf("unknown scheme %v (%s)", daemonURL.Scheme, daemon)
}
}