request.go 6.8 KB

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