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