request.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  1. package request // import "github.com/docker/docker/integration-cli/request"
  2. import (
  3. "bytes"
  4. "crypto/tls"
  5. "encoding/json"
  6. "io"
  7. "io/ioutil"
  8. "net"
  9. "net/http"
  10. "net/url"
  11. "os"
  12. "path/filepath"
  13. "strings"
  14. "time"
  15. dclient "github.com/docker/docker/client"
  16. "github.com/docker/docker/opts"
  17. "github.com/docker/docker/pkg/ioutils"
  18. "github.com/docker/go-connections/sockets"
  19. "github.com/docker/go-connections/tlsconfig"
  20. "github.com/pkg/errors"
  21. )
  22. // Method creates a modifier that sets the specified string as the request method
  23. func Method(method string) func(*http.Request) error {
  24. return func(req *http.Request) error {
  25. req.Method = method
  26. return nil
  27. }
  28. }
  29. // RawString sets the specified string as body for the request
  30. func RawString(content string) func(*http.Request) error {
  31. return RawContent(ioutil.NopCloser(strings.NewReader(content)))
  32. }
  33. // RawContent sets the specified reader as body for the request
  34. func RawContent(reader io.ReadCloser) func(*http.Request) error {
  35. return func(req *http.Request) error {
  36. req.Body = reader
  37. return nil
  38. }
  39. }
  40. // ContentType sets the specified Content-Type request header
  41. func ContentType(contentType string) func(*http.Request) error {
  42. return func(req *http.Request) error {
  43. req.Header.Set("Content-Type", contentType)
  44. return nil
  45. }
  46. }
  47. // JSON sets the Content-Type request header to json
  48. func JSON(req *http.Request) error {
  49. return ContentType("application/json")(req)
  50. }
  51. // JSONBody creates a modifier that encodes the specified data to a JSON string and set it as request body. It also sets
  52. // the Content-Type header of the request.
  53. func JSONBody(data interface{}) func(*http.Request) error {
  54. return func(req *http.Request) error {
  55. jsonData := bytes.NewBuffer(nil)
  56. if err := json.NewEncoder(jsonData).Encode(data); err != nil {
  57. return err
  58. }
  59. req.Body = ioutil.NopCloser(jsonData)
  60. req.Header.Set("Content-Type", "application/json")
  61. return nil
  62. }
  63. }
  64. // Post creates and execute a POST request on the specified host and endpoint, with the specified request modifiers
  65. func Post(endpoint string, modifiers ...func(*http.Request) error) (*http.Response, io.ReadCloser, error) {
  66. return Do(endpoint, append(modifiers, Method(http.MethodPost))...)
  67. }
  68. // Delete creates and execute a DELETE request on the specified host and endpoint, with the specified request modifiers
  69. func Delete(endpoint string, modifiers ...func(*http.Request) error) (*http.Response, io.ReadCloser, error) {
  70. return Do(endpoint, append(modifiers, Method(http.MethodDelete))...)
  71. }
  72. // Get creates and execute a GET request on the specified host and endpoint, with the specified request modifiers
  73. func Get(endpoint string, modifiers ...func(*http.Request) error) (*http.Response, io.ReadCloser, error) {
  74. return Do(endpoint, modifiers...)
  75. }
  76. // Do creates and execute a request on the specified endpoint, with the specified request modifiers
  77. func Do(endpoint string, modifiers ...func(*http.Request) error) (*http.Response, io.ReadCloser, error) {
  78. return DoOnHost(DaemonHost(), endpoint, modifiers...)
  79. }
  80. // DoOnHost creates and execute a request on the specified host and endpoint, with the specified request modifiers
  81. func DoOnHost(host, endpoint string, modifiers ...func(*http.Request) error) (*http.Response, io.ReadCloser, error) {
  82. req, err := newRequest(host, endpoint, modifiers...)
  83. if err != nil {
  84. return nil, nil, err
  85. }
  86. client, err := newHTTPClient(host)
  87. if err != nil {
  88. return nil, nil, err
  89. }
  90. resp, err := client.Do(req)
  91. var body io.ReadCloser
  92. if resp != nil {
  93. body = ioutils.NewReadCloserWrapper(resp.Body, func() error {
  94. defer resp.Body.Close()
  95. return nil
  96. })
  97. }
  98. return resp, body, err
  99. }
  100. // newRequest creates a new http Request to the specified host and endpoint, with the specified request modifiers
  101. func newRequest(host, endpoint string, modifiers ...func(*http.Request) error) (*http.Request, error) {
  102. hostUrl, err := dclient.ParseHostURL(host)
  103. if err != nil {
  104. return nil, errors.Wrapf(err, "failed parsing url %q", 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 modifiers {
  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 := dclient.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. // NewClient returns a new Docker API client
  145. // Deprecated: Use Execution.APIClient()
  146. func NewClient() (dclient.APIClient, error) {
  147. return dclient.NewClientWithOpts(dclient.WithHost(DaemonHost()))
  148. }
  149. // ReadBody read the specified ReadCloser content and returns it
  150. func ReadBody(b io.ReadCloser) ([]byte, error) {
  151. defer b.Close()
  152. return ioutil.ReadAll(b)
  153. }
  154. // SockConn opens a connection on the specified socket
  155. func SockConn(timeout time.Duration, daemon string) (net.Conn, error) {
  156. daemonURL, err := url.Parse(daemon)
  157. if err != nil {
  158. return nil, errors.Wrapf(err, "could not parse url %q", daemon)
  159. }
  160. var c net.Conn
  161. switch daemonURL.Scheme {
  162. case "npipe":
  163. return npipeDial(daemonURL.Path, timeout)
  164. case "unix":
  165. return net.DialTimeout(daemonURL.Scheme, daemonURL.Path, timeout)
  166. case "tcp":
  167. if os.Getenv("DOCKER_TLS_VERIFY") != "" {
  168. // Setup the socket TLS configuration.
  169. tlsConfig, err := getTLSConfig()
  170. if err != nil {
  171. return nil, err
  172. }
  173. dialer := &net.Dialer{Timeout: timeout}
  174. return tls.DialWithDialer(dialer, daemonURL.Scheme, daemonURL.Host, tlsConfig)
  175. }
  176. return net.DialTimeout(daemonURL.Scheme, daemonURL.Host, timeout)
  177. default:
  178. return c, errors.Errorf("unknown scheme %v (%s)", daemonURL.Scheme, daemon)
  179. }
  180. }
  181. func getTLSConfig() (*tls.Config, error) {
  182. dockerCertPath := os.Getenv("DOCKER_CERT_PATH")
  183. if dockerCertPath == "" {
  184. return nil, errors.New("DOCKER_TLS_VERIFY specified, but no DOCKER_CERT_PATH environment variable")
  185. }
  186. option := &tlsconfig.Options{
  187. CAFile: filepath.Join(dockerCertPath, "ca.pem"),
  188. CertFile: filepath.Join(dockerCertPath, "cert.pem"),
  189. KeyFile: filepath.Join(dockerCertPath, "key.pem"),
  190. }
  191. tlsConfig, err := tlsconfig.Client(*option)
  192. if err != nil {
  193. return nil, err
  194. }
  195. return tlsConfig, nil
  196. }
  197. // DaemonHost return the daemon host string for this test execution
  198. func DaemonHost() string {
  199. daemonURLStr := "unix://" + opts.DefaultUnixSocket
  200. if daemonHostVar := os.Getenv("DOCKER_HOST"); daemonHostVar != "" {
  201. daemonURLStr = daemonHostVar
  202. }
  203. return daemonURLStr
  204. }