request.go 10 KB

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