request.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  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/gotestyourself/gotestyourself/assert"
  22. "github.com/pkg/errors"
  23. )
  24. // NewAPIClient returns a docker API client configured from environment variables
  25. func NewAPIClient(t assert.TestingT, ops ...func(*client.Client) error) client.APIClient {
  26. if ht, ok := t.(test.HelperT); ok {
  27. ht.Helper()
  28. }
  29. ops = append([]func(*client.Client) error{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. // Do creates and execute a request on the specified endpoint, with the specified request modifiers
  70. func Do(endpoint string, modifiers ...func(*Options)) (*http.Response, io.ReadCloser, error) {
  71. opts := &Options{
  72. host: DaemonHost(),
  73. }
  74. for _, mod := range modifiers {
  75. mod(opts)
  76. }
  77. req, err := newRequest(endpoint, opts)
  78. if err != nil {
  79. return nil, nil, err
  80. }
  81. client, err := newHTTPClient(opts.host)
  82. if err != nil {
  83. return nil, nil, err
  84. }
  85. resp, err := client.Do(req)
  86. var body io.ReadCloser
  87. if resp != nil {
  88. body = ioutils.NewReadCloserWrapper(resp.Body, func() error {
  89. defer resp.Body.Close()
  90. return nil
  91. })
  92. }
  93. return resp, body, err
  94. }
  95. // ReadBody read the specified ReadCloser content and returns it
  96. func ReadBody(b io.ReadCloser) ([]byte, error) {
  97. defer b.Close()
  98. return ioutil.ReadAll(b)
  99. }
  100. // newRequest creates a new http Request to the specified host and endpoint, with the specified request modifiers
  101. func newRequest(endpoint string, opts *Options) (*http.Request, error) {
  102. hostURL, err := client.ParseHostURL(opts.host)
  103. if err != nil {
  104. return nil, errors.Wrapf(err, "failed parsing url %q", opts.host)
  105. }
  106. req, err := http.NewRequest("GET", endpoint, nil)
  107. if err != nil {
  108. return nil, errors.Wrap(err, "failed to create request")
  109. }
  110. if os.Getenv("DOCKER_TLS_VERIFY") != "" {
  111. req.URL.Scheme = "https"
  112. } else {
  113. req.URL.Scheme = "http"
  114. }
  115. req.URL.Host = hostURL.Host
  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 := "unix://" + opts.DefaultUnixSocket
  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. }