request.go 6.7 KB

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