Fix 2.4.2 upgrade notes formatting refs #19330
[arvados.git] / sdk / go / arvados / client.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: Apache-2.0
4
5 package arvados
6
7 import (
8         "bytes"
9         "context"
10         "crypto/tls"
11         "encoding/json"
12         "errors"
13         "fmt"
14         "io"
15         "io/fs"
16         "io/ioutil"
17         "log"
18         "net/http"
19         "net/url"
20         "os"
21         "regexp"
22         "strings"
23         "time"
24
25         "git.arvados.org/arvados.git/sdk/go/httpserver"
26 )
27
28 // A Client is an HTTP client with an API endpoint and a set of
29 // Arvados credentials.
30 //
31 // It offers methods for accessing individual Arvados APIs, and
32 // methods that implement common patterns like fetching multiple pages
33 // of results using List APIs.
34 type Client struct {
35         // HTTP client used to make requests. If nil,
36         // DefaultSecureClient or InsecureHTTPClient will be used.
37         Client *http.Client `json:"-"`
38
39         // Protocol scheme: "http", "https", or "" (https)
40         Scheme string
41
42         // Hostname (or host:port) of Arvados API server.
43         APIHost string
44
45         // User authentication token.
46         AuthToken string
47
48         // Accept unverified certificates. This works only if the
49         // Client field is nil: otherwise, it has no effect.
50         Insecure bool
51
52         // Override keep service discovery with a list of base
53         // URIs. (Currently there are no Client methods for
54         // discovering keep services so this is just a convenience for
55         // callers who use a Client to initialize an
56         // arvadosclient.ArvadosClient.)
57         KeepServiceURIs []string `json:",omitempty"`
58
59         // HTTP headers to add/override in outgoing requests.
60         SendHeader http.Header
61
62         // Timeout for requests. NewClientFromConfig and
63         // NewClientFromEnv return a Client with a default 5 minute
64         // timeout.  To disable this timeout and rely on each
65         // http.Request's context deadline instead, set Timeout to
66         // zero.
67         Timeout time.Duration
68
69         dd *DiscoveryDocument
70
71         defaultRequestID string
72
73         // APIHost and AuthToken were loaded from ARVADOS_* env vars
74         // (used to customize "no host/token" error messages)
75         loadedFromEnv bool
76 }
77
78 // InsecureHTTPClient is the default http.Client used by a Client with
79 // Insecure==true and Client==nil.
80 var InsecureHTTPClient = &http.Client{
81         Transport: &http.Transport{
82                 TLSClientConfig: &tls.Config{
83                         InsecureSkipVerify: true}}}
84
85 // DefaultSecureClient is the default http.Client used by a Client otherwise.
86 var DefaultSecureClient = &http.Client{}
87
88 // NewClientFromConfig creates a new Client that uses the endpoints in
89 // the given cluster.
90 //
91 // AuthToken is left empty for the caller to populate.
92 func NewClientFromConfig(cluster *Cluster) (*Client, error) {
93         ctrlURL := cluster.Services.Controller.ExternalURL
94         if ctrlURL.Host == "" {
95                 return nil, fmt.Errorf("no host in config Services.Controller.ExternalURL: %v", ctrlURL)
96         }
97         return &Client{
98                 Scheme:   ctrlURL.Scheme,
99                 APIHost:  ctrlURL.Host,
100                 Insecure: cluster.TLS.Insecure,
101                 Timeout:  5 * time.Minute,
102         }, nil
103 }
104
105 // NewClientFromEnv creates a new Client that uses the default HTTP
106 // client, and loads API endpoint and credentials from ARVADOS_*
107 // environment variables (if set) and
108 // $HOME/.config/arvados/settings.conf (if readable).
109 //
110 // If a config exists in both locations, the environment variable is
111 // used.
112 //
113 // If there is an error (other than ENOENT) reading settings.conf,
114 // NewClientFromEnv logs the error to log.Default(), then proceeds as
115 // if settings.conf did not exist.
116 //
117 // Space characters are trimmed when reading the settings file, so
118 // these are equivalent:
119 //
120 //   ARVADOS_API_HOST=localhost\n
121 //   ARVADOS_API_HOST=localhost\r\n
122 //   ARVADOS_API_HOST = localhost \n
123 //   \tARVADOS_API_HOST = localhost\n
124 func NewClientFromEnv() *Client {
125         vars := map[string]string{}
126         home := os.Getenv("HOME")
127         conffile := home + "/.config/arvados/settings.conf"
128         if home == "" {
129                 // no $HOME => just use env vars
130         } else if settings, err := os.ReadFile(conffile); errors.Is(err, fs.ErrNotExist) {
131                 // no config file => just use env vars
132         } else if err != nil {
133                 // config file unreadable => log message, then use env vars
134                 log.Printf("continuing without loading %s: %s", conffile, err)
135         } else {
136                 for _, line := range bytes.Split(settings, []byte{'\n'}) {
137                         kv := bytes.SplitN(line, []byte{'='}, 2)
138                         k := string(bytes.TrimSpace(kv[0]))
139                         if len(kv) != 2 || !strings.HasPrefix(k, "ARVADOS_") {
140                                 // Same behavior as python sdk:
141                                 // silently skip leading # (comments),
142                                 // blank lines, typos, and non-Arvados
143                                 // vars.
144                                 continue
145                         }
146                         vars[k] = string(bytes.TrimSpace(kv[1]))
147                 }
148         }
149         for _, env := range os.Environ() {
150                 if !strings.HasPrefix(env, "ARVADOS_") {
151                         continue
152                 }
153                 kv := strings.SplitN(env, "=", 2)
154                 if len(kv) == 2 {
155                         vars[kv[0]] = kv[1]
156                 }
157         }
158         var svcs []string
159         for _, s := range strings.Split(vars["ARVADOS_KEEP_SERVICES"], " ") {
160                 if s == "" {
161                         continue
162                 } else if u, err := url.Parse(s); err != nil {
163                         log.Printf("ARVADOS_KEEP_SERVICES: %q: %s", s, err)
164                 } else if !u.IsAbs() {
165                         log.Printf("ARVADOS_KEEP_SERVICES: %q: not an absolute URI", s)
166                 } else {
167                         svcs = append(svcs, s)
168                 }
169         }
170         var insecure bool
171         if s := strings.ToLower(vars["ARVADOS_API_HOST_INSECURE"]); s == "1" || s == "yes" || s == "true" {
172                 insecure = true
173         }
174         return &Client{
175                 Scheme:          "https",
176                 APIHost:         vars["ARVADOS_API_HOST"],
177                 AuthToken:       vars["ARVADOS_API_TOKEN"],
178                 Insecure:        insecure,
179                 KeepServiceURIs: svcs,
180                 Timeout:         5 * time.Minute,
181                 loadedFromEnv:   true,
182         }
183 }
184
185 var reqIDGen = httpserver.IDGenerator{Prefix: "req-"}
186
187 // Do adds Authorization and X-Request-Id headers and then calls
188 // (*http.Client)Do().
189 func (c *Client) Do(req *http.Request) (*http.Response, error) {
190         if auth, _ := req.Context().Value(contextKeyAuthorization{}).(string); auth != "" {
191                 req.Header.Add("Authorization", auth)
192         } else if c.AuthToken != "" {
193                 req.Header.Add("Authorization", "OAuth2 "+c.AuthToken)
194         }
195
196         if req.Header.Get("X-Request-Id") == "" {
197                 var reqid string
198                 if ctxreqid, _ := req.Context().Value(contextKeyRequestID{}).(string); ctxreqid != "" {
199                         reqid = ctxreqid
200                 } else if c.defaultRequestID != "" {
201                         reqid = c.defaultRequestID
202                 } else {
203                         reqid = reqIDGen.Next()
204                 }
205                 if req.Header == nil {
206                         req.Header = http.Header{"X-Request-Id": {reqid}}
207                 } else {
208                         req.Header.Set("X-Request-Id", reqid)
209                 }
210         }
211         var cancel context.CancelFunc
212         if c.Timeout > 0 {
213                 ctx := req.Context()
214                 ctx, cancel = context.WithDeadline(ctx, time.Now().Add(c.Timeout))
215                 req = req.WithContext(ctx)
216         }
217         resp, err := c.httpClient().Do(req)
218         if err == nil && cancel != nil {
219                 // We need to call cancel() eventually, but we can't
220                 // use "defer cancel()" because the context has to
221                 // stay alive until the caller has finished reading
222                 // the response body.
223                 resp.Body = cancelOnClose{ReadCloser: resp.Body, cancel: cancel}
224         } else if cancel != nil {
225                 cancel()
226         }
227         return resp, err
228 }
229
230 // cancelOnClose calls a provided CancelFunc when its wrapped
231 // ReadCloser's Close() method is called.
232 type cancelOnClose struct {
233         io.ReadCloser
234         cancel context.CancelFunc
235 }
236
237 func (coc cancelOnClose) Close() error {
238         err := coc.ReadCloser.Close()
239         coc.cancel()
240         return err
241 }
242
243 func isRedirectStatus(code int) bool {
244         switch code {
245         case http.StatusMovedPermanently, http.StatusFound, http.StatusSeeOther, http.StatusTemporaryRedirect, http.StatusPermanentRedirect:
246                 return true
247         default:
248                 return false
249         }
250 }
251
252 // DoAndDecode performs req and unmarshals the response (which must be
253 // JSON) into dst. Use this instead of RequestAndDecode if you need
254 // more control of the http.Request object.
255 //
256 // If the response status indicates an HTTP redirect, the Location
257 // header value is unmarshalled to dst as a RedirectLocation
258 // key/field.
259 func (c *Client) DoAndDecode(dst interface{}, req *http.Request) error {
260         resp, err := c.Do(req)
261         if err != nil {
262                 return err
263         }
264         defer resp.Body.Close()
265         buf, err := ioutil.ReadAll(resp.Body)
266         if err != nil {
267                 return err
268         }
269         switch {
270         case resp.StatusCode == http.StatusNoContent:
271                 return nil
272         case resp.StatusCode == http.StatusOK && dst == nil:
273                 return nil
274         case resp.StatusCode == http.StatusOK:
275                 return json.Unmarshal(buf, dst)
276
277         // If the caller uses a client with a custom CheckRedirect
278         // func, Do() might return the 3xx response instead of
279         // following it.
280         case isRedirectStatus(resp.StatusCode) && dst == nil:
281                 return nil
282         case isRedirectStatus(resp.StatusCode):
283                 // Copy the redirect target URL to dst.RedirectLocation.
284                 buf, err := json.Marshal(map[string]string{"redirect_location": resp.Header.Get("Location")})
285                 if err != nil {
286                         return err
287                 }
288                 return json.Unmarshal(buf, dst)
289
290         default:
291                 return newTransactionError(req, resp, buf)
292         }
293 }
294
295 // Convert an arbitrary struct to url.Values. For example,
296 //
297 //     Foo{Bar: []int{1,2,3}, Baz: "waz"}
298 //
299 // becomes
300 //
301 //     url.Values{`bar`:`{"a":[1,2,3]}`,`Baz`:`waz`}
302 //
303 // params itself is returned if it is already an url.Values.
304 func anythingToValues(params interface{}) (url.Values, error) {
305         if v, ok := params.(url.Values); ok {
306                 return v, nil
307         }
308         // TODO: Do this more efficiently, possibly using
309         // json.Decode/Encode, so the whole thing doesn't have to get
310         // encoded, decoded, and re-encoded.
311         j, err := json.Marshal(params)
312         if err != nil {
313                 return nil, err
314         }
315         var generic map[string]interface{}
316         dec := json.NewDecoder(bytes.NewBuffer(j))
317         dec.UseNumber()
318         err = dec.Decode(&generic)
319         if err != nil {
320                 return nil, err
321         }
322         urlValues := url.Values{}
323         for k, v := range generic {
324                 if v, ok := v.(string); ok {
325                         urlValues.Set(k, v)
326                         continue
327                 }
328                 if v, ok := v.(json.Number); ok {
329                         urlValues.Set(k, v.String())
330                         continue
331                 }
332                 if v, ok := v.(bool); ok {
333                         if v {
334                                 urlValues.Set(k, "true")
335                         } else {
336                                 // "foo=false", "foo=0", and "foo="
337                                 // are all taken as true strings, so
338                                 // don't send false values at all --
339                                 // rely on the default being false.
340                         }
341                         continue
342                 }
343                 j, err := json.Marshal(v)
344                 if err != nil {
345                         return nil, err
346                 }
347                 if bytes.Equal(j, []byte("null")) {
348                         // don't add it to urlValues at all
349                         continue
350                 }
351                 urlValues.Set(k, string(j))
352         }
353         return urlValues, nil
354 }
355
356 // RequestAndDecode performs an API request and unmarshals the
357 // response (which must be JSON) into dst. Method and body arguments
358 // are the same as for http.NewRequest(). The given path is added to
359 // the server's scheme/host/port to form the request URL. The given
360 // params are passed via POST form or query string.
361 //
362 // path must not contain a query string.
363 func (c *Client) RequestAndDecode(dst interface{}, method, path string, body io.Reader, params interface{}) error {
364         return c.RequestAndDecodeContext(context.Background(), dst, method, path, body, params)
365 }
366
367 // RequestAndDecodeContext does the same as RequestAndDecode, but with a context
368 func (c *Client) RequestAndDecodeContext(ctx context.Context, dst interface{}, method, path string, body io.Reader, params interface{}) error {
369         if body, ok := body.(io.Closer); ok {
370                 // Ensure body is closed even if we error out early
371                 defer body.Close()
372         }
373         if c.APIHost == "" {
374                 if c.loadedFromEnv {
375                         return errors.New("ARVADOS_API_HOST and/or ARVADOS_API_TOKEN environment variables are not set")
376                 }
377                 return errors.New("arvados.Client cannot perform request: APIHost is not set")
378         }
379         urlString := c.apiURL(path)
380         urlValues, err := anythingToValues(params)
381         if err != nil {
382                 return err
383         }
384         if urlValues == nil {
385                 // Nothing to send
386         } else if body != nil || ((method == "GET" || method == "HEAD") && len(urlValues.Encode()) < 1000) {
387                 // Send params in query part of URL
388                 u, err := url.Parse(urlString)
389                 if err != nil {
390                         return err
391                 }
392                 u.RawQuery = urlValues.Encode()
393                 urlString = u.String()
394         } else {
395                 body = strings.NewReader(urlValues.Encode())
396         }
397         req, err := http.NewRequest(method, urlString, body)
398         if err != nil {
399                 return err
400         }
401         if (method == "GET" || method == "HEAD") && body != nil {
402                 req.Header.Set("X-Http-Method-Override", method)
403                 req.Method = "POST"
404         }
405         req = req.WithContext(ctx)
406         req.Header.Set("Content-type", "application/x-www-form-urlencoded")
407         for k, v := range c.SendHeader {
408                 req.Header[k] = v
409         }
410         return c.DoAndDecode(dst, req)
411 }
412
413 type resource interface {
414         resourceName() string
415 }
416
417 // UpdateBody returns an io.Reader suitable for use as an http.Request
418 // Body for a create or update API call.
419 func (c *Client) UpdateBody(rsc resource) io.Reader {
420         j, err := json.Marshal(rsc)
421         if err != nil {
422                 // Return a reader that returns errors.
423                 r, w := io.Pipe()
424                 w.CloseWithError(err)
425                 return r
426         }
427         v := url.Values{rsc.resourceName(): {string(j)}}
428         return bytes.NewBufferString(v.Encode())
429 }
430
431 // WithRequestID returns a new shallow copy of c that sends the given
432 // X-Request-Id value (instead of a new randomly generated one) with
433 // each subsequent request that doesn't provide its own via context or
434 // header.
435 func (c *Client) WithRequestID(reqid string) *Client {
436         cc := *c
437         cc.defaultRequestID = reqid
438         return &cc
439 }
440
441 func (c *Client) httpClient() *http.Client {
442         switch {
443         case c.Client != nil:
444                 return c.Client
445         case c.Insecure:
446                 return InsecureHTTPClient
447         default:
448                 return DefaultSecureClient
449         }
450 }
451
452 func (c *Client) apiURL(path string) string {
453         scheme := c.Scheme
454         if scheme == "" {
455                 scheme = "https"
456         }
457         return scheme + "://" + c.APIHost + "/" + path
458 }
459
460 // DiscoveryDocument is the Arvados server's description of itself.
461 type DiscoveryDocument struct {
462         BasePath                     string              `json:"basePath"`
463         DefaultCollectionReplication int                 `json:"defaultCollectionReplication"`
464         BlobSignatureTTL             int64               `json:"blobSignatureTtl"`
465         GitURL                       string              `json:"gitUrl"`
466         Schemas                      map[string]Schema   `json:"schemas"`
467         Resources                    map[string]Resource `json:"resources"`
468 }
469
470 type Resource struct {
471         Methods map[string]ResourceMethod `json:"methods"`
472 }
473
474 type ResourceMethod struct {
475         HTTPMethod string         `json:"httpMethod"`
476         Path       string         `json:"path"`
477         Response   MethodResponse `json:"response"`
478 }
479
480 type MethodResponse struct {
481         Ref string `json:"$ref"`
482 }
483
484 type Schema struct {
485         UUIDPrefix string `json:"uuidPrefix"`
486 }
487
488 // DiscoveryDocument returns a *DiscoveryDocument. The returned object
489 // should not be modified: the same object may be returned by
490 // subsequent calls.
491 func (c *Client) DiscoveryDocument() (*DiscoveryDocument, error) {
492         if c.dd != nil {
493                 return c.dd, nil
494         }
495         var dd DiscoveryDocument
496         err := c.RequestAndDecode(&dd, "GET", "discovery/v1/apis/arvados/v1/rest", nil, nil)
497         if err != nil {
498                 return nil, err
499         }
500         c.dd = &dd
501         return c.dd, nil
502 }
503
504 var pdhRegexp = regexp.MustCompile(`^[0-9a-f]{32}\+\d+$`)
505
506 func (c *Client) modelForUUID(dd *DiscoveryDocument, uuid string) (string, error) {
507         if pdhRegexp.MatchString(uuid) {
508                 return "Collection", nil
509         }
510         if len(uuid) != 27 {
511                 return "", fmt.Errorf("invalid UUID: %q", uuid)
512         }
513         infix := uuid[6:11]
514         var model string
515         for m, s := range dd.Schemas {
516                 if s.UUIDPrefix == infix {
517                         model = m
518                         break
519                 }
520         }
521         if model == "" {
522                 return "", fmt.Errorf("unrecognized type portion %q in UUID %q", infix, uuid)
523         }
524         return model, nil
525 }
526
527 func (c *Client) KindForUUID(uuid string) (string, error) {
528         dd, err := c.DiscoveryDocument()
529         if err != nil {
530                 return "", err
531         }
532         model, err := c.modelForUUID(dd, uuid)
533         if err != nil {
534                 return "", err
535         }
536         return "arvados#" + strings.ToLower(model[:1]) + model[1:], nil
537 }
538
539 func (c *Client) PathForUUID(method, uuid string) (string, error) {
540         dd, err := c.DiscoveryDocument()
541         if err != nil {
542                 return "", err
543         }
544         model, err := c.modelForUUID(dd, uuid)
545         if err != nil {
546                 return "", err
547         }
548         var resource string
549         for r, rsc := range dd.Resources {
550                 if rsc.Methods["get"].Response.Ref == model {
551                         resource = r
552                         break
553                 }
554         }
555         if resource == "" {
556                 return "", fmt.Errorf("no resource for model: %q", model)
557         }
558         m, ok := dd.Resources[resource].Methods[method]
559         if !ok {
560                 return "", fmt.Errorf("no method %q for resource %q", method, resource)
561         }
562         path := dd.BasePath + strings.Replace(m.Path, "{uuid}", uuid, -1)
563         if path[0] == '/' {
564                 path = path[1:]
565         }
566         return path, nil
567 }