8f902d3a09574d2f52ef388978c51f391b4b9d58
[arvados.git] / sdk / go / arvadosclient / arvadosclient.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: Apache-2.0
4
5 /* Simple Arvados Go SDK for communicating with API server. */
6
7 package arvadosclient
8
9 import (
10         "bytes"
11         "crypto/tls"
12         "crypto/x509"
13         "encoding/json"
14         "errors"
15         "fmt"
16         "io"
17         "io/ioutil"
18         "log"
19         "net/http"
20         "net/url"
21         "os"
22         "regexp"
23         "strings"
24         "sync"
25         "time"
26
27         "git.arvados.org/arvados.git/sdk/go/arvados"
28 )
29
30 type StringMatcher func(string) bool
31
32 var UUIDMatch StringMatcher = regexp.MustCompile(`^[a-z0-9]{5}-[a-z0-9]{5}-[a-z0-9]{15}$`).MatchString
33 var PDHMatch StringMatcher = regexp.MustCompile(`^[0-9a-f]{32}\+\d+$`).MatchString
34
35 var MissingArvadosApiHost = errors.New("Missing required environment variable ARVADOS_API_HOST")
36 var MissingArvadosApiToken = errors.New("Missing required environment variable ARVADOS_API_TOKEN")
37 var ErrInvalidArgument = errors.New("Invalid argument")
38
39 // A common failure mode is to reuse a keepalive connection that has been
40 // terminated (in a way that we can't detect) for being idle too long.
41 // POST and DELETE are not safe to retry automatically, so we minimize
42 // such failures by always using a new or recently active socket.
43 var MaxIdleConnectionDuration = 30 * time.Second
44
45 var RetryDelay = 2 * time.Second
46
47 var (
48         defaultInsecureHTTPClient *http.Client
49         defaultSecureHTTPClient   *http.Client
50         defaultHTTPClientMtx      sync.Mutex
51 )
52
53 // APIServerError contains an error that was returned by the API server.
54 type APIServerError struct {
55         // Address of server returning error, of the form "host:port".
56         ServerAddress string
57
58         // Components of server response.
59         HttpStatusCode    int
60         HttpStatusMessage string
61
62         // Additional error details from response body.
63         ErrorDetails []string
64 }
65
66 func (e APIServerError) Error() string {
67         if len(e.ErrorDetails) > 0 {
68                 return fmt.Sprintf("arvados API server error: %s (%d: %s) returned by %s",
69                         strings.Join(e.ErrorDetails, "; "),
70                         e.HttpStatusCode,
71                         e.HttpStatusMessage,
72                         e.ServerAddress)
73         }
74         return fmt.Sprintf("arvados API server error: %d: %s returned by %s",
75                 e.HttpStatusCode,
76                 e.HttpStatusMessage,
77                 e.ServerAddress)
78 }
79
80 // StringBool tests whether s is suggestive of true. It returns true
81 // if s is a mixed/uppoer/lower-case variant of "1", "yes", or "true".
82 func StringBool(s string) bool {
83         s = strings.ToLower(s)
84         return s == "1" || s == "yes" || s == "true"
85 }
86
87 // Dict is a helper type so we don't have to write out 'map[string]interface{}' every time.
88 type Dict map[string]interface{}
89
90 // ArvadosClient contains information about how to contact the Arvados server
91 type ArvadosClient struct {
92         // https
93         Scheme string
94
95         // Arvados API server, form "host:port"
96         ApiServer string
97
98         // Arvados API token for authentication
99         ApiToken string
100
101         // Whether to require a valid SSL certificate or not
102         ApiInsecure bool
103
104         // Client object shared by client requests.  Supports HTTP KeepAlive.
105         Client *http.Client
106
107         // If true, sets the X-External-Client header to indicate
108         // the client is outside the cluster.
109         External bool
110
111         // Base URIs of Keep services, e.g., {"https://host1:8443",
112         // "https://host2:8443"}.  If this is nil, Keep clients will
113         // use the arvados.v1.keep_services.accessible API to discover
114         // available services.
115         KeepServiceURIs []string
116
117         // Discovery document
118         DiscoveryDoc Dict
119
120         lastClosedIdlesAt time.Time
121
122         // Number of retries
123         Retries int
124
125         // X-Request-Id for outgoing requests
126         RequestID string
127 }
128
129 var CertFiles = []string{
130         "/etc/arvados/ca-certificates.crt",
131         "/etc/ssl/certs/ca-certificates.crt", // Debian/Ubuntu/Gentoo etc.
132         "/etc/pki/tls/certs/ca-bundle.crt",   // Fedora/RHEL
133 }
134
135 // MakeTLSConfig sets up TLS configuration for communicating with
136 // Arvados and Keep services.
137 func MakeTLSConfig(insecure bool) *tls.Config {
138         tlsconfig := tls.Config{InsecureSkipVerify: insecure}
139
140         if !insecure {
141                 // Use the first entry in CertFiles that we can read
142                 // certificates from. If none of those work out, use
143                 // the Go defaults.
144                 certs := x509.NewCertPool()
145                 for _, file := range CertFiles {
146                         data, err := ioutil.ReadFile(file)
147                         if err != nil {
148                                 if !os.IsNotExist(err) {
149                                         log.Printf("proceeding without loading cert file %q: %s", file, err)
150                                 }
151                                 continue
152                         }
153                         if !certs.AppendCertsFromPEM(data) {
154                                 log.Printf("unable to load any certificates from %v", file)
155                                 continue
156                         }
157                         tlsconfig.RootCAs = certs
158                         break
159                 }
160         }
161
162         return &tlsconfig
163 }
164
165 // New returns an ArvadosClient using the given arvados.Client
166 // configuration. This is useful for callers who load arvados.Client
167 // fields from configuration files but still need to use the
168 // arvadosclient.ArvadosClient package.
169 func New(c *arvados.Client) (*ArvadosClient, error) {
170         ac := &ArvadosClient{
171                 Scheme:      "https",
172                 ApiServer:   c.APIHost,
173                 ApiToken:    c.AuthToken,
174                 ApiInsecure: c.Insecure,
175                 Client: &http.Client{
176                         Timeout: 5 * time.Minute,
177                         Transport: &http.Transport{
178                                 TLSClientConfig: MakeTLSConfig(c.Insecure)},
179                 },
180                 External:          false,
181                 Retries:           2,
182                 KeepServiceURIs:   c.KeepServiceURIs,
183                 lastClosedIdlesAt: time.Now(),
184         }
185
186         return ac, nil
187 }
188
189 // MakeArvadosClient creates a new ArvadosClient using the standard
190 // environment variables ARVADOS_API_HOST, ARVADOS_API_TOKEN,
191 // ARVADOS_API_HOST_INSECURE, ARVADOS_EXTERNAL_CLIENT, and
192 // ARVADOS_KEEP_SERVICES.
193 func MakeArvadosClient() (ac *ArvadosClient, err error) {
194         ac, err = New(arvados.NewClientFromEnv())
195         if err != nil {
196                 return
197         }
198         ac.External = StringBool(os.Getenv("ARVADOS_EXTERNAL_CLIENT"))
199         return
200 }
201
202 // CallRaw is the same as Call() but returns a Reader that reads the
203 // response body, instead of taking an output object.
204 func (c *ArvadosClient) CallRaw(method string, resourceType string, uuid string, action string, parameters Dict) (reader io.ReadCloser, err error) {
205         scheme := c.Scheme
206         if scheme == "" {
207                 scheme = "https"
208         }
209         if c.ApiServer == "" {
210                 return nil, fmt.Errorf("Arvados client is not configured (target API host is not set). Maybe env var ARVADOS_API_HOST should be set first?")
211         }
212         u := url.URL{
213                 Scheme: scheme,
214                 Host:   c.ApiServer}
215
216         if resourceType != ApiDiscoveryResource {
217                 u.Path = "/arvados/v1"
218         }
219
220         if resourceType != "" {
221                 u.Path = u.Path + "/" + resourceType
222         }
223         if uuid != "" {
224                 u.Path = u.Path + "/" + uuid
225         }
226         if action != "" {
227                 u.Path = u.Path + "/" + action
228         }
229
230         if parameters == nil {
231                 parameters = make(Dict)
232         }
233
234         vals := make(url.Values)
235         for k, v := range parameters {
236                 if s, ok := v.(string); ok {
237                         vals.Set(k, s)
238                 } else if m, err := json.Marshal(v); err == nil {
239                         vals.Set(k, string(m))
240                 }
241         }
242
243         retryable := false
244         switch method {
245         case "GET", "HEAD", "PUT", "OPTIONS", "DELETE":
246                 retryable = true
247         }
248
249         // Non-retryable methods such as POST are not safe to retry automatically,
250         // so we minimize such failures by always using a new or recently active socket
251         if !retryable {
252                 if time.Since(c.lastClosedIdlesAt) > MaxIdleConnectionDuration {
253                         c.lastClosedIdlesAt = time.Now()
254                         c.Client.Transport.(*http.Transport).CloseIdleConnections()
255                 }
256         }
257
258         // Make the request
259         var req *http.Request
260         var resp *http.Response
261
262         for attempt := 0; attempt <= c.Retries; attempt++ {
263                 if method == "GET" || method == "HEAD" {
264                         u.RawQuery = vals.Encode()
265                         if req, err = http.NewRequest(method, u.String(), nil); err != nil {
266                                 return nil, err
267                         }
268                 } else {
269                         if req, err = http.NewRequest(method, u.String(), bytes.NewBufferString(vals.Encode())); err != nil {
270                                 return nil, err
271                         }
272                         req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
273                 }
274
275                 // Add api token header
276                 req.Header.Add("Authorization", fmt.Sprintf("OAuth2 %s", c.ApiToken))
277                 if c.RequestID != "" {
278                         req.Header.Add("X-Request-Id", c.RequestID)
279                 }
280                 if c.External {
281                         req.Header.Add("X-External-Client", "1")
282                 }
283
284                 resp, err = c.Client.Do(req)
285                 if err != nil {
286                         if retryable {
287                                 time.Sleep(RetryDelay)
288                                 continue
289                         } else {
290                                 return nil, err
291                         }
292                 }
293
294                 if resp.StatusCode == http.StatusOK {
295                         return resp.Body, nil
296                 }
297
298                 defer resp.Body.Close()
299
300                 switch resp.StatusCode {
301                 case 408, 409, 422, 423, 500, 502, 503, 504:
302                         time.Sleep(RetryDelay)
303                         continue
304                 default:
305                         return nil, newAPIServerError(c.ApiServer, resp)
306                 }
307         }
308
309         if resp != nil {
310                 return nil, newAPIServerError(c.ApiServer, resp)
311         }
312         return nil, err
313 }
314
315 func newAPIServerError(ServerAddress string, resp *http.Response) APIServerError {
316
317         ase := APIServerError{
318                 ServerAddress:     ServerAddress,
319                 HttpStatusCode:    resp.StatusCode,
320                 HttpStatusMessage: resp.Status}
321
322         // If the response body has {"errors":["reason1","reason2"]}
323         // then return those reasons.
324         var errInfo = Dict{}
325         if err := json.NewDecoder(resp.Body).Decode(&errInfo); err == nil {
326                 if errorList, ok := errInfo["errors"]; ok {
327                         if errArray, ok := errorList.([]interface{}); ok {
328                                 for _, errItem := range errArray {
329                                         // We expect an array of strings here.
330                                         // Non-strings will be passed along
331                                         // JSON-encoded.
332                                         if s, ok := errItem.(string); ok {
333                                                 ase.ErrorDetails = append(ase.ErrorDetails, s)
334                                         } else if j, err := json.Marshal(errItem); err == nil {
335                                                 ase.ErrorDetails = append(ase.ErrorDetails, string(j))
336                                         }
337                                 }
338                         }
339                 }
340         }
341         return ase
342 }
343
344 // Call an API endpoint and parse the JSON response into an object.
345 //
346 //   method - HTTP method: GET, HEAD, PUT, POST, PATCH or DELETE.
347 //   resourceType - the type of arvados resource to act on (e.g., "collections", "pipeline_instances").
348 //   uuid - the uuid of the specific item to access. May be empty.
349 //   action - API method name (e.g., "lock"). This is often empty if implied by method and uuid.
350 //   parameters - method parameters.
351 //   output - a map or annotated struct which is a legal target for encoding/json/Decoder.
352 //
353 // Returns a non-nil error if an error occurs making the API call, the
354 // API responds with a non-successful HTTP status, or an error occurs
355 // parsing the response body.
356 func (c *ArvadosClient) Call(method, resourceType, uuid, action string, parameters Dict, output interface{}) error {
357         reader, err := c.CallRaw(method, resourceType, uuid, action, parameters)
358         if reader != nil {
359                 defer reader.Close()
360         }
361         if err != nil {
362                 return err
363         }
364
365         if output != nil {
366                 dec := json.NewDecoder(reader)
367                 if err = dec.Decode(output); err != nil {
368                         return err
369                 }
370         }
371         return nil
372 }
373
374 // Create a new resource. See Call for argument descriptions.
375 func (c *ArvadosClient) Create(resourceType string, parameters Dict, output interface{}) error {
376         return c.Call("POST", resourceType, "", "", parameters, output)
377 }
378
379 // Delete a resource. See Call for argument descriptions.
380 func (c *ArvadosClient) Delete(resource string, uuid string, parameters Dict, output interface{}) (err error) {
381         return c.Call("DELETE", resource, uuid, "", parameters, output)
382 }
383
384 // Update attributes of a resource. See Call for argument descriptions.
385 func (c *ArvadosClient) Update(resourceType string, uuid string, parameters Dict, output interface{}) (err error) {
386         return c.Call("PUT", resourceType, uuid, "", parameters, output)
387 }
388
389 // Get a resource. See Call for argument descriptions.
390 func (c *ArvadosClient) Get(resourceType string, uuid string, parameters Dict, output interface{}) (err error) {
391         if !UUIDMatch(uuid) && !(resourceType == "collections" && PDHMatch(uuid)) {
392                 // No object has uuid == "": there is no need to make
393                 // an API call. Furthermore, the HTTP request for such
394                 // an API call would be "GET /arvados/v1/type/", which
395                 // is liable to be misinterpreted as the List API.
396                 return ErrInvalidArgument
397         }
398         return c.Call("GET", resourceType, uuid, "", parameters, output)
399 }
400
401 // List resources of a given type. See Call for argument descriptions.
402 func (c *ArvadosClient) List(resource string, parameters Dict, output interface{}) (err error) {
403         return c.Call("GET", resource, "", "", parameters, output)
404 }
405
406 const ApiDiscoveryResource = "discovery/v1/apis/arvados/v1/rest"
407
408 // Discovery returns the value of the given parameter in the discovery
409 // document. Returns a non-nil error if the discovery document cannot
410 // be retrieved/decoded. Returns ErrInvalidArgument if the requested
411 // parameter is not found in the discovery document.
412 func (c *ArvadosClient) Discovery(parameter string) (value interface{}, err error) {
413         if len(c.DiscoveryDoc) == 0 {
414                 c.DiscoveryDoc = make(Dict)
415                 err = c.Call("GET", ApiDiscoveryResource, "", "", nil, &c.DiscoveryDoc)
416                 if err != nil {
417                         return nil, err
418                 }
419         }
420
421         var found bool
422         value, found = c.DiscoveryDoc[parameter]
423         if found {
424                 return value, nil
425         }
426         return value, ErrInvalidArgument
427 }
428
429 // ClusterConfig returns the value of the given key in the current cluster's
430 // exported config. If key is an empty string, it'll return the entire config.
431 func (c *ArvadosClient) ClusterConfig(key string) (config interface{}, err error) {
432         var clusterConfig interface{}
433         err = c.Call("GET", "config", "", "", nil, &clusterConfig)
434         if err != nil {
435                 return nil, err
436         }
437         if key == "" {
438                 return clusterConfig, nil
439         }
440         configData, ok := clusterConfig.(map[string]interface{})[key]
441         if !ok {
442                 return nil, ErrInvalidArgument
443         }
444         return configData, nil
445 }
446
447 func (c *ArvadosClient) httpClient() *http.Client {
448         if c.Client != nil {
449                 return c.Client
450         }
451         cl := &defaultSecureHTTPClient
452         if c.ApiInsecure {
453                 cl = &defaultInsecureHTTPClient
454         }
455         if *cl == nil {
456                 defaultHTTPClientMtx.Lock()
457                 defer defaultHTTPClientMtx.Unlock()
458                 *cl = &http.Client{Transport: &http.Transport{
459                         TLSClientConfig: MakeTLSConfig(c.ApiInsecure)}}
460         }
461         return *cl
462 }