request.go 6.6 KB

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