request.go 8.2 KB

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