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