Merge branch 'master' into 5538-arvadosclient-retry
[arvados.git] / sdk / go / arvadosclient / arvadosclient.go
1 /* Simple Arvados Go SDK for communicating with API server. */
2
3 package arvadosclient
4
5 import (
6         "bytes"
7         "crypto/tls"
8         "encoding/json"
9         "errors"
10         "fmt"
11         "io"
12         "net/http"
13         "net/url"
14         "os"
15         "regexp"
16         "strings"
17         "time"
18 )
19
20 type StringMatcher func(string) bool
21
22 var UUIDMatch StringMatcher = regexp.MustCompile(`^[a-z0-9]{5}-[a-z0-9]{5}-[a-z0-9]{15}$`).MatchString
23 var PDHMatch StringMatcher = regexp.MustCompile(`^[0-9a-f]{32}\+\d+$`).MatchString
24
25 var MissingArvadosApiHost = errors.New("Missing required environment variable ARVADOS_API_HOST")
26 var MissingArvadosApiToken = errors.New("Missing required environment variable ARVADOS_API_TOKEN")
27 var ErrInvalidArgument = errors.New("Invalid argument")
28
29 // A common failure mode is to reuse a keepalive connection that has been
30 // terminated (in a way that we can't detect) for being idle too long.
31 // POST and DELETE are not safe to retry automatically, so we minimize
32 // such failures by always using a new or recently active socket.
33 var MaxIdleConnectionDuration = 30 * time.Second
34
35 // Indicates an error that was returned by the API server.
36 type APIServerError struct {
37         // Address of server returning error, of the form "host:port".
38         ServerAddress string
39
40         // Components of server response.
41         HttpStatusCode    int
42         HttpStatusMessage string
43
44         // Additional error details from response body.
45         ErrorDetails []string
46 }
47
48 func (e APIServerError) Error() string {
49         if len(e.ErrorDetails) > 0 {
50                 return fmt.Sprintf("arvados API server error: %s (%d: %s) returned by %s",
51                         strings.Join(e.ErrorDetails, "; "),
52                         e.HttpStatusCode,
53                         e.HttpStatusMessage,
54                         e.ServerAddress)
55         } else {
56                 return fmt.Sprintf("arvados API server error: %d: %s returned by %s",
57                         e.HttpStatusCode,
58                         e.HttpStatusMessage,
59                         e.ServerAddress)
60         }
61 }
62
63 // Helper type so we don't have to write out 'map[string]interface{}' every time.
64 type Dict map[string]interface{}
65
66 // Information about how to contact the Arvados server
67 type ArvadosClient struct {
68         // https
69         Scheme string
70
71         // Arvados API server, form "host:port"
72         ApiServer string
73
74         // Arvados API token for authentication
75         ApiToken string
76
77         // Whether to require a valid SSL certificate or not
78         ApiInsecure bool
79
80         // Client object shared by client requests.  Supports HTTP KeepAlive.
81         Client *http.Client
82
83         // If true, sets the X-External-Client header to indicate
84         // the client is outside the cluster.
85         External bool
86
87         // Discovery document
88         DiscoveryDoc Dict
89
90         lastClosedIdlesAt time.Time
91
92         // Number of retries
93         Retries int
94 }
95
96 // Create a new ArvadosClient, initialized with standard Arvados environment
97 // variables ARVADOS_API_HOST, ARVADOS_API_TOKEN, and (optionally)
98 // ARVADOS_API_HOST_INSECURE.
99 func MakeArvadosClient() (ac ArvadosClient, err error) {
100         var matchTrue = regexp.MustCompile("^(?i:1|yes|true)$")
101         insecure := matchTrue.MatchString(os.Getenv("ARVADOS_API_HOST_INSECURE"))
102         external := matchTrue.MatchString(os.Getenv("ARVADOS_EXTERNAL_CLIENT"))
103
104         ac = ArvadosClient{
105                 Scheme:      "https",
106                 ApiServer:   os.Getenv("ARVADOS_API_HOST"),
107                 ApiToken:    os.Getenv("ARVADOS_API_TOKEN"),
108                 ApiInsecure: insecure,
109                 Client: &http.Client{Transport: &http.Transport{
110                         TLSClientConfig: &tls.Config{InsecureSkipVerify: insecure}}},
111                 External: external,
112                 Retries:  2}
113
114         if ac.ApiServer == "" {
115                 return ac, MissingArvadosApiHost
116         }
117         if ac.ApiToken == "" {
118                 return ac, MissingArvadosApiToken
119         }
120
121         ac.lastClosedIdlesAt = time.Now()
122
123         return ac, err
124 }
125
126 // CallRaw is the same as Call() but returns a Reader that reads the
127 // response body, instead of taking an output object.
128 func (c ArvadosClient) CallRaw(method string, resourceType string, uuid string, action string, parameters Dict) (reader io.ReadCloser, err error) {
129         scheme := c.Scheme
130         if scheme == "" {
131                 scheme = "https"
132         }
133         u := url.URL{
134                 Scheme: scheme,
135                 Host:   c.ApiServer}
136
137         if resourceType != API_DISCOVERY_RESOURCE {
138                 u.Path = "/arvados/v1"
139         }
140
141         if resourceType != "" {
142                 u.Path = u.Path + "/" + resourceType
143         }
144         if uuid != "" {
145                 u.Path = u.Path + "/" + uuid
146         }
147         if action != "" {
148                 u.Path = u.Path + "/" + action
149         }
150
151         if parameters == nil {
152                 parameters = make(Dict)
153         }
154
155         vals := make(url.Values)
156         for k, v := range parameters {
157                 if s, ok := v.(string); ok {
158                         vals.Set(k, s)
159                 } else if m, err := json.Marshal(v); err == nil {
160                         vals.Set(k, string(m))
161                 }
162         }
163
164         // Make the request
165         remainingTries := 1 + c.Retries
166         var req *http.Request
167         var resp *http.Response
168         var errs []string
169         var badResp bool
170
171         for remainingTries > 0 {
172                 if method == "GET" || method == "HEAD" {
173                         u.RawQuery = vals.Encode()
174                         if req, err = http.NewRequest(method, u.String(), nil); err != nil {
175                                 return nil, err
176                         }
177                 } else {
178                         if req, err = http.NewRequest(method, u.String(), bytes.NewBufferString(vals.Encode())); err != nil {
179                                 return nil, err
180                         }
181                         req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
182                 }
183
184                 // Add api token header
185                 req.Header.Add("Authorization", fmt.Sprintf("OAuth2 %s", c.ApiToken))
186                 if c.External {
187                         req.Header.Add("X-External-Client", "1")
188                 }
189
190                 // POST and DELETE are not safe to retry automatically, so we minimize
191                 // such failures by always using a new or recently active socket
192                 if method == "POST" || method == "DELETE" {
193                         if time.Since(c.lastClosedIdlesAt) > MaxIdleConnectionDuration {
194                                 c.lastClosedIdlesAt = time.Now()
195                                 c.Client.Transport.(*http.Transport).CloseIdleConnections()
196                         }
197                 }
198
199                 resp, err = c.Client.Do(req)
200                 if err != nil {
201                         if method == "GET" || method == "HEAD" || method == "PUT" {
202                                 errs = append(errs, err.Error())
203                                 badResp = false
204                                 remainingTries -= 1
205                                 continue
206                         } else {
207                                 return nil, err
208                         }
209                 }
210
211                 if resp.StatusCode == http.StatusOK {
212                         return resp.Body, nil
213                 }
214
215                 defer resp.Body.Close()
216
217                 if resp.StatusCode == 408 ||
218                         resp.StatusCode == 409 ||
219                         resp.StatusCode == 422 ||
220                         resp.StatusCode == 423 ||
221                         resp.StatusCode == 500 ||
222                         resp.StatusCode == 502 ||
223                         resp.StatusCode == 503 ||
224                         resp.StatusCode == 504 {
225                         badResp = true
226                         remainingTries -= 1
227                         continue
228                 } else {
229                         return nil, newAPIServerError(c.ApiServer, resp)
230                 }
231         }
232
233         if badResp {
234                 return nil, newAPIServerError(c.ApiServer, resp)
235         } else {
236                 return nil, fmt.Errorf("%v", errs)
237         }
238 }
239
240 func newAPIServerError(ServerAddress string, resp *http.Response) APIServerError {
241
242         ase := APIServerError{
243                 ServerAddress:     ServerAddress,
244                 HttpStatusCode:    resp.StatusCode,
245                 HttpStatusMessage: resp.Status}
246
247         // If the response body has {"errors":["reason1","reason2"]}
248         // then return those reasons.
249         var errInfo = Dict{}
250         if err := json.NewDecoder(resp.Body).Decode(&errInfo); err == nil {
251                 if errorList, ok := errInfo["errors"]; ok {
252                         if errArray, ok := errorList.([]interface{}); ok {
253                                 for _, errItem := range errArray {
254                                         // We expect an array of strings here.
255                                         // Non-strings will be passed along
256                                         // JSON-encoded.
257                                         if s, ok := errItem.(string); ok {
258                                                 ase.ErrorDetails = append(ase.ErrorDetails, s)
259                                         } else if j, err := json.Marshal(errItem); err == nil {
260                                                 ase.ErrorDetails = append(ase.ErrorDetails, string(j))
261                                         }
262                                 }
263                         }
264                 }
265         }
266         return ase
267 }
268
269 // Call an API endpoint and parse the JSON response into an object.
270 //
271 //   method - HTTP method: GET, HEAD, PUT, POST, PATCH or DELETE.
272 //   resourceType - the type of arvados resource to act on (e.g., "collections", "pipeline_instances").
273 //   uuid - the uuid of the specific item to access. May be empty.
274 //   action - API method name (e.g., "lock"). This is often empty if implied by method and uuid.
275 //   parameters - method parameters.
276 //   output - a map or annotated struct which is a legal target for encoding/json/Decoder.
277 //
278 // Returns a non-nil error if an error occurs making the API call, the
279 // API responds with a non-successful HTTP status, or an error occurs
280 // parsing the response body.
281 func (c ArvadosClient) Call(method string, resourceType string, uuid string, action string, parameters Dict, output interface{}) error {
282         reader, err := c.CallRaw(method, resourceType, uuid, action, parameters)
283         if reader != nil {
284                 defer reader.Close()
285         }
286         if err != nil {
287                 return err
288         }
289
290         if output != nil {
291                 dec := json.NewDecoder(reader)
292                 if err = dec.Decode(output); err != nil {
293                         return err
294                 }
295         }
296         return nil
297 }
298
299 // Create a new resource. See Call for argument descriptions.
300 func (c ArvadosClient) Create(resourceType string, parameters Dict, output interface{}) error {
301         return c.Call("POST", resourceType, "", "", parameters, output)
302 }
303
304 // Delete a resource. See Call for argument descriptions.
305 func (c ArvadosClient) Delete(resource string, uuid string, parameters Dict, output interface{}) (err error) {
306         return c.Call("DELETE", resource, uuid, "", parameters, output)
307 }
308
309 // Modify attributes of a resource. See Call for argument descriptions.
310 func (c ArvadosClient) Update(resourceType string, uuid string, parameters Dict, output interface{}) (err error) {
311         return c.Call("PUT", resourceType, uuid, "", parameters, output)
312 }
313
314 // Get a resource. See Call for argument descriptions.
315 func (c ArvadosClient) Get(resourceType string, uuid string, parameters Dict, output interface{}) (err error) {
316         if !UUIDMatch(uuid) && !(resourceType == "collections" && PDHMatch(uuid)) {
317                 // No object has uuid == "": there is no need to make
318                 // an API call. Furthermore, the HTTP request for such
319                 // an API call would be "GET /arvados/v1/type/", which
320                 // is liable to be misinterpreted as the List API.
321                 return ErrInvalidArgument
322         }
323         return c.Call("GET", resourceType, uuid, "", parameters, output)
324 }
325
326 // List resources of a given type. See Call for argument descriptions.
327 func (c ArvadosClient) List(resource string, parameters Dict, output interface{}) (err error) {
328         return c.Call("GET", resource, "", "", parameters, output)
329 }
330
331 const API_DISCOVERY_RESOURCE = "discovery/v1/apis/arvados/v1/rest"
332
333 // Discovery returns the value of the given parameter in the discovery
334 // document. Returns a non-nil error if the discovery document cannot
335 // be retrieved/decoded. Returns ErrInvalidArgument if the requested
336 // parameter is not found in the discovery document.
337 func (c *ArvadosClient) Discovery(parameter string) (value interface{}, err error) {
338         if len(c.DiscoveryDoc) == 0 {
339                 c.DiscoveryDoc = make(Dict)
340                 err = c.Call("GET", API_DISCOVERY_RESOURCE, "", "", nil, &c.DiscoveryDoc)
341                 if err != nil {
342                         return nil, err
343                 }
344         }
345
346         var found bool
347         value, found = c.DiscoveryDoc[parameter]
348         if found {
349                 return value, nil
350         } else {
351                 return value, ErrInvalidArgument
352         }
353 }