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