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