16306: Merge branch 'master'
[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("error reading %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         u := url.URL{
210                 Scheme: scheme,
211                 Host:   c.ApiServer}
212
213         if resourceType != ApiDiscoveryResource {
214                 u.Path = "/arvados/v1"
215         }
216
217         if resourceType != "" {
218                 u.Path = u.Path + "/" + resourceType
219         }
220         if uuid != "" {
221                 u.Path = u.Path + "/" + uuid
222         }
223         if action != "" {
224                 u.Path = u.Path + "/" + action
225         }
226
227         if parameters == nil {
228                 parameters = make(Dict)
229         }
230
231         vals := make(url.Values)
232         for k, v := range parameters {
233                 if s, ok := v.(string); ok {
234                         vals.Set(k, s)
235                 } else if m, err := json.Marshal(v); err == nil {
236                         vals.Set(k, string(m))
237                 }
238         }
239
240         retryable := false
241         switch method {
242         case "GET", "HEAD", "PUT", "OPTIONS", "DELETE":
243                 retryable = true
244         }
245
246         // Non-retryable methods such as POST are not safe to retry automatically,
247         // so we minimize such failures by always using a new or recently active socket
248         if !retryable {
249                 if time.Since(c.lastClosedIdlesAt) > MaxIdleConnectionDuration {
250                         c.lastClosedIdlesAt = time.Now()
251                         c.Client.Transport.(*http.Transport).CloseIdleConnections()
252                 }
253         }
254
255         // Make the request
256         var req *http.Request
257         var resp *http.Response
258
259         for attempt := 0; attempt <= c.Retries; attempt++ {
260                 if method == "GET" || method == "HEAD" {
261                         u.RawQuery = vals.Encode()
262                         if req, err = http.NewRequest(method, u.String(), nil); err != nil {
263                                 return nil, err
264                         }
265                 } else {
266                         if req, err = http.NewRequest(method, u.String(), bytes.NewBufferString(vals.Encode())); err != nil {
267                                 return nil, err
268                         }
269                         req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
270                 }
271
272                 // Add api token header
273                 req.Header.Add("Authorization", fmt.Sprintf("OAuth2 %s", c.ApiToken))
274                 if c.RequestID != "" {
275                         req.Header.Add("X-Request-Id", c.RequestID)
276                 }
277                 if c.External {
278                         req.Header.Add("X-External-Client", "1")
279                 }
280
281                 resp, err = c.Client.Do(req)
282                 if err != nil {
283                         if retryable {
284                                 time.Sleep(RetryDelay)
285                                 continue
286                         } else {
287                                 return nil, err
288                         }
289                 }
290
291                 if resp.StatusCode == http.StatusOK {
292                         return resp.Body, nil
293                 }
294
295                 defer resp.Body.Close()
296
297                 switch resp.StatusCode {
298                 case 408, 409, 422, 423, 500, 502, 503, 504:
299                         time.Sleep(RetryDelay)
300                         continue
301                 default:
302                         return nil, newAPIServerError(c.ApiServer, resp)
303                 }
304         }
305
306         if resp != nil {
307                 return nil, newAPIServerError(c.ApiServer, resp)
308         }
309         return nil, err
310 }
311
312 func newAPIServerError(ServerAddress string, resp *http.Response) APIServerError {
313
314         ase := APIServerError{
315                 ServerAddress:     ServerAddress,
316                 HttpStatusCode:    resp.StatusCode,
317                 HttpStatusMessage: resp.Status}
318
319         // If the response body has {"errors":["reason1","reason2"]}
320         // then return those reasons.
321         var errInfo = Dict{}
322         if err := json.NewDecoder(resp.Body).Decode(&errInfo); err == nil {
323                 if errorList, ok := errInfo["errors"]; ok {
324                         if errArray, ok := errorList.([]interface{}); ok {
325                                 for _, errItem := range errArray {
326                                         // We expect an array of strings here.
327                                         // Non-strings will be passed along
328                                         // JSON-encoded.
329                                         if s, ok := errItem.(string); ok {
330                                                 ase.ErrorDetails = append(ase.ErrorDetails, s)
331                                         } else if j, err := json.Marshal(errItem); err == nil {
332                                                 ase.ErrorDetails = append(ase.ErrorDetails, string(j))
333                                         }
334                                 }
335                         }
336                 }
337         }
338         return ase
339 }
340
341 // Call an API endpoint and parse the JSON response into an object.
342 //
343 //   method - HTTP method: GET, HEAD, PUT, POST, PATCH or DELETE.
344 //   resourceType - the type of arvados resource to act on (e.g., "collections", "pipeline_instances").
345 //   uuid - the uuid of the specific item to access. May be empty.
346 //   action - API method name (e.g., "lock"). This is often empty if implied by method and uuid.
347 //   parameters - method parameters.
348 //   output - a map or annotated struct which is a legal target for encoding/json/Decoder.
349 //
350 // Returns a non-nil error if an error occurs making the API call, the
351 // API responds with a non-successful HTTP status, or an error occurs
352 // parsing the response body.
353 func (c *ArvadosClient) Call(method, resourceType, uuid, action string, parameters Dict, output interface{}) error {
354         reader, err := c.CallRaw(method, resourceType, uuid, action, parameters)
355         if reader != nil {
356                 defer reader.Close()
357         }
358         if err != nil {
359                 return err
360         }
361
362         if output != nil {
363                 dec := json.NewDecoder(reader)
364                 if err = dec.Decode(output); err != nil {
365                         return err
366                 }
367         }
368         return nil
369 }
370
371 // Create a new resource. See Call for argument descriptions.
372 func (c *ArvadosClient) Create(resourceType string, parameters Dict, output interface{}) error {
373         return c.Call("POST", resourceType, "", "", parameters, output)
374 }
375
376 // Delete a resource. See Call for argument descriptions.
377 func (c *ArvadosClient) Delete(resource string, uuid string, parameters Dict, output interface{}) (err error) {
378         return c.Call("DELETE", resource, uuid, "", parameters, output)
379 }
380
381 // Update attributes of a resource. See Call for argument descriptions.
382 func (c *ArvadosClient) Update(resourceType string, uuid string, parameters Dict, output interface{}) (err error) {
383         return c.Call("PUT", resourceType, uuid, "", parameters, output)
384 }
385
386 // Get a resource. See Call for argument descriptions.
387 func (c *ArvadosClient) Get(resourceType string, uuid string, parameters Dict, output interface{}) (err error) {
388         if !UUIDMatch(uuid) && !(resourceType == "collections" && PDHMatch(uuid)) {
389                 // No object has uuid == "": there is no need to make
390                 // an API call. Furthermore, the HTTP request for such
391                 // an API call would be "GET /arvados/v1/type/", which
392                 // is liable to be misinterpreted as the List API.
393                 return ErrInvalidArgument
394         }
395         return c.Call("GET", resourceType, uuid, "", parameters, output)
396 }
397
398 // List resources of a given type. See Call for argument descriptions.
399 func (c *ArvadosClient) List(resource string, parameters Dict, output interface{}) (err error) {
400         return c.Call("GET", resource, "", "", parameters, output)
401 }
402
403 const ApiDiscoveryResource = "discovery/v1/apis/arvados/v1/rest"
404
405 // Discovery returns the value of the given parameter in the discovery
406 // document. Returns a non-nil error if the discovery document cannot
407 // be retrieved/decoded. Returns ErrInvalidArgument if the requested
408 // parameter is not found in the discovery document.
409 func (c *ArvadosClient) Discovery(parameter string) (value interface{}, err error) {
410         if len(c.DiscoveryDoc) == 0 {
411                 c.DiscoveryDoc = make(Dict)
412                 err = c.Call("GET", ApiDiscoveryResource, "", "", nil, &c.DiscoveryDoc)
413                 if err != nil {
414                         return nil, err
415                 }
416         }
417
418         var found bool
419         value, found = c.DiscoveryDoc[parameter]
420         if found {
421                 return value, nil
422         }
423         return value, ErrInvalidArgument
424 }
425
426 func (c *ArvadosClient) httpClient() *http.Client {
427         if c.Client != nil {
428                 return c.Client
429         }
430         cl := &defaultSecureHTTPClient
431         if c.ApiInsecure {
432                 cl = &defaultInsecureHTTPClient
433         }
434         if *cl == nil {
435                 defaultHTTPClientMtx.Lock()
436                 defer defaultHTTPClientMtx.Unlock()
437                 *cl = &http.Client{Transport: &http.Transport{
438                         TLSClientConfig: MakeTLSConfig(c.ApiInsecure)}}
439         }
440         return *cl
441 }