request.go 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. package request
  2. import (
  3. "bufio"
  4. "bytes"
  5. "crypto/tls"
  6. "encoding/json"
  7. "fmt"
  8. "io"
  9. "io/ioutil"
  10. "net"
  11. "net/http"
  12. "net/http/httputil"
  13. "net/url"
  14. "os"
  15. "path/filepath"
  16. "strings"
  17. "time"
  18. dclient "github.com/docker/docker/client"
  19. "github.com/docker/docker/opts"
  20. "github.com/docker/docker/pkg/ioutils"
  21. "github.com/docker/docker/pkg/testutil"
  22. "github.com/docker/go-connections/sockets"
  23. "github.com/docker/go-connections/tlsconfig"
  24. "github.com/pkg/errors"
  25. )
  26. // Method creates a modifier that sets the specified string as the request method
  27. func Method(method string) func(*http.Request) error {
  28. return func(req *http.Request) error {
  29. req.Method = method
  30. return nil
  31. }
  32. }
  33. // RawString sets the specified string as body for the request
  34. func RawString(content string) func(*http.Request) error {
  35. return RawContent(ioutil.NopCloser(strings.NewReader(content)))
  36. }
  37. // RawContent sets the specified reader as body for the request
  38. func RawContent(reader io.ReadCloser) func(*http.Request) error {
  39. return func(req *http.Request) error {
  40. req.Body = reader
  41. return nil
  42. }
  43. }
  44. // ContentType sets the specified Content-Type request header
  45. func ContentType(contentType string) func(*http.Request) error {
  46. return func(req *http.Request) error {
  47. req.Header.Set("Content-Type", contentType)
  48. return nil
  49. }
  50. }
  51. // JSON sets the Content-Type request header to json
  52. func JSON(req *http.Request) error {
  53. return ContentType("application/json")(req)
  54. }
  55. // JSONBody creates a modifier that encodes the specified data to a JSON string and set it as request body. It also sets
  56. // the Content-Type header of the request.
  57. func JSONBody(data interface{}) func(*http.Request) error {
  58. return func(req *http.Request) error {
  59. jsonData := bytes.NewBuffer(nil)
  60. if err := json.NewEncoder(jsonData).Encode(data); err != nil {
  61. return err
  62. }
  63. req.Body = ioutil.NopCloser(jsonData)
  64. req.Header.Set("Content-Type", "application/json")
  65. return nil
  66. }
  67. }
  68. // Post creates and execute a POST request on the specified host and endpoint, with the specified request modifiers
  69. func Post(endpoint string, modifiers ...func(*http.Request) error) (*http.Response, io.ReadCloser, error) {
  70. return Do(endpoint, append(modifiers, Method(http.MethodPost))...)
  71. }
  72. // Delete creates and execute a DELETE request on the specified host and endpoint, with the specified request modifiers
  73. func Delete(endpoint string, modifiers ...func(*http.Request) error) (*http.Response, io.ReadCloser, error) {
  74. return Do(endpoint, append(modifiers, Method(http.MethodDelete))...)
  75. }
  76. // Get creates and execute a GET request on the specified host and endpoint, with the specified request modifiers
  77. func Get(endpoint string, modifiers ...func(*http.Request) error) (*http.Response, io.ReadCloser, error) {
  78. return Do(endpoint, modifiers...)
  79. }
  80. // Do creates and execute a request on the specified endpoint, with the specified request modifiers
  81. func Do(endpoint string, modifiers ...func(*http.Request) error) (*http.Response, io.ReadCloser, error) {
  82. return DoOnHost(DaemonHost(), endpoint, modifiers...)
  83. }
  84. // DoOnHost creates and execute a request on the specified host and endpoint, with the specified request modifiers
  85. func DoOnHost(host, endpoint string, modifiers ...func(*http.Request) error) (*http.Response, io.ReadCloser, error) {
  86. req, err := New(host, endpoint, modifiers...)
  87. if err != nil {
  88. return nil, nil, err
  89. }
  90. client, err := NewClient(host)
  91. if err != nil {
  92. return nil, nil, err
  93. }
  94. resp, err := client.Do(req)
  95. var body io.ReadCloser
  96. if resp != nil {
  97. body = ioutils.NewReadCloserWrapper(resp.Body, func() error {
  98. defer resp.Body.Close()
  99. return nil
  100. })
  101. }
  102. return resp, body, err
  103. }
  104. // New creates a new http Request to the specified host and endpoint, with the specified request modifiers
  105. func New(host, endpoint string, modifiers ...func(*http.Request) error) (*http.Request, error) {
  106. _, addr, _, err := dclient.ParseHost(host)
  107. if err != nil {
  108. return nil, err
  109. }
  110. if err != nil {
  111. return nil, errors.Wrapf(err, "could not parse url %q", host)
  112. }
  113. req, err := http.NewRequest("GET", endpoint, nil)
  114. if err != nil {
  115. return nil, fmt.Errorf("could not create new request: %v", err)
  116. }
  117. req.URL.Scheme = "http"
  118. req.URL.Host = addr
  119. for _, config := range modifiers {
  120. if err := config(req); err != nil {
  121. return nil, err
  122. }
  123. }
  124. return req, nil
  125. }
  126. // NewClient creates an http client for the specific host
  127. func NewClient(host string) (*http.Client, error) {
  128. // FIXME(vdemeester) 10*time.Second timeout of SockRequest… ?
  129. proto, addr, _, err := dclient.ParseHost(host)
  130. if err != nil {
  131. return nil, err
  132. }
  133. transport := new(http.Transport)
  134. if proto == "tcp" && os.Getenv("DOCKER_TLS_VERIFY") != "" {
  135. // Setup the socket TLS configuration.
  136. tlsConfig, err := getTLSConfig()
  137. if err != nil {
  138. return nil, err
  139. }
  140. transport = &http.Transport{TLSClientConfig: tlsConfig}
  141. }
  142. transport.DisableKeepAlives = true
  143. err = sockets.ConfigureTransport(transport, proto, addr)
  144. return &http.Client{
  145. Transport: transport,
  146. }, err
  147. }
  148. // FIXME(vdemeester) httputil.ClientConn is deprecated, use http.Client instead (closer to actual client)
  149. // Deprecated: Use New instead of NewRequestClient
  150. // Deprecated: use request.Do (or Get, Delete, Post) instead
  151. func newRequestClient(method, endpoint string, data io.Reader, ct, daemon string, modifiers ...func(*http.Request)) (*http.Request, *httputil.ClientConn, error) {
  152. c, err := SockConn(time.Duration(10*time.Second), daemon)
  153. if err != nil {
  154. return nil, nil, fmt.Errorf("could not dial docker daemon: %v", err)
  155. }
  156. client := httputil.NewClientConn(c, nil)
  157. req, err := http.NewRequest(method, endpoint, data)
  158. if err != nil {
  159. client.Close()
  160. return nil, nil, fmt.Errorf("could not create new request: %v", err)
  161. }
  162. for _, opt := range modifiers {
  163. opt(req)
  164. }
  165. if ct != "" {
  166. req.Header.Set("Content-Type", ct)
  167. }
  168. return req, client, nil
  169. }
  170. // SockRequest create a request against the specified host (with method, endpoint and other request modifier) and
  171. // returns the status code, and the content as an byte slice
  172. // Deprecated: use request.Do instead
  173. func SockRequest(method, endpoint string, data interface{}, daemon string, modifiers ...func(*http.Request)) (int, []byte, error) {
  174. jsonData := bytes.NewBuffer(nil)
  175. if err := json.NewEncoder(jsonData).Encode(data); err != nil {
  176. return -1, nil, err
  177. }
  178. res, body, err := SockRequestRaw(method, endpoint, jsonData, "application/json", daemon, modifiers...)
  179. if err != nil {
  180. return -1, nil, err
  181. }
  182. b, err := testutil.ReadBody(body)
  183. return res.StatusCode, b, err
  184. }
  185. // SockRequestRaw create a request against the specified host (with method, endpoint and other request modifier) and
  186. // returns the http response, the output as a io.ReadCloser
  187. // Deprecated: use request.Do (or Get, Delete, Post) instead
  188. func SockRequestRaw(method, endpoint string, data io.Reader, ct, daemon string, modifiers ...func(*http.Request)) (*http.Response, io.ReadCloser, error) {
  189. req, client, err := newRequestClient(method, endpoint, data, ct, daemon, modifiers...)
  190. if err != nil {
  191. return nil, nil, err
  192. }
  193. resp, err := client.Do(req)
  194. if err != nil {
  195. client.Close()
  196. return resp, nil, err
  197. }
  198. body := ioutils.NewReadCloserWrapper(resp.Body, func() error {
  199. defer resp.Body.Close()
  200. return client.Close()
  201. })
  202. return resp, body, err
  203. }
  204. // SockRequestHijack creates a connection to specified host (with method, contenttype, …) and returns a hijacked connection
  205. // and the output as a `bufio.Reader`
  206. func SockRequestHijack(method, endpoint string, data io.Reader, ct string, daemon string, modifiers ...func(*http.Request)) (net.Conn, *bufio.Reader, error) {
  207. req, client, err := newRequestClient(method, endpoint, data, ct, daemon, modifiers...)
  208. if err != nil {
  209. return nil, nil, err
  210. }
  211. client.Do(req)
  212. conn, br := client.Hijack()
  213. return conn, br, nil
  214. }
  215. // SockConn opens a connection on the specified socket
  216. func SockConn(timeout time.Duration, daemon string) (net.Conn, error) {
  217. daemonURL, err := url.Parse(daemon)
  218. if err != nil {
  219. return nil, errors.Wrapf(err, "could not parse url %q", daemon)
  220. }
  221. var c net.Conn
  222. switch daemonURL.Scheme {
  223. case "npipe":
  224. return npipeDial(daemonURL.Path, timeout)
  225. case "unix":
  226. return net.DialTimeout(daemonURL.Scheme, daemonURL.Path, timeout)
  227. case "tcp":
  228. if os.Getenv("DOCKER_TLS_VERIFY") != "" {
  229. // Setup the socket TLS configuration.
  230. tlsConfig, err := getTLSConfig()
  231. if err != nil {
  232. return nil, err
  233. }
  234. dialer := &net.Dialer{Timeout: timeout}
  235. return tls.DialWithDialer(dialer, daemonURL.Scheme, daemonURL.Host, tlsConfig)
  236. }
  237. return net.DialTimeout(daemonURL.Scheme, daemonURL.Host, timeout)
  238. default:
  239. return c, errors.Errorf("unknown scheme %v (%s)", daemonURL.Scheme, daemon)
  240. }
  241. }
  242. func getTLSConfig() (*tls.Config, error) {
  243. dockerCertPath := os.Getenv("DOCKER_CERT_PATH")
  244. if dockerCertPath == "" {
  245. return nil, errors.New("DOCKER_TLS_VERIFY specified, but no DOCKER_CERT_PATH environment variable")
  246. }
  247. option := &tlsconfig.Options{
  248. CAFile: filepath.Join(dockerCertPath, "ca.pem"),
  249. CertFile: filepath.Join(dockerCertPath, "cert.pem"),
  250. KeyFile: filepath.Join(dockerCertPath, "key.pem"),
  251. }
  252. tlsConfig, err := tlsconfig.Client(*option)
  253. if err != nil {
  254. return nil, err
  255. }
  256. return tlsConfig, nil
  257. }
  258. // DaemonHost return the daemon host string for this test execution
  259. func DaemonHost() string {
  260. daemonURLStr := "unix://" + opts.DefaultUnixSocket
  261. if daemonHostVar := os.Getenv("DOCKER_HOST"); daemonHostVar != "" {
  262. daemonURLStr = daemonHostVar
  263. }
  264. return daemonURLStr
  265. }