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