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