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