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