Merge branch 'main' from arvados-workbench2.git
[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         // Discovery document
109         DiscoveryDoc Dict
110
111         lastClosedIdlesAt time.Time
112
113         // Number of retries
114         Retries int
115
116         // X-Request-Id for outgoing requests
117         RequestID string
118 }
119
120 // MakeTLSConfig sets up TLS configuration for communicating with
121 // Arvados and Keep services.
122 func MakeTLSConfig(insecure bool) *tls.Config {
123         return &tls.Config{InsecureSkipVerify: insecure}
124 }
125
126 // New returns an ArvadosClient using the given arvados.Client
127 // configuration. This is useful for callers who load arvados.Client
128 // fields from configuration files but still need to use the
129 // arvadosclient.ArvadosClient package.
130 func New(c *arvados.Client) (*ArvadosClient, error) {
131         hc := c.Client
132         if hc == nil {
133                 hc = &http.Client{
134                         Timeout: 5 * time.Minute,
135                         Transport: &http.Transport{
136                                 TLSClientConfig: MakeTLSConfig(c.Insecure)},
137                 }
138         }
139         ac := &ArvadosClient{
140                 Scheme:            "https",
141                 ApiServer:         c.APIHost,
142                 ApiToken:          c.AuthToken,
143                 ApiInsecure:       c.Insecure,
144                 Client:            hc,
145                 Retries:           2,
146                 KeepServiceURIs:   c.KeepServiceURIs,
147                 lastClosedIdlesAt: time.Now(),
148         }
149
150         return ac, nil
151 }
152
153 // MakeArvadosClient creates a new ArvadosClient using the standard
154 // environment variables ARVADOS_API_HOST, ARVADOS_API_TOKEN,
155 // ARVADOS_API_HOST_INSECURE, and ARVADOS_KEEP_SERVICES.
156 func MakeArvadosClient() (*ArvadosClient, error) {
157         return New(arvados.NewClientFromEnv())
158 }
159
160 // CallRaw is the same as Call() but returns a Reader that reads the
161 // response body, instead of taking an output object.
162 func (c *ArvadosClient) CallRaw(method string, resourceType string, uuid string, action string, parameters Dict) (reader io.ReadCloser, err error) {
163         scheme := c.Scheme
164         if scheme == "" {
165                 scheme = "https"
166         }
167         if c.ApiServer == "" {
168                 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?")
169         }
170         u := url.URL{
171                 Scheme: scheme,
172                 Host:   c.ApiServer}
173
174         if resourceType != ApiDiscoveryResource {
175                 u.Path = "/arvados/v1"
176         }
177
178         if resourceType != "" {
179                 u.Path = u.Path + "/" + resourceType
180         }
181         if uuid != "" {
182                 u.Path = u.Path + "/" + uuid
183         }
184         if action != "" {
185                 u.Path = u.Path + "/" + action
186         }
187
188         if parameters == nil {
189                 parameters = make(Dict)
190         }
191
192         vals := make(url.Values)
193         for k, v := range parameters {
194                 if s, ok := v.(string); ok {
195                         vals.Set(k, s)
196                 } else if m, err := json.Marshal(v); err == nil {
197                         vals.Set(k, string(m))
198                 }
199         }
200         var req *http.Request
201         if method == "GET" || method == "HEAD" {
202                 u.RawQuery = vals.Encode()
203                 if req, err = http.NewRequest(method, u.String(), nil); err != nil {
204                         return nil, err
205                 }
206         } else {
207                 if req, err = http.NewRequest(method, u.String(), bytes.NewBufferString(vals.Encode())); err != nil {
208                         return nil, err
209                 }
210                 req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
211         }
212         if c.RequestID != "" {
213                 req.Header.Add("X-Request-Id", c.RequestID)
214         }
215         client := arvados.Client{
216                 Client:    c.Client,
217                 APIHost:   c.ApiServer,
218                 AuthToken: c.ApiToken,
219                 Insecure:  c.ApiInsecure,
220                 Timeout:   30 * RetryDelay * time.Duration(c.Retries),
221         }
222         resp, err := client.Do(req)
223         if err != nil {
224                 return nil, err
225         }
226         if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusNoContent {
227                 defer resp.Body.Close()
228                 return nil, newAPIServerError(c.ApiServer, resp)
229         }
230         return resp.Body, nil
231 }
232
233 func newAPIServerError(ServerAddress string, resp *http.Response) APIServerError {
234
235         ase := APIServerError{
236                 ServerAddress:     ServerAddress,
237                 HttpStatusCode:    resp.StatusCode,
238                 HttpStatusMessage: resp.Status}
239
240         // If the response body has {"errors":["reason1","reason2"]}
241         // then return those reasons.
242         var errInfo = Dict{}
243         if err := json.NewDecoder(resp.Body).Decode(&errInfo); err == nil {
244                 if errorList, ok := errInfo["errors"]; ok {
245                         if errArray, ok := errorList.([]interface{}); ok {
246                                 for _, errItem := range errArray {
247                                         // We expect an array of strings here.
248                                         // Non-strings will be passed along
249                                         // JSON-encoded.
250                                         if s, ok := errItem.(string); ok {
251                                                 ase.ErrorDetails = append(ase.ErrorDetails, s)
252                                         } else if j, err := json.Marshal(errItem); err == nil {
253                                                 ase.ErrorDetails = append(ase.ErrorDetails, string(j))
254                                         }
255                                 }
256                         }
257                 }
258         }
259         return ase
260 }
261
262 // Call an API endpoint and parse the JSON response into an object.
263 //
264 //      method - HTTP method: GET, HEAD, PUT, POST, PATCH or DELETE.
265 //      resourceType - the type of arvados resource to act on (e.g., "collections", "pipeline_instances").
266 //      uuid - the uuid of the specific item to access. May be empty.
267 //      action - API method name (e.g., "lock"). This is often empty if implied by method and uuid.
268 //      parameters - method parameters.
269 //      output - a map or annotated struct which is a legal target for encoding/json/Decoder.
270 //
271 // Returns a non-nil error if an error occurs making the API call, the
272 // API responds with a non-successful HTTP status, or an error occurs
273 // parsing the response body.
274 func (c *ArvadosClient) Call(method, resourceType, uuid, action string, parameters Dict, output interface{}) error {
275         reader, err := c.CallRaw(method, resourceType, uuid, action, parameters)
276         if reader != nil {
277                 defer reader.Close()
278         }
279         if err != nil {
280                 return err
281         }
282
283         if output != nil {
284                 dec := json.NewDecoder(reader)
285                 if err = dec.Decode(output); err != nil {
286                         return err
287                 }
288         }
289         return nil
290 }
291
292 // Create a new resource. See Call for argument descriptions.
293 func (c *ArvadosClient) Create(resourceType string, parameters Dict, output interface{}) error {
294         return c.Call("POST", resourceType, "", "", parameters, output)
295 }
296
297 // Delete a resource. See Call for argument descriptions.
298 func (c *ArvadosClient) Delete(resource string, uuid string, parameters Dict, output interface{}) (err error) {
299         return c.Call("DELETE", resource, uuid, "", parameters, output)
300 }
301
302 // Update attributes of a resource. See Call for argument descriptions.
303 func (c *ArvadosClient) Update(resourceType string, uuid string, parameters Dict, output interface{}) (err error) {
304         return c.Call("PUT", resourceType, uuid, "", parameters, output)
305 }
306
307 // Get a resource. See Call for argument descriptions.
308 func (c *ArvadosClient) Get(resourceType string, uuid string, parameters Dict, output interface{}) (err error) {
309         if !UUIDMatch(uuid) && !(resourceType == "collections" && PDHMatch(uuid)) {
310                 // No object has uuid == "": there is no need to make
311                 // an API call. Furthermore, the HTTP request for such
312                 // an API call would be "GET /arvados/v1/type/", which
313                 // is liable to be misinterpreted as the List API.
314                 return ErrInvalidArgument
315         }
316         return c.Call("GET", resourceType, uuid, "", parameters, output)
317 }
318
319 // List resources of a given type. See Call for argument descriptions.
320 func (c *ArvadosClient) List(resource string, parameters Dict, output interface{}) (err error) {
321         return c.Call("GET", resource, "", "", parameters, output)
322 }
323
324 const ApiDiscoveryResource = "discovery/v1/apis/arvados/v1/rest"
325
326 // Discovery returns the value of the given parameter in the discovery
327 // document. Returns a non-nil error if the discovery document cannot
328 // be retrieved/decoded. Returns ErrInvalidArgument if the requested
329 // parameter is not found in the discovery document.
330 func (c *ArvadosClient) Discovery(parameter string) (value interface{}, err error) {
331         if len(c.DiscoveryDoc) == 0 {
332                 c.DiscoveryDoc = make(Dict)
333                 err = c.Call("GET", ApiDiscoveryResource, "", "", nil, &c.DiscoveryDoc)
334                 if err != nil {
335                         return nil, err
336                 }
337         }
338
339         var found bool
340         value, found = c.DiscoveryDoc[parameter]
341         if found {
342                 return value, nil
343         }
344         return value, ErrInvalidArgument
345 }
346
347 // ClusterConfig returns the value of the given key in the current cluster's
348 // exported config. If key is an empty string, it'll return the entire config.
349 func (c *ArvadosClient) ClusterConfig(key string) (config interface{}, err error) {
350         var clusterConfig interface{}
351         err = c.Call("GET", "config", "", "", nil, &clusterConfig)
352         if err != nil {
353                 return nil, err
354         }
355         if key == "" {
356                 return clusterConfig, nil
357         }
358         configData, ok := clusterConfig.(map[string]interface{})[key]
359         if !ok {
360                 return nil, ErrInvalidArgument
361         }
362         return configData, nil
363 }
364
365 func (c *ArvadosClient) httpClient() *http.Client {
366         if c.Client != nil {
367                 return c.Client
368         }
369         cl := &defaultSecureHTTPClient
370         if c.ApiInsecure {
371                 cl = &defaultInsecureHTTPClient
372         }
373         if *cl == nil {
374                 defaultHTTPClientMtx.Lock()
375                 defer defaultHTTPClientMtx.Unlock()
376                 *cl = &http.Client{Transport: &http.Transport{
377                         TLSClientConfig: MakeTLSConfig(c.ApiInsecure)}}
378         }
379         return *cl
380 }