dial.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. // Copyright 2015 Google LLC.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // Package http supports network connections to HTTP servers.
  5. // This package is not intended for use by end developers. Use the
  6. // google.golang.org/api/option package to configure API clients.
  7. package http
  8. import (
  9. "context"
  10. "crypto/tls"
  11. "errors"
  12. "net"
  13. "net/http"
  14. "time"
  15. "go.opencensus.io/plugin/ochttp"
  16. "golang.org/x/net/http2"
  17. "golang.org/x/oauth2"
  18. "google.golang.org/api/googleapi/transport"
  19. "google.golang.org/api/internal"
  20. "google.golang.org/api/internal/cert"
  21. "google.golang.org/api/option"
  22. "google.golang.org/api/transport/http/internal/propagation"
  23. )
  24. // NewClient returns an HTTP client for use communicating with a Google cloud
  25. // service, configured with the given ClientOptions. It also returns the endpoint
  26. // for the service as specified in the options.
  27. func NewClient(ctx context.Context, opts ...option.ClientOption) (*http.Client, string, error) {
  28. settings, err := newSettings(opts)
  29. if err != nil {
  30. return nil, "", err
  31. }
  32. clientCertSource, dialTLSContext, endpoint, err := internal.GetHTTPTransportConfigAndEndpoint(settings)
  33. if err != nil {
  34. return nil, "", err
  35. }
  36. // TODO(cbro): consider injecting the User-Agent even if an explicit HTTP client is provided?
  37. if settings.HTTPClient != nil {
  38. return settings.HTTPClient, endpoint, nil
  39. }
  40. trans, err := newTransport(ctx, defaultBaseTransport(ctx, clientCertSource, dialTLSContext), settings)
  41. if err != nil {
  42. return nil, "", err
  43. }
  44. return &http.Client{Transport: trans}, endpoint, nil
  45. }
  46. // NewTransport creates an http.RoundTripper for use communicating with a Google
  47. // cloud service, configured with the given ClientOptions. Its RoundTrip method delegates to base.
  48. func NewTransport(ctx context.Context, base http.RoundTripper, opts ...option.ClientOption) (http.RoundTripper, error) {
  49. settings, err := newSettings(opts)
  50. if err != nil {
  51. return nil, err
  52. }
  53. if settings.HTTPClient != nil {
  54. return nil, errors.New("transport/http: WithHTTPClient passed to NewTransport")
  55. }
  56. return newTransport(ctx, base, settings)
  57. }
  58. func newTransport(ctx context.Context, base http.RoundTripper, settings *internal.DialSettings) (http.RoundTripper, error) {
  59. paramTransport := &parameterTransport{
  60. base: base,
  61. userAgent: settings.UserAgent,
  62. requestReason: settings.RequestReason,
  63. }
  64. var trans http.RoundTripper = paramTransport
  65. trans = addOCTransport(trans, settings)
  66. switch {
  67. case settings.NoAuth:
  68. // Do nothing.
  69. case settings.APIKey != "":
  70. paramTransport.quotaProject = internal.GetQuotaProject(nil, settings.QuotaProject)
  71. trans = &transport.APIKey{
  72. Transport: trans,
  73. Key: settings.APIKey,
  74. }
  75. default:
  76. creds, err := internal.Creds(ctx, settings)
  77. if err != nil {
  78. return nil, err
  79. }
  80. paramTransport.quotaProject = internal.GetQuotaProject(creds, settings.QuotaProject)
  81. ts := creds.TokenSource
  82. if settings.ImpersonationConfig == nil && settings.TokenSource != nil {
  83. ts = settings.TokenSource
  84. }
  85. trans = &oauth2.Transport{
  86. Base: trans,
  87. Source: ts,
  88. }
  89. }
  90. return trans, nil
  91. }
  92. func newSettings(opts []option.ClientOption) (*internal.DialSettings, error) {
  93. var o internal.DialSettings
  94. for _, opt := range opts {
  95. opt.Apply(&o)
  96. }
  97. if err := o.Validate(); err != nil {
  98. return nil, err
  99. }
  100. if o.GRPCConn != nil {
  101. return nil, errors.New("unsupported gRPC connection specified")
  102. }
  103. return &o, nil
  104. }
  105. type parameterTransport struct {
  106. userAgent string
  107. quotaProject string
  108. requestReason string
  109. base http.RoundTripper
  110. }
  111. func (t *parameterTransport) RoundTrip(req *http.Request) (*http.Response, error) {
  112. rt := t.base
  113. if rt == nil {
  114. return nil, errors.New("transport: no Transport specified")
  115. }
  116. newReq := *req
  117. newReq.Header = make(http.Header)
  118. for k, vv := range req.Header {
  119. newReq.Header[k] = vv
  120. }
  121. if t.userAgent != "" {
  122. // TODO(cbro): append to existing User-Agent header?
  123. newReq.Header.Set("User-Agent", t.userAgent)
  124. }
  125. // Attach system parameters into the header
  126. if t.quotaProject != "" {
  127. newReq.Header.Set("X-Goog-User-Project", t.quotaProject)
  128. }
  129. if t.requestReason != "" {
  130. newReq.Header.Set("X-Goog-Request-Reason", t.requestReason)
  131. }
  132. return rt.RoundTrip(&newReq)
  133. }
  134. // Set at init time by dial_appengine.go. If nil, we're not on App Engine.
  135. var appengineUrlfetchHook func(context.Context) http.RoundTripper
  136. // defaultBaseTransport returns the base HTTP transport.
  137. // On App Engine, this is urlfetch.Transport.
  138. // Otherwise, use a default transport, taking most defaults from
  139. // http.DefaultTransport.
  140. // If TLSCertificate is available, set TLSClientConfig as well.
  141. func defaultBaseTransport(ctx context.Context, clientCertSource cert.Source, dialTLSContext func(context.Context, string, string) (net.Conn, error)) http.RoundTripper {
  142. if appengineUrlfetchHook != nil {
  143. return appengineUrlfetchHook(ctx)
  144. }
  145. // Copy http.DefaultTransport except for MaxIdleConnsPerHost setting,
  146. // which is increased due to reported performance issues under load in the GCS
  147. // client. Transport.Clone is only available in Go 1.13 and up.
  148. trans := clonedTransport(http.DefaultTransport)
  149. if trans == nil {
  150. trans = fallbackBaseTransport()
  151. }
  152. trans.MaxIdleConnsPerHost = 100
  153. if clientCertSource != nil {
  154. trans.TLSClientConfig = &tls.Config{
  155. GetClientCertificate: clientCertSource,
  156. }
  157. }
  158. if dialTLSContext != nil {
  159. // If DialTLSContext is set, TLSClientConfig wil be ignored
  160. trans.DialTLSContext = dialTLSContext
  161. }
  162. configureHTTP2(trans)
  163. return trans
  164. }
  165. // configureHTTP2 configures the ReadIdleTimeout HTTP/2 option for the
  166. // transport. This allows broken idle connections to be pruned more quickly,
  167. // preventing the client from attempting to re-use connections that will no
  168. // longer work.
  169. func configureHTTP2(trans *http.Transport) {
  170. http2Trans, err := http2.ConfigureTransports(trans)
  171. if err == nil {
  172. http2Trans.ReadIdleTimeout = time.Second * 31
  173. }
  174. }
  175. // fallbackBaseTransport is used in <go1.13 as well as in the rare case if
  176. // http.DefaultTransport has been reassigned something that's not a
  177. // *http.Transport.
  178. func fallbackBaseTransport() *http.Transport {
  179. return &http.Transport{
  180. Proxy: http.ProxyFromEnvironment,
  181. DialContext: (&net.Dialer{
  182. Timeout: 30 * time.Second,
  183. KeepAlive: 30 * time.Second,
  184. DualStack: true,
  185. }).DialContext,
  186. MaxIdleConns: 100,
  187. MaxIdleConnsPerHost: 100,
  188. IdleConnTimeout: 90 * time.Second,
  189. TLSHandshakeTimeout: 10 * time.Second,
  190. ExpectContinueTimeout: 1 * time.Second,
  191. }
  192. }
  193. func addOCTransport(trans http.RoundTripper, settings *internal.DialSettings) http.RoundTripper {
  194. if settings.TelemetryDisabled {
  195. return trans
  196. }
  197. return &ochttp.Transport{
  198. Base: trans,
  199. Propagation: &propagation.HTTPFormat{},
  200. }
  201. }
  202. // clonedTransport returns the given RoundTripper as a cloned *http.Transport.
  203. // It returns nil if the RoundTripper can't be cloned or coerced to
  204. // *http.Transport.
  205. func clonedTransport(rt http.RoundTripper) *http.Transport {
  206. t, ok := rt.(*http.Transport)
  207. if !ok {
  208. return nil
  209. }
  210. return t.Clone()
  211. }