client.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. package autorest
  2. // Copyright 2017 Microsoft Corporation
  3. //
  4. // Licensed under the Apache License, Version 2.0 (the "License");
  5. // you may not use this file except in compliance with the License.
  6. // You may obtain a copy of the License at
  7. //
  8. // http://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software
  11. // distributed under the License is distributed on an "AS IS" BASIS,
  12. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. // See the License for the specific language governing permissions and
  14. // limitations under the License.
  15. import (
  16. "bytes"
  17. "fmt"
  18. "io"
  19. "io/ioutil"
  20. "log"
  21. "net/http"
  22. "net/http/cookiejar"
  23. "strings"
  24. "time"
  25. "github.com/Azure/go-autorest/logger"
  26. "github.com/Azure/go-autorest/version"
  27. )
  28. const (
  29. // DefaultPollingDelay is a reasonable delay between polling requests.
  30. DefaultPollingDelay = 60 * time.Second
  31. // DefaultPollingDuration is a reasonable total polling duration.
  32. DefaultPollingDuration = 15 * time.Minute
  33. // DefaultRetryAttempts is number of attempts for retry status codes (5xx).
  34. DefaultRetryAttempts = 3
  35. // DefaultRetryDuration is the duration to wait between retries.
  36. DefaultRetryDuration = 30 * time.Second
  37. )
  38. var (
  39. // StatusCodesForRetry are a defined group of status code for which the client will retry
  40. StatusCodesForRetry = []int{
  41. http.StatusRequestTimeout, // 408
  42. http.StatusTooManyRequests, // 429
  43. http.StatusInternalServerError, // 500
  44. http.StatusBadGateway, // 502
  45. http.StatusServiceUnavailable, // 503
  46. http.StatusGatewayTimeout, // 504
  47. }
  48. )
  49. const (
  50. requestFormat = `HTTP Request Begin ===================================================
  51. %s
  52. ===================================================== HTTP Request End
  53. `
  54. responseFormat = `HTTP Response Begin ===================================================
  55. %s
  56. ===================================================== HTTP Response End
  57. `
  58. )
  59. // Response serves as the base for all responses from generated clients. It provides access to the
  60. // last http.Response.
  61. type Response struct {
  62. *http.Response `json:"-"`
  63. }
  64. // LoggingInspector implements request and response inspectors that log the full request and
  65. // response to a supplied log.
  66. type LoggingInspector struct {
  67. Logger *log.Logger
  68. }
  69. // WithInspection returns a PrepareDecorator that emits the http.Request to the supplied logger. The
  70. // body is restored after being emitted.
  71. //
  72. // Note: Since it reads the entire Body, this decorator should not be used where body streaming is
  73. // important. It is best used to trace JSON or similar body values.
  74. func (li LoggingInspector) WithInspection() PrepareDecorator {
  75. return func(p Preparer) Preparer {
  76. return PreparerFunc(func(r *http.Request) (*http.Request, error) {
  77. var body, b bytes.Buffer
  78. defer r.Body.Close()
  79. r.Body = ioutil.NopCloser(io.TeeReader(r.Body, &body))
  80. if err := r.Write(&b); err != nil {
  81. return nil, fmt.Errorf("Failed to write response: %v", err)
  82. }
  83. li.Logger.Printf(requestFormat, b.String())
  84. r.Body = ioutil.NopCloser(&body)
  85. return p.Prepare(r)
  86. })
  87. }
  88. }
  89. // ByInspecting returns a RespondDecorator that emits the http.Response to the supplied logger. The
  90. // body is restored after being emitted.
  91. //
  92. // Note: Since it reads the entire Body, this decorator should not be used where body streaming is
  93. // important. It is best used to trace JSON or similar body values.
  94. func (li LoggingInspector) ByInspecting() RespondDecorator {
  95. return func(r Responder) Responder {
  96. return ResponderFunc(func(resp *http.Response) error {
  97. var body, b bytes.Buffer
  98. defer resp.Body.Close()
  99. resp.Body = ioutil.NopCloser(io.TeeReader(resp.Body, &body))
  100. if err := resp.Write(&b); err != nil {
  101. return fmt.Errorf("Failed to write response: %v", err)
  102. }
  103. li.Logger.Printf(responseFormat, b.String())
  104. resp.Body = ioutil.NopCloser(&body)
  105. return r.Respond(resp)
  106. })
  107. }
  108. }
  109. // Client is the base for autorest generated clients. It provides default, "do nothing"
  110. // implementations of an Authorizer, RequestInspector, and ResponseInspector. It also returns the
  111. // standard, undecorated http.Client as a default Sender.
  112. //
  113. // Generated clients should also use Error (see NewError and NewErrorWithError) for errors and
  114. // return responses that compose with Response.
  115. //
  116. // Most customization of generated clients is best achieved by supplying a custom Authorizer, custom
  117. // RequestInspector, and / or custom ResponseInspector. Users may log requests, implement circuit
  118. // breakers (see https://msdn.microsoft.com/en-us/library/dn589784.aspx) or otherwise influence
  119. // sending the request by providing a decorated Sender.
  120. type Client struct {
  121. Authorizer Authorizer
  122. Sender Sender
  123. RequestInspector PrepareDecorator
  124. ResponseInspector RespondDecorator
  125. // PollingDelay sets the polling frequency used in absence of a Retry-After HTTP header
  126. PollingDelay time.Duration
  127. // PollingDuration sets the maximum polling time after which an error is returned.
  128. // Setting this to zero will use the provided context to control the duration.
  129. PollingDuration time.Duration
  130. // RetryAttempts sets the default number of retry attempts for client.
  131. RetryAttempts int
  132. // RetryDuration sets the delay duration for retries.
  133. RetryDuration time.Duration
  134. // UserAgent, if not empty, will be set as the HTTP User-Agent header on all requests sent
  135. // through the Do method.
  136. UserAgent string
  137. Jar http.CookieJar
  138. // Set to true to skip attempted registration of resource providers (false by default).
  139. SkipResourceProviderRegistration bool
  140. }
  141. // NewClientWithUserAgent returns an instance of a Client with the UserAgent set to the passed
  142. // string.
  143. func NewClientWithUserAgent(ua string) Client {
  144. c := Client{
  145. PollingDelay: DefaultPollingDelay,
  146. PollingDuration: DefaultPollingDuration,
  147. RetryAttempts: DefaultRetryAttempts,
  148. RetryDuration: DefaultRetryDuration,
  149. UserAgent: version.UserAgent(),
  150. }
  151. c.Sender = c.sender()
  152. c.AddToUserAgent(ua)
  153. return c
  154. }
  155. // AddToUserAgent adds an extension to the current user agent
  156. func (c *Client) AddToUserAgent(extension string) error {
  157. if extension != "" {
  158. c.UserAgent = fmt.Sprintf("%s %s", c.UserAgent, extension)
  159. return nil
  160. }
  161. return fmt.Errorf("Extension was empty, User Agent stayed as %s", c.UserAgent)
  162. }
  163. // Do implements the Sender interface by invoking the active Sender after applying authorization.
  164. // If Sender is not set, it uses a new instance of http.Client. In both cases it will, if UserAgent
  165. // is set, apply set the User-Agent header.
  166. func (c Client) Do(r *http.Request) (*http.Response, error) {
  167. if r.UserAgent() == "" {
  168. r, _ = Prepare(r,
  169. WithUserAgent(c.UserAgent))
  170. }
  171. // NOTE: c.WithInspection() must be last in the list so that it can inspect all preceding operations
  172. r, err := Prepare(r,
  173. c.WithAuthorization(),
  174. c.WithInspection())
  175. if err != nil {
  176. var resp *http.Response
  177. if detErr, ok := err.(DetailedError); ok {
  178. // if the authorization failed (e.g. invalid credentials) there will
  179. // be a response associated with the error, be sure to return it.
  180. resp = detErr.Response
  181. }
  182. return resp, NewErrorWithError(err, "autorest/Client", "Do", nil, "Preparing request failed")
  183. }
  184. logger.Instance.WriteRequest(r, logger.Filter{
  185. Header: func(k string, v []string) (bool, []string) {
  186. // remove the auth token from the log
  187. if strings.EqualFold(k, "Authorization") || strings.EqualFold(k, "Ocp-Apim-Subscription-Key") {
  188. v = []string{"**REDACTED**"}
  189. }
  190. return true, v
  191. },
  192. })
  193. resp, err := SendWithSender(c.sender(), r)
  194. logger.Instance.WriteResponse(resp, logger.Filter{})
  195. Respond(resp, c.ByInspecting())
  196. return resp, err
  197. }
  198. // sender returns the Sender to which to send requests.
  199. func (c Client) sender() Sender {
  200. if c.Sender == nil {
  201. j, _ := cookiejar.New(nil)
  202. return &http.Client{Jar: j}
  203. }
  204. return c.Sender
  205. }
  206. // WithAuthorization is a convenience method that returns the WithAuthorization PrepareDecorator
  207. // from the current Authorizer. If not Authorizer is set, it uses the NullAuthorizer.
  208. func (c Client) WithAuthorization() PrepareDecorator {
  209. return c.authorizer().WithAuthorization()
  210. }
  211. // authorizer returns the Authorizer to use.
  212. func (c Client) authorizer() Authorizer {
  213. if c.Authorizer == nil {
  214. return NullAuthorizer{}
  215. }
  216. return c.Authorizer
  217. }
  218. // WithInspection is a convenience method that passes the request to the supplied RequestInspector,
  219. // if present, or returns the WithNothing PrepareDecorator otherwise.
  220. func (c Client) WithInspection() PrepareDecorator {
  221. if c.RequestInspector == nil {
  222. return WithNothing()
  223. }
  224. return c.RequestInspector
  225. }
  226. // ByInspecting is a convenience method that passes the response to the supplied ResponseInspector,
  227. // if present, or returns the ByIgnoring RespondDecorator otherwise.
  228. func (c Client) ByInspecting() RespondDecorator {
  229. if c.ResponseInspector == nil {
  230. return ByIgnoring()
  231. }
  232. return c.ResponseInspector
  233. }