blob: f88682381dda13bc7d7899a0b0db1b2a3dd8d904 [file] [log] [blame]
Ash Wilson89466cc2014-08-29 11:27:39 -04001package gophercloud
2
Ash Wilson89eec332015-02-12 13:40:32 -05003import (
4 "bytes"
5 "encoding/json"
Ash Wilson89eec332015-02-12 13:40:32 -05006 "io"
7 "io/ioutil"
8 "net/http"
Jon Perritt2b5e3e12015-02-13 12:15:08 -07009 "strings"
Ash Wilson89eec332015-02-12 13:40:32 -050010)
11
Jon Perritt2b5e3e12015-02-13 12:15:08 -070012// DefaultUserAgent is the default User-Agent string set in the request header.
jrperrittb1013232016-02-10 19:01:53 -060013const DefaultUserAgent = "gophercloud/2.0.0"
Jon Perritt2b5e3e12015-02-13 12:15:08 -070014
15// UserAgent represents a User-Agent header.
16type UserAgent struct {
17 // prepend is the slice of User-Agent strings to prepend to DefaultUserAgent.
18 // All the strings to prepend are accumulated and prepended in the Join method.
19 prepend []string
20}
21
22// Prepend prepends a user-defined string to the default User-Agent string. Users
23// may pass in one or more strings to prepend.
24func (ua *UserAgent) Prepend(s ...string) {
25 ua.prepend = append(s, ua.prepend...)
26}
27
28// Join concatenates all the user-defined User-Agend strings with the default
29// Gophercloud User-Agent string.
30func (ua *UserAgent) Join() string {
31 uaSlice := append(ua.prepend, DefaultUserAgent)
32 return strings.Join(uaSlice, " ")
33}
34
Jamie Hannafordb280dea2014-10-24 15:14:06 +020035// ProviderClient stores details that are required to interact with any
36// services within a specific provider's API.
Ash Wilson89466cc2014-08-29 11:27:39 -040037//
Jamie Hannafordb280dea2014-10-24 15:14:06 +020038// Generally, you acquire a ProviderClient by calling the NewClient method in
39// the appropriate provider's child package, providing whatever authentication
40// credentials are required.
Ash Wilson89466cc2014-08-29 11:27:39 -040041type ProviderClient struct {
Jamie Hannafordb280dea2014-10-24 15:14:06 +020042 // IdentityBase is the base URL used for a particular provider's identity
43 // service - it will be used when issuing authenticatation requests. It
44 // should point to the root resource of the identity service, not a specific
45 // identity version.
Ash Wilson09694b92014-09-09 14:08:27 -040046 IdentityBase string
47
Jamie Hannafordb280dea2014-10-24 15:14:06 +020048 // IdentityEndpoint is the identity endpoint. This may be a specific version
49 // of the identity service. If this is the case, this endpoint is used rather
50 // than querying versions first.
Ash Wilsonc6372fe2014-09-03 11:24:52 -040051 IdentityEndpoint string
52
Jamie Hannafordb280dea2014-10-24 15:14:06 +020053 // TokenID is the ID of the most recently issued valid token.
Ash Wilson89466cc2014-08-29 11:27:39 -040054 TokenID string
Ash Wilsonb8401a72014-09-08 17:07:49 -040055
Jamie Hannafordb280dea2014-10-24 15:14:06 +020056 // EndpointLocator describes how this provider discovers the endpoints for
57 // its constituent services.
Ash Wilsonb8401a72014-09-08 17:07:49 -040058 EndpointLocator EndpointLocator
Ash Wilson89eec332015-02-12 13:40:32 -050059
60 // HTTPClient allows users to interject arbitrary http, https, or other transit behaviors.
61 HTTPClient http.Client
Jon Perritt2b5e3e12015-02-13 12:15:08 -070062
63 // UserAgent represents the User-Agent header in the HTTP request.
64 UserAgent UserAgent
Jon Perrittf4052c62015-02-14 09:48:18 -070065
Jon Perrittf4052c62015-02-14 09:48:18 -070066 // ReauthFunc is the function used to re-authenticate the user if the request
67 // fails with a 401 HTTP response code. This a needed because there may be multiple
68 // authentication functions for different Identity service versions.
Jon Perritt6fe7c402015-02-17 12:24:53 -070069 ReauthFunc func() error
Jon Perrittf094fef2016-03-07 01:41:59 -060070
71 Debug bool
Ash Wilson89466cc2014-08-29 11:27:39 -040072}
73
Jamie Hannafordb280dea2014-10-24 15:14:06 +020074// AuthenticatedHeaders returns a map of HTTP headers that are common for all
75// authenticated service requests.
Ash Wilson89466cc2014-08-29 11:27:39 -040076func (client *ProviderClient) AuthenticatedHeaders() map[string]string {
Ash Wilson89eec332015-02-12 13:40:32 -050077 if client.TokenID == "" {
78 return map[string]string{}
79 }
Ash Wilson89466cc2014-08-29 11:27:39 -040080 return map[string]string{"X-Auth-Token": client.TokenID}
81}
Ash Wilson89eec332015-02-12 13:40:32 -050082
83// RequestOpts customizes the behavior of the provider.Request() method.
84type RequestOpts struct {
85 // JSONBody, if provided, will be encoded as JSON and used as the body of the HTTP request. The
86 // content type of the request will default to "application/json" unless overridden by MoreHeaders.
87 // It's an error to specify both a JSONBody and a RawBody.
88 JSONBody interface{}
jrperrittb1013232016-02-10 19:01:53 -060089 // RawBody contains an io.Reader that will be consumed by the request directly. No content-type
Ash Wilson89eec332015-02-12 13:40:32 -050090 // will be set unless one is provided explicitly by MoreHeaders.
jrperrittb1013232016-02-10 19:01:53 -060091 RawBody io.Reader
Ash Wilson89eec332015-02-12 13:40:32 -050092 // JSONResponse, if provided, will be populated with the contents of the response body parsed as
93 // JSON.
Ash Wilson2491b4c2015-02-12 16:13:39 -050094 JSONResponse interface{}
Ash Wilson89eec332015-02-12 13:40:32 -050095 // OkCodes contains a list of numeric HTTP status codes that should be interpreted as success. If
96 // the response has a different code, an error will be returned.
97 OkCodes []int
Ash Wilson89eec332015-02-12 13:40:32 -050098 // MoreHeaders specifies additional HTTP headers to be provide on the request. If a header is
99 // provided with a blank value (""), that header will be *omitted* instead: use this to suppress
100 // the default Accept header or an inferred Content-Type, for example.
101 MoreHeaders map[string]string
Jon Perritt4024a022016-02-29 19:58:56 -0600102 // ErrorContext specifies the resource error type to return if an error is encountered.
Jon Perritte0f9e4f2016-02-21 21:41:03 -0600103 // This lets resources override default error messages based on the response status code.
104 ErrorContext error
Ash Wilson89eec332015-02-12 13:40:32 -0500105}
106
Ash Wilson89eec332015-02-12 13:40:32 -0500107var applicationJSON = "application/json"
108
109// Request performs an HTTP request using the ProviderClient's current HTTPClient. An authentication
110// header will automatically be provided.
Jon Perritt90d31ce2016-03-10 02:48:46 -0600111func (client *ProviderClient) Request(method, url string, options *RequestOpts) (*http.Response, error) {
jrperrittb1013232016-02-10 19:01:53 -0600112 var body io.Reader
Ash Wilson89eec332015-02-12 13:40:32 -0500113 var contentType *string
114
115 // Derive the content body by either encoding an arbitrary object as JSON, or by taking a provided
Brendan ODonnella69b3472015-04-27 13:59:41 -0500116 // io.ReadSeeker as-is. Default the content-type to application/json.
Ash Wilson89eec332015-02-12 13:40:32 -0500117 if options.JSONBody != nil {
118 if options.RawBody != nil {
119 panic("Please provide only one of JSONBody or RawBody to gophercloud.Request().")
120 }
121
122 rendered, err := json.Marshal(options.JSONBody)
123 if err != nil {
124 return nil, err
125 }
126
127 body = bytes.NewReader(rendered)
128 contentType = &applicationJSON
129 }
130
131 if options.RawBody != nil {
132 body = options.RawBody
133 }
134
135 // Construct the http.Request.
Ash Wilson89eec332015-02-12 13:40:32 -0500136 req, err := http.NewRequest(method, url, body)
137 if err != nil {
138 return nil, err
139 }
140
141 // Populate the request headers. Apply options.MoreHeaders last, to give the caller the chance to
142 // modify or omit any header.
Ash Wilson89eec332015-02-12 13:40:32 -0500143 if contentType != nil {
Ash Wilson54d62fa2015-02-12 15:09:46 -0500144 req.Header.Set("Content-Type", *contentType)
Ash Wilson89eec332015-02-12 13:40:32 -0500145 }
Ash Wilson54d62fa2015-02-12 15:09:46 -0500146 req.Header.Set("Accept", applicationJSON)
Ash Wilson89eec332015-02-12 13:40:32 -0500147
148 for k, v := range client.AuthenticatedHeaders() {
149 req.Header.Add(k, v)
150 }
151
Jon Perrittf0a1fee2015-02-13 12:53:23 -0700152 // Set the User-Agent header
153 req.Header.Set("User-Agent", client.UserAgent.Join())
154
Ash Wilson89eec332015-02-12 13:40:32 -0500155 if options.MoreHeaders != nil {
156 for k, v := range options.MoreHeaders {
157 if v != "" {
Ash Wilson54d62fa2015-02-12 15:09:46 -0500158 req.Header.Set(k, v)
Ash Wilson89eec332015-02-12 13:40:32 -0500159 } else {
160 req.Header.Del(k)
161 }
162 }
163 }
164
Kostiantyn Yarovyi3fa30bb2015-11-25 17:21:03 +0200165 // Set connection parameter to close the connection immediately when we've got the response
166 req.Close = true
Jon Perrittaaafa612016-02-21 18:23:38 -0600167
Jon Perritt2b5e3e12015-02-13 12:15:08 -0700168 // Issue the request.
Ash Wilson89eec332015-02-12 13:40:32 -0500169 resp, err := client.HTTPClient.Do(req)
170 if err != nil {
171 return nil, err
172 }
173
Jamie Hannaford647cea52015-03-23 17:15:07 +0100174 // Allow default OkCodes if none explicitly set
175 if options.OkCodes == nil {
176 options.OkCodes = defaultOkCodes(method)
177 }
178
179 // Validate the HTTP response status.
180 var ok bool
181 for _, code := range options.OkCodes {
182 if resp.StatusCode == code {
183 ok = true
184 break
Ash Wilson89eec332015-02-12 13:40:32 -0500185 }
Jamie Hannaford647cea52015-03-23 17:15:07 +0100186 }
Jon Perritt28256b32016-02-29 03:06:36 -0600187
Jamie Hannaford647cea52015-03-23 17:15:07 +0100188 if !ok {
189 body, _ := ioutil.ReadAll(resp.Body)
190 resp.Body.Close()
Jon Perrittf094fef2016-03-07 01:41:59 -0600191 //pc := make([]uintptr, 1)
Jon Perritt28256b32016-02-29 03:06:36 -0600192 //runtime.Callers(2, pc)
193 //f := runtime.FuncForPC(pc[0])
Jon Perrittf094fef2016-03-07 01:41:59 -0600194 respErr := ErrUnexpectedResponseCode{
Jamie Hannaford647cea52015-03-23 17:15:07 +0100195 URL: url,
196 Method: method,
197 Expected: options.OkCodes,
198 Actual: resp.StatusCode,
199 Body: body,
Ash Wilson89eec332015-02-12 13:40:32 -0500200 }
Jon Perritt90d31ce2016-03-10 02:48:46 -0600201 //respErr.Function = "gophercloud.ProviderClient.Request"
Jon Perritte0f9e4f2016-02-21 21:41:03 -0600202
203 errType := options.ErrorContext
204 switch resp.StatusCode {
205 case http.StatusBadRequest:
206 err = ErrDefault400{respErr}
207 if error400er, ok := errType.(Err400er); ok {
208 err = error400er.Error400(respErr)
209 }
210 case http.StatusUnauthorized:
211 if client.ReauthFunc != nil {
212 err = client.ReauthFunc()
213 if err != nil {
Jon Perritt28256b32016-02-29 03:06:36 -0600214 e := &ErrUnableToReauthenticate{}
Jon Perrittf094fef2016-03-07 01:41:59 -0600215 e.ErrOriginal = respErr
Jon Perritt28256b32016-02-29 03:06:36 -0600216 return nil, e
Jon Perritte0f9e4f2016-02-21 21:41:03 -0600217 }
218 if options.RawBody != nil {
Jon Perritt28256b32016-02-29 03:06:36 -0600219 if seeker, ok := options.RawBody.(io.Seeker); ok {
220 seeker.Seek(0, 0)
Jon Perritte0f9e4f2016-02-21 21:41:03 -0600221 }
Jon Perritte0f9e4f2016-02-21 21:41:03 -0600222 }
223 resp, err = client.Request(method, url, options)
224 if err != nil {
225 switch err.(type) {
226 case *ErrUnexpectedResponseCode:
Jon Perritt28256b32016-02-29 03:06:36 -0600227 e := &ErrErrorAfterReauthentication{}
Jon Perrittf094fef2016-03-07 01:41:59 -0600228 e.ErrOriginal = err.(*ErrUnexpectedResponseCode)
Jon Perritt28256b32016-02-29 03:06:36 -0600229 return nil, e
Jon Perritte0f9e4f2016-02-21 21:41:03 -0600230 default:
Jon Perritt28256b32016-02-29 03:06:36 -0600231 e := &ErrErrorAfterReauthentication{}
Jon Perrittf094fef2016-03-07 01:41:59 -0600232 e.ErrOriginal = err
Jon Perritt28256b32016-02-29 03:06:36 -0600233 return nil, e
Jon Perritte0f9e4f2016-02-21 21:41:03 -0600234 }
235 }
236 return resp, nil
237 }
238 err = ErrDefault401{respErr}
239 if error401er, ok := errType.(Err401er); ok {
240 err = error401er.Error401(respErr)
241 }
242 case http.StatusNotFound:
243 err = ErrDefault404{respErr}
244 if error404er, ok := errType.(Err404er); ok {
245 err = error404er.Error404(respErr)
246 }
247 case http.StatusMethodNotAllowed:
248 err = ErrDefault405{respErr}
249 if error405er, ok := errType.(Err405er); ok {
250 err = error405er.Error405(respErr)
251 }
252 case http.StatusRequestTimeout:
253 err = ErrDefault408{respErr}
254 if error408er, ok := errType.(Err408er); ok {
255 err = error408er.Error408(respErr)
256 }
257 case 429:
258 err = ErrDefault429{respErr}
259 if error429er, ok := errType.(Err429er); ok {
260 err = error429er.Error429(respErr)
261 }
262 case http.StatusInternalServerError:
263 err = ErrDefault500{respErr}
264 if error500er, ok := errType.(Err500er); ok {
265 err = error500er.Error500(respErr)
266 }
267 case http.StatusServiceUnavailable:
268 err = ErrDefault503{respErr}
269 if error503er, ok := errType.(Err503er); ok {
270 err = error503er.Error503(respErr)
271 }
272 }
273
274 if err == nil {
275 err = respErr
276 }
277
278 return resp, err
Ash Wilson89eec332015-02-12 13:40:32 -0500279 }
280
281 // Parse the response body as JSON, if requested to do so.
Ash Wilson89eec332015-02-12 13:40:32 -0500282 if options.JSONResponse != nil {
283 defer resp.Body.Close()
Pratik Mallyaee675fd2015-09-14 14:07:30 -0500284 if err := json.NewDecoder(resp.Body).Decode(options.JSONResponse); err != nil {
285 return nil, err
286 }
Ash Wilson89eec332015-02-12 13:40:32 -0500287 }
288
289 return resp, nil
290}
Jamie Hannaford647cea52015-03-23 17:15:07 +0100291
292func defaultOkCodes(method string) []int {
293 switch {
294 case method == "GET":
295 return []int{200}
296 case method == "POST":
297 return []int{201, 202}
298 case method == "PUT":
299 return []int{201, 202}
Krzysztof Kwapisiewicz136d2c22016-02-03 15:36:06 +0100300 case method == "PATCH":
301 return []int{200, 204}
Jamie Hannaford647cea52015-03-23 17:15:07 +0100302 case method == "DELETE":
303 return []int{202, 204}
304 }
305
306 return []int{}
307}