request.go 10.0 KB

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