1
// Copyright 2012-2016 Canonical Ltd.
2
// Licensed under the LGPLv3, see LICENCE file for details.
18
"github.com/juju/errors"
22
// Number of retries performed when the server returns a 503
23
// response with a 'Retry-after' header. A request will be issued
24
// at most NumberOfRetries + 1 times.
27
RetryAfterHeaderName = "Retry-After"
30
// Client represents a way to communicating with a MAAS API instance.
31
// It is stateless, so it can have concurrent requests in progress.
37
// ServerError is an http error (or at least, a non-2xx result) received from
38
// the server. It contains the numerical HTTP status code as well as an error
39
// string and the response's headers.
40
type ServerError struct {
47
// GetServerError returns the ServerError from the cause of the error if it is a
48
// ServerError, and also returns the bool to indicate if it was a ServerError or
50
func GetServerError(err error) (ServerError, bool) {
51
svrErr, ok := errors.Cause(err).(ServerError)
55
// readAndClose reads and closes the given ReadCloser.
57
// Trying to read from a nil simply returns nil, no error.
58
func readAndClose(stream io.ReadCloser) ([]byte, error) {
63
return ioutil.ReadAll(stream)
66
// dispatchRequest sends a request to the server, and interprets the response.
67
// Client-side errors will return an empty response and a non-nil error. For
68
// server-side errors however (i.e. responses with a non 2XX status code), the
69
// returned error will be ServerError and the returned body will reflect the
70
// server's response. If the server returns a 503 response with a 'Retry-after'
71
// header, the request will be transparenty retried.
72
func (client Client) dispatchRequest(request *http.Request) ([]byte, error) {
73
// First, store the request's body into a byte[] to be able to restore it
74
// after each request.
75
bodyContent, err := readAndClose(request.Body)
79
for retry := 0; retry < NumberOfRetries; retry++ {
80
// Restore body before issuing request.
81
newBody := ioutil.NopCloser(bytes.NewReader(bodyContent))
82
request.Body = newBody
83
body, err := client.dispatchSingleRequest(request)
84
// If this is a 503 response with a non-void "Retry-After" header: wait
85
// as instructed and retry the request.
87
serverError, ok := errors.Cause(err).(ServerError)
88
if ok && serverError.StatusCode == http.StatusServiceUnavailable {
89
retry_time_int, errConv := strconv.Atoi(serverError.Header.Get(RetryAfterHeaderName))
92
case <-time.After(time.Duration(retry_time_int) * time.Second):
100
// Restore body before issuing request.
101
newBody := ioutil.NopCloser(bytes.NewReader(bodyContent))
102
request.Body = newBody
103
return client.dispatchSingleRequest(request)
106
func (client Client) dispatchSingleRequest(request *http.Request) ([]byte, error) {
107
client.Signer.OAuthSign(request)
108
httpClient := http.Client{}
109
// See https://code.google.com/p/go/issues/detail?id=4677
110
// We need to force the connection to close each time so that we don't
111
// hit the above Go bug.
113
response, err := httpClient.Do(request)
117
body, err := readAndClose(response.Body)
121
if response.StatusCode < 200 || response.StatusCode > 299 {
122
err := errors.Errorf("ServerError: %v (%s)", response.Status, body)
123
return body, errors.Trace(ServerError{error: err, StatusCode: response.StatusCode, Header: response.Header, BodyMessage: string(body)})
128
// GetURL returns the URL to a given resource on the API, based on its URI.
129
// The resource URI may be absolute or relative; either way the result is a
130
// full absolute URL including the network part.
131
func (client Client) GetURL(uri *url.URL) *url.URL {
132
return client.APIURL.ResolveReference(uri)
135
// Get performs an HTTP "GET" to the API. This may be either an API method
136
// invocation (if you pass its name in "operation") or plain resource
137
// retrieval (if you leave "operation" blank).
138
func (client Client) Get(uri *url.URL, operation string, parameters url.Values) ([]byte, error) {
139
if parameters == nil {
140
parameters = make(url.Values)
142
opParameter := parameters.Get("op")
143
if opParameter != "" {
144
msg := errors.Errorf("reserved parameter 'op' passed (with value '%s')", opParameter)
148
parameters.Set("op", operation)
150
queryUrl := client.GetURL(uri)
151
queryUrl.RawQuery = parameters.Encode()
152
request, err := http.NewRequest("GET", queryUrl.String(), nil)
156
return client.dispatchRequest(request)
159
// writeMultiPartFiles writes the given files as parts of a multipart message
160
// using the given writer.
161
func writeMultiPartFiles(writer *multipart.Writer, files map[string][]byte) error {
162
for fileName, fileContent := range files {
164
fw, err := writer.CreateFormFile(fileName, fileName)
168
io.Copy(fw, bytes.NewBuffer(fileContent))
173
// writeMultiPartParams writes the given parameters as parts of a multipart
174
// message using the given writer.
175
func writeMultiPartParams(writer *multipart.Writer, parameters url.Values) error {
176
for key, values := range parameters {
177
for _, value := range values {
178
fw, err := writer.CreateFormField(key)
182
buffer := bytes.NewBufferString(value)
190
// nonIdempotentRequestFiles implements the common functionality of PUT and
191
// POST requests (but not GET or DELETE requests) when uploading files is
193
func (client Client) nonIdempotentRequestFiles(method string, uri *url.URL, parameters url.Values, files map[string][]byte) ([]byte, error) {
194
buf := new(bytes.Buffer)
195
writer := multipart.NewWriter(buf)
196
err := writeMultiPartFiles(writer, files)
200
err = writeMultiPartParams(writer, parameters)
205
url := client.GetURL(uri)
206
request, err := http.NewRequest(method, url.String(), buf)
210
request.Header.Set("Content-Type", writer.FormDataContentType())
211
return client.dispatchRequest(request)
215
// nonIdempotentRequest implements the common functionality of PUT and POST
216
// requests (but not GET or DELETE requests).
217
func (client Client) nonIdempotentRequest(method string, uri *url.URL, parameters url.Values) ([]byte, error) {
218
url := client.GetURL(uri)
219
request, err := http.NewRequest(method, url.String(), strings.NewReader(string(parameters.Encode())))
223
request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
224
return client.dispatchRequest(request)
227
// Post performs an HTTP "POST" to the API. This may be either an API method
228
// invocation (if you pass its name in "operation") or plain resource
229
// retrieval (if you leave "operation" blank).
230
func (client Client) Post(uri *url.URL, operation string, parameters url.Values, files map[string][]byte) ([]byte, error) {
231
queryParams := url.Values{"op": {operation}}
232
uri.RawQuery = queryParams.Encode()
234
return client.nonIdempotentRequestFiles("POST", uri, parameters, files)
236
return client.nonIdempotentRequest("POST", uri, parameters)
239
// Put updates an object on the API, using an HTTP "PUT" request.
240
func (client Client) Put(uri *url.URL, parameters url.Values) ([]byte, error) {
241
return client.nonIdempotentRequest("PUT", uri, parameters)
244
// Delete deletes an object on the API, using an HTTP "DELETE" request.
245
func (client Client) Delete(uri *url.URL) error {
246
url := client.GetURL(uri)
247
request, err := http.NewRequest("DELETE", url.String(), strings.NewReader(""))
251
_, err = client.dispatchRequest(request)
258
// Anonymous "signature method" implementation.
259
type anonSigner struct{}
261
func (signer anonSigner) OAuthSign(request *http.Request) error {
265
// *anonSigner implements the OAuthSigner interface.
266
var _ OAuthSigner = anonSigner{}
268
func composeAPIURL(BaseURL string, apiVersion string) (*url.URL, error) {
269
baseurl := EnsureTrailingSlash(BaseURL)
270
apiurl := fmt.Sprintf("%sapi/%s/", baseurl, apiVersion)
271
return url.Parse(apiurl)
274
// NewAnonymousClient creates a client that issues anonymous requests.
275
// BaseURL should refer to the root of the MAAS server path, e.g.
276
// http://my.maas.server.example.com/MAAS/
277
// apiVersion should contain the version of the MAAS API that you want to use.
278
func NewAnonymousClient(BaseURL string, apiVersion string) (*Client, error) {
279
parsedBaseURL, err := composeAPIURL(BaseURL, apiVersion)
283
return &Client{Signer: &anonSigner{}, APIURL: parsedBaseURL}, nil
286
// NewAuthenticatedClient parses the given MAAS API key into the individual
287
// OAuth tokens and creates an Client that will use these tokens to sign the
288
// requests it issues.
289
// BaseURL should refer to the root of the MAAS server path, e.g.
290
// http://my.maas.server.example.com/MAAS/
291
// apiVersion should contain the version of the MAAS API that you want to use.
292
func NewAuthenticatedClient(BaseURL string, apiKey string, apiVersion string) (*Client, error) {
293
elements := strings.Split(apiKey, ":")
294
if len(elements) != 3 {
295
errString := fmt.Sprintf("invalid API key %q; expected \"<consumer secret>:<token key>:<token secret>\"", apiKey)
296
return nil, errors.NewNotValid(nil, errString)
298
token := &OAuthToken{
299
ConsumerKey: elements[0],
300
// The consumer secret is the empty string in MAAS' authentication.
302
TokenKey: elements[1],
303
TokenSecret: elements[2],
305
signer, err := NewPlainTestOAuthSigner(token, "MAAS API")
309
parsedBaseURL, err := composeAPIURL(BaseURL, apiVersion)
313
return &Client{Signer: signer, APIURL: parsedBaseURL}, nil