request.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. package request // import "github.com/docker/docker/testutil/request"
  2. import (
  3. "context"
  4. "crypto/tls"
  5. "fmt"
  6. "io"
  7. "net"
  8. "net/http"
  9. "net/url"
  10. "os"
  11. "path/filepath"
  12. "testing"
  13. "time"
  14. "github.com/docker/docker/client"
  15. "github.com/docker/docker/pkg/ioutils"
  16. "github.com/docker/docker/testutil/environment"
  17. "github.com/docker/go-connections/sockets"
  18. "github.com/docker/go-connections/tlsconfig"
  19. "github.com/pkg/errors"
  20. "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
  21. "gotest.tools/v3/assert"
  22. )
  23. // NewAPIClient returns a docker API client configured from environment variables
  24. func NewAPIClient(t testing.TB, ops ...client.Opt) client.APIClient {
  25. t.Helper()
  26. ops = append([]client.Opt{client.FromEnv}, ops...)
  27. clt, err := client.NewClientWithOpts(ops...)
  28. assert.NilError(t, err)
  29. return clt
  30. }
  31. // DaemonTime provides the current time on the daemon host
  32. func DaemonTime(ctx context.Context, t testing.TB, client client.APIClient, testEnv *environment.Execution) time.Time {
  33. t.Helper()
  34. if testEnv.IsLocalDaemon() {
  35. return time.Now()
  36. }
  37. info, err := client.Info(ctx)
  38. assert.NilError(t, err)
  39. dt, err := time.Parse(time.RFC3339Nano, info.SystemTime)
  40. assert.NilError(t, err, "invalid time format in GET /info response")
  41. return dt
  42. }
  43. // DaemonUnixTime returns the current time on the daemon host with nanoseconds precision.
  44. // It return the time formatted how the client sends timestamps to the server.
  45. func DaemonUnixTime(ctx context.Context, t testing.TB, client client.APIClient, testEnv *environment.Execution) string {
  46. t.Helper()
  47. dt := DaemonTime(ctx, t, client, testEnv)
  48. return fmt.Sprintf("%d.%09d", dt.Unix(), int64(dt.Nanosecond()))
  49. }
  50. // Post creates and execute a POST request on the specified host and endpoint, with the specified request modifiers
  51. func Post(ctx context.Context, endpoint string, modifiers ...func(*Options)) (*http.Response, io.ReadCloser, error) {
  52. return Do(ctx, endpoint, append(modifiers, Method(http.MethodPost))...)
  53. }
  54. // Delete creates and execute a DELETE request on the specified host and endpoint, with the specified request modifiers
  55. func Delete(ctx context.Context, endpoint string, modifiers ...func(*Options)) (*http.Response, io.ReadCloser, error) {
  56. return Do(ctx, endpoint, append(modifiers, Method(http.MethodDelete))...)
  57. }
  58. // Get creates and execute a GET request on the specified host and endpoint, with the specified request modifiers
  59. func Get(ctx context.Context, endpoint string, modifiers ...func(*Options)) (*http.Response, io.ReadCloser, error) {
  60. return Do(ctx, endpoint, modifiers...)
  61. }
  62. // Head creates and execute a HEAD request on the specified host and endpoint, with the specified request modifiers
  63. func Head(ctx context.Context, endpoint string, modifiers ...func(*Options)) (*http.Response, io.ReadCloser, error) {
  64. return Do(ctx, endpoint, append(modifiers, Method(http.MethodHead))...)
  65. }
  66. // Do creates and execute a request on the specified endpoint, with the specified request modifiers
  67. func Do(ctx context.Context, endpoint string, modifiers ...func(*Options)) (*http.Response, io.ReadCloser, error) {
  68. opts := &Options{
  69. host: DaemonHost(),
  70. }
  71. for _, mod := range modifiers {
  72. mod(opts)
  73. }
  74. req, err := newRequest(endpoint, opts)
  75. if err != nil {
  76. return nil, nil, err
  77. }
  78. req = req.WithContext(ctx)
  79. httpClient, err := newHTTPClient(opts.host)
  80. if err != nil {
  81. return nil, nil, err
  82. }
  83. resp, err := httpClient.Do(req)
  84. var body io.ReadCloser
  85. if resp != nil {
  86. body = ioutils.NewReadCloserWrapper(resp.Body, func() error {
  87. defer resp.Body.Close()
  88. return nil
  89. })
  90. }
  91. return resp, body, err
  92. }
  93. // ReadBody read the specified ReadCloser content and returns it
  94. func ReadBody(b io.ReadCloser) ([]byte, error) {
  95. defer b.Close()
  96. return io.ReadAll(b)
  97. }
  98. // newRequest creates a new http Request to the specified host and endpoint, with the specified request modifiers
  99. func newRequest(endpoint string, opts *Options) (*http.Request, error) {
  100. hostURL, err := client.ParseHostURL(opts.host)
  101. if err != nil {
  102. return nil, errors.Wrapf(err, "failed parsing url %q", opts.host)
  103. }
  104. req, err := http.NewRequest(http.MethodGet, endpoint, nil)
  105. if err != nil {
  106. return nil, errors.Wrap(err, "failed to create request")
  107. }
  108. if os.Getenv("DOCKER_TLS_VERIFY") != "" {
  109. req.URL.Scheme = "https"
  110. } else {
  111. req.URL.Scheme = "http"
  112. }
  113. req.URL.Host = hostURL.Host
  114. if hostURL.Scheme == "unix" || hostURL.Scheme == "npipe" {
  115. // Override host header for non-tcp connections.
  116. req.Host = client.DummyHost
  117. }
  118. for _, config := range opts.requestModifiers {
  119. if err := config(req); err != nil {
  120. return nil, err
  121. }
  122. }
  123. return req, nil
  124. }
  125. // newHTTPClient creates an http client for the specific host
  126. // TODO: Share more code with client.defaultHTTPClient
  127. func newHTTPClient(host string) (*http.Client, error) {
  128. // FIXME(vdemeester) 10*time.Second timeout of SockRequest… ?
  129. hostURL, err := client.ParseHostURL(host)
  130. if err != nil {
  131. return nil, err
  132. }
  133. transport := new(http.Transport)
  134. if hostURL.Scheme == "tcp" && os.Getenv("DOCKER_TLS_VERIFY") != "" {
  135. // Setup the socket TLS configuration.
  136. tlsConfig, err := getTLSConfig()
  137. if err != nil {
  138. return nil, err
  139. }
  140. transport = &http.Transport{TLSClientConfig: tlsConfig}
  141. }
  142. transport.DisableKeepAlives = true
  143. err = sockets.ConfigureTransport(transport, hostURL.Scheme, hostURL.Host)
  144. return &http.Client{Transport: otelhttp.NewTransport(transport)}, err
  145. }
  146. func getTLSConfig() (*tls.Config, error) {
  147. dockerCertPath := os.Getenv("DOCKER_CERT_PATH")
  148. if dockerCertPath == "" {
  149. return nil, errors.New("DOCKER_TLS_VERIFY specified, but no DOCKER_CERT_PATH environment variable")
  150. }
  151. option := &tlsconfig.Options{
  152. CAFile: filepath.Join(dockerCertPath, "ca.pem"),
  153. CertFile: filepath.Join(dockerCertPath, "cert.pem"),
  154. KeyFile: filepath.Join(dockerCertPath, "key.pem"),
  155. }
  156. tlsConfig, err := tlsconfig.Client(*option)
  157. if err != nil {
  158. return nil, err
  159. }
  160. return tlsConfig, nil
  161. }
  162. // DaemonHost return the daemon host string for this test execution
  163. func DaemonHost() string {
  164. daemonURLStr := client.DefaultDockerHost
  165. if daemonHostVar := os.Getenv("DOCKER_HOST"); daemonHostVar != "" {
  166. daemonURLStr = daemonHostVar
  167. }
  168. return daemonURLStr
  169. }
  170. // SockConn opens a connection on the specified socket
  171. func SockConn(timeout time.Duration, daemon string) (net.Conn, error) {
  172. daemonURL, err := url.Parse(daemon)
  173. if err != nil {
  174. return nil, errors.Wrapf(err, "could not parse url %q", daemon)
  175. }
  176. var c net.Conn
  177. switch daemonURL.Scheme {
  178. case "npipe":
  179. return npipeDial(daemonURL.Path, timeout)
  180. case "unix":
  181. return net.DialTimeout(daemonURL.Scheme, daemonURL.Path, timeout)
  182. case "tcp":
  183. if os.Getenv("DOCKER_TLS_VERIFY") != "" {
  184. // Setup the socket TLS configuration.
  185. tlsConfig, err := getTLSConfig()
  186. if err != nil {
  187. return nil, err
  188. }
  189. dialer := &net.Dialer{Timeout: timeout}
  190. return tls.DialWithDialer(dialer, daemonURL.Scheme, daemonURL.Host, tlsConfig)
  191. }
  192. return net.DialTimeout(daemonURL.Scheme, daemonURL.Host, timeout)
  193. default:
  194. return c, errors.Errorf("unknown scheme %v (%s)", daemonURL.Scheme, daemon)
  195. }
  196. }