request.go 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  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 := NewHTTPClient(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. // NewHTTPClient creates an http client for the specific host
  127. func NewHTTPClient(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. // NewClient returns a new Docker API client
  149. func NewClient() (dclient.APIClient, error) {
  150. host := DaemonHost()
  151. httpClient, err := NewHTTPClient(host)
  152. if err != nil {
  153. return nil, err
  154. }
  155. return dclient.NewClient(host, "", httpClient, nil)
  156. }
  157. // FIXME(vdemeester) httputil.ClientConn is deprecated, use http.Client instead (closer to actual client)
  158. // Deprecated: Use New instead of NewRequestClient
  159. // Deprecated: use request.Do (or Get, Delete, Post) instead
  160. func newRequestClient(method, endpoint string, data io.Reader, ct, daemon string, modifiers ...func(*http.Request)) (*http.Request, *httputil.ClientConn, error) {
  161. c, err := SockConn(time.Duration(10*time.Second), daemon)
  162. if err != nil {
  163. return nil, nil, fmt.Errorf("could not dial docker daemon: %v", err)
  164. }
  165. client := httputil.NewClientConn(c, nil)
  166. req, err := http.NewRequest(method, endpoint, data)
  167. if err != nil {
  168. client.Close()
  169. return nil, nil, fmt.Errorf("could not create new request: %v", err)
  170. }
  171. for _, opt := range modifiers {
  172. opt(req)
  173. }
  174. if ct != "" {
  175. req.Header.Set("Content-Type", ct)
  176. }
  177. return req, client, nil
  178. }
  179. // SockRequest create a request against the specified host (with method, endpoint and other request modifier) and
  180. // returns the status code, and the content as an byte slice
  181. // Deprecated: use request.Do instead
  182. func SockRequest(method, endpoint string, data interface{}, daemon string, modifiers ...func(*http.Request)) (int, []byte, error) {
  183. jsonData := bytes.NewBuffer(nil)
  184. if err := json.NewEncoder(jsonData).Encode(data); err != nil {
  185. return -1, nil, err
  186. }
  187. res, body, err := SockRequestRaw(method, endpoint, jsonData, "application/json", daemon, modifiers...)
  188. if err != nil {
  189. return -1, nil, err
  190. }
  191. b, err := testutil.ReadBody(body)
  192. return res.StatusCode, b, err
  193. }
  194. // SockRequestRaw create a request against the specified host (with method, endpoint and other request modifier) and
  195. // returns the http response, the output as a io.ReadCloser
  196. // Deprecated: use request.Do (or Get, Delete, Post) instead
  197. func SockRequestRaw(method, endpoint string, data io.Reader, ct, daemon string, modifiers ...func(*http.Request)) (*http.Response, io.ReadCloser, error) {
  198. req, client, err := newRequestClient(method, endpoint, data, ct, daemon, modifiers...)
  199. if err != nil {
  200. return nil, nil, err
  201. }
  202. resp, err := client.Do(req)
  203. if err != nil {
  204. client.Close()
  205. return resp, nil, err
  206. }
  207. body := ioutils.NewReadCloserWrapper(resp.Body, func() error {
  208. defer resp.Body.Close()
  209. return client.Close()
  210. })
  211. return resp, body, err
  212. }
  213. // SockRequestHijack creates a connection to specified host (with method, contenttype, …) and returns a hijacked connection
  214. // and the output as a `bufio.Reader`
  215. func SockRequestHijack(method, endpoint string, data io.Reader, ct string, daemon string, modifiers ...func(*http.Request)) (net.Conn, *bufio.Reader, error) {
  216. req, client, err := newRequestClient(method, endpoint, data, ct, daemon, modifiers...)
  217. if err != nil {
  218. return nil, nil, err
  219. }
  220. client.Do(req)
  221. conn, br := client.Hijack()
  222. return conn, br, nil
  223. }
  224. // SockConn opens a connection on the specified socket
  225. func SockConn(timeout time.Duration, daemon string) (net.Conn, error) {
  226. daemonURL, err := url.Parse(daemon)
  227. if err != nil {
  228. return nil, errors.Wrapf(err, "could not parse url %q", daemon)
  229. }
  230. var c net.Conn
  231. switch daemonURL.Scheme {
  232. case "npipe":
  233. return npipeDial(daemonURL.Path, timeout)
  234. case "unix":
  235. return net.DialTimeout(daemonURL.Scheme, daemonURL.Path, timeout)
  236. case "tcp":
  237. if os.Getenv("DOCKER_TLS_VERIFY") != "" {
  238. // Setup the socket TLS configuration.
  239. tlsConfig, err := getTLSConfig()
  240. if err != nil {
  241. return nil, err
  242. }
  243. dialer := &net.Dialer{Timeout: timeout}
  244. return tls.DialWithDialer(dialer, daemonURL.Scheme, daemonURL.Host, tlsConfig)
  245. }
  246. return net.DialTimeout(daemonURL.Scheme, daemonURL.Host, timeout)
  247. default:
  248. return c, errors.Errorf("unknown scheme %v (%s)", daemonURL.Scheme, daemon)
  249. }
  250. }
  251. func getTLSConfig() (*tls.Config, error) {
  252. dockerCertPath := os.Getenv("DOCKER_CERT_PATH")
  253. if dockerCertPath == "" {
  254. return nil, errors.New("DOCKER_TLS_VERIFY specified, but no DOCKER_CERT_PATH environment variable")
  255. }
  256. option := &tlsconfig.Options{
  257. CAFile: filepath.Join(dockerCertPath, "ca.pem"),
  258. CertFile: filepath.Join(dockerCertPath, "cert.pem"),
  259. KeyFile: filepath.Join(dockerCertPath, "key.pem"),
  260. }
  261. tlsConfig, err := tlsconfig.Client(*option)
  262. if err != nil {
  263. return nil, err
  264. }
  265. return tlsConfig, nil
  266. }
  267. // DaemonHost return the daemon host string for this test execution
  268. func DaemonHost() string {
  269. daemonURLStr := "unix://" + opts.DefaultUnixSocket
  270. if daemonHostVar := os.Getenv("DOCKER_HOST"); daemonHostVar != "" {
  271. daemonURLStr = daemonHostVar
  272. }
  273. return daemonURLStr
  274. }