1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: Apache-2.0
33 "git.arvados.org/arvados.git/sdk/go/httpserver"
34 "github.com/hashicorp/go-retryablehttp"
35 "github.com/sirupsen/logrus"
38 // A Client is an HTTP client with an API endpoint and a set of
39 // Arvados credentials.
41 // It offers methods for accessing individual Arvados APIs, and
42 // methods that implement common patterns like fetching multiple pages
43 // of results using List APIs.
45 // HTTP client used to make requests. If nil,
46 // DefaultSecureClient or InsecureHTTPClient will be used.
47 Client *http.Client `json:"-"`
49 // Protocol scheme: "http", "https", or "" (https)
52 // Hostname (or host:port) of Arvados API server.
55 // User authentication token.
58 // Accept unverified certificates. This works only if the
59 // Client field is nil: otherwise, it has no effect.
62 // Override keep service discovery with a list of base
63 // URIs. (Currently there are no Client methods for
64 // discovering keep services so this is just a convenience for
65 // callers who use a Client to initialize an
66 // arvadosclient.ArvadosClient.)
67 KeepServiceURIs []string `json:",omitempty"`
69 // HTTP headers to add/override in outgoing requests.
70 SendHeader http.Header
72 // Timeout for requests. NewClientFromConfig and
73 // NewClientFromEnv return a Client with a default 5 minute
74 // timeout. Within this time, retryable errors are
75 // automatically retried with exponential backoff.
77 // To disable automatic retries, set Timeout to zero and use a
78 // context deadline to establish a maximum request time.
81 // Maximum disk cache size in bytes or percent of total
82 // filesystem size. If zero, use default, currently 10% of
84 DiskCacheSize ByteSizeOrPercent
86 // Where to write debug logs. May be nil.
87 Logger logrus.FieldLogger
89 // The cluster config, if the Client was initialized via
90 // NewClientFromConfig. Otherwise nil.
95 defaultRequestID string
97 // APIHost and AuthToken were loaded from ARVADOS_* env vars
98 // (used to customize "no host/token" error messages)
101 // Track/limit concurrent outgoing API calls. Note this
102 // differs from an outgoing connection limit (a feature
103 // provided by http.Transport) when concurrent calls are
104 // multiplexed on a single http2 connection.
106 // getRequestLimiter() should always be used, because this can
108 requestLimiter *requestLimiter
113 // InsecureHTTPClient is the default http.Client used by a Client with
114 // Insecure==true and Client==nil.
115 var InsecureHTTPClient = &http.Client{
116 Transport: &http.Transport{
117 TLSClientConfig: &tls.Config{
118 InsecureSkipVerify: true}}}
120 // DefaultSecureClient is the default http.Client used by a Client otherwise.
121 var DefaultSecureClient = &http.Client{}
123 // NewClientFromConfig creates a new Client that uses the endpoints in
124 // the given cluster.
126 // AuthToken is left empty for the caller to populate.
127 func NewClientFromConfig(cluster *Cluster) (*Client, error) {
128 ctrlURL := cluster.Services.Controller.ExternalURL
129 if ctrlURL.Host == "" {
130 return nil, fmt.Errorf("no host in config Services.Controller.ExternalURL: %v", ctrlURL)
133 if srvaddr := os.Getenv("ARVADOS_SERVER_ADDRESS"); srvaddr != "" {
134 // When this client is used to make a request to
135 // https://{ctrlhost}:port/ (any port), it dials the
136 // indicated port on ARVADOS_SERVER_ADDRESS instead.
138 // This is invoked by arvados-server boot to ensure
139 // that server->server traffic (e.g.,
140 // keepproxy->controller) only hits local interfaces,
141 // even if the Controller.ExternalURL host is a load
142 // balancer / gateway and not a local interface
143 // address (e.g., when running on a cloud VM).
145 // This avoids unnecessary delay/cost of routing
146 // external traffic, and also allows controller to
147 // recognize other services as internal clients based
148 // on the connection source address.
149 divertedHost := (*url.URL)(&cluster.Services.Controller.ExternalURL).Hostname()
150 var dialer net.Dialer
152 Transport: &http.Transport{
153 TLSClientConfig: &tls.Config{InsecureSkipVerify: cluster.TLS.Insecure},
154 DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
155 host, port, err := net.SplitHostPort(addr)
156 if err == nil && network == "tcp" && host == divertedHost {
157 addr = net.JoinHostPort(srvaddr, port)
159 return dialer.DialContext(ctx, network, addr)
166 Scheme: ctrlURL.Scheme,
167 APIHost: ctrlURL.Host,
168 Insecure: cluster.TLS.Insecure,
169 KeepServiceURIs: parseKeepServiceURIs(os.Getenv("ARVADOS_KEEP_SERVICES")),
170 Timeout: 5 * time.Minute,
171 DiskCacheSize: cluster.Collections.WebDAVCache.DiskCacheSize,
172 requestLimiter: &requestLimiter{maxlimit: int64(cluster.API.MaxConcurrentRequests / 4)},
177 // NewClientFromEnv creates a new Client that uses the default HTTP
178 // client, and loads API endpoint and credentials from ARVADOS_*
179 // environment variables (if set) and
180 // $HOME/.config/arvados/settings.conf (if readable).
182 // If a config exists in both locations, the environment variable is
185 // If there is an error (other than ENOENT) reading settings.conf,
186 // NewClientFromEnv logs the error to log.Default(), then proceeds as
187 // if settings.conf did not exist.
189 // Space characters are trimmed when reading the settings file, so
190 // these are equivalent:
192 // ARVADOS_API_HOST=localhost\n
193 // ARVADOS_API_HOST=localhost\r\n
194 // ARVADOS_API_HOST = localhost \n
195 // \tARVADOS_API_HOST = localhost\n
196 func NewClientFromEnv() *Client {
197 vars := map[string]string{}
198 home := os.Getenv("HOME")
199 conffile := home + "/.config/arvados/settings.conf"
201 // no $HOME => just use env vars
202 } else if settings, err := os.ReadFile(conffile); errors.Is(err, fs.ErrNotExist) {
203 // no config file => just use env vars
204 } else if err != nil {
205 // config file unreadable => log message, then use env vars
206 log.Printf("continuing without loading %s: %s", conffile, err)
208 for _, line := range bytes.Split(settings, []byte{'\n'}) {
209 kv := bytes.SplitN(line, []byte{'='}, 2)
210 k := string(bytes.TrimSpace(kv[0]))
211 if len(kv) != 2 || !strings.HasPrefix(k, "ARVADOS_") {
212 // Same behavior as python sdk:
213 // silently skip leading # (comments),
214 // blank lines, typos, and non-Arvados
218 vars[k] = string(bytes.TrimSpace(kv[1]))
221 for _, env := range os.Environ() {
222 if !strings.HasPrefix(env, "ARVADOS_") {
225 kv := strings.SplitN(env, "=", 2)
231 if s := strings.ToLower(vars["ARVADOS_API_HOST_INSECURE"]); s == "1" || s == "yes" || s == "true" {
236 APIHost: vars["ARVADOS_API_HOST"],
237 AuthToken: vars["ARVADOS_API_TOKEN"],
239 KeepServiceURIs: parseKeepServiceURIs(vars["ARVADOS_KEEP_SERVICES"]),
240 Timeout: 5 * time.Minute,
245 func parseKeepServiceURIs(svclist string) []string {
247 for _, s := range strings.Split(svclist, " ") {
250 } else if u, err := url.Parse(s); err != nil {
251 log.Printf("ARVADOS_KEEP_SERVICES: %q: %s", s, err)
252 } else if !u.IsAbs() {
253 log.Printf("ARVADOS_KEEP_SERVICES: %q: not an absolute URI", s)
255 svcs = append(svcs, s)
261 var reqIDGen = httpserver.IDGenerator{Prefix: "req-"}
263 var nopCancelFunc context.CancelFunc = func() {}
265 // Do augments (*http.Client)Do(): adds Authorization and X-Request-Id
266 // headers, delays in order to comply with rate-limiting restrictions,
267 // and retries failed requests when appropriate.
268 func (c *Client) Do(req *http.Request) (*http.Response, error) {
270 if auth, _ := ctx.Value(contextKeyAuthorization{}).(string); auth != "" {
271 req.Header.Add("Authorization", auth)
272 } else if c.AuthToken != "" {
273 req.Header.Add("Authorization", "Bearer "+c.AuthToken)
276 if req.Header.Get("X-Request-Id") == "" {
278 if ctxreqid, _ := ctx.Value(contextKeyRequestID{}).(string); ctxreqid != "" {
280 } else if c.defaultRequestID != "" {
281 reqid = c.defaultRequestID
283 reqid = reqIDGen.Next()
285 if req.Header == nil {
286 req.Header = http.Header{"X-Request-Id": {reqid}}
288 req.Header.Set("X-Request-Id", reqid)
292 rreq, err := retryablehttp.FromRequest(req)
297 cancel := nopCancelFunc
298 var lastResp *http.Response
299 var lastRespBody io.ReadCloser
301 var checkRetryCalled int
303 rclient := retryablehttp.NewClient()
304 rclient.HTTPClient = c.httpClient()
305 rclient.Backoff = exponentialBackoff
307 rclient.RetryWaitMax = c.Timeout / 10
308 rclient.RetryMax = 32
309 ctx, cancel = context.WithDeadline(ctx, time.Now().Add(c.Timeout))
310 rreq = rreq.WithContext(ctx)
314 rclient.CheckRetry = func(ctx context.Context, resp *http.Response, respErr error) (bool, error) {
316 if c.getRequestLimiter().Report(resp, respErr) {
317 c.last503.Store(time.Now())
322 retrying, err := retryablehttp.DefaultRetryPolicy(ctx, resp, respErr)
324 lastResp, lastRespBody, lastErr = resp, nil, respErr
326 // Save the response and body so we
327 // can return it instead of "deadline
328 // exceeded". retryablehttp.Client
329 // will drain and discard resp.body,
330 // so we need to stash it separately.
331 buf, err := ioutil.ReadAll(resp.Body)
333 lastRespBody = io.NopCloser(bytes.NewReader(buf))
335 lastResp, lastErr = nil, err
343 limiter := c.getRequestLimiter()
345 if ctx.Err() != nil {
348 return nil, ctx.Err()
350 resp, err := rclient.Do(rreq)
351 if (errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled)) && (lastResp != nil || lastErr != nil) {
354 if checkRetryCalled > 0 && err != nil {
355 // Mimic retryablehttp's "giving up after X
356 // attempts" message, even if we gave up
357 // because of time rather than maxretries.
358 err = fmt.Errorf("%s %s giving up after %d attempt(s): %w", req.Method, req.URL.String(), checkRetryCalled, err)
361 resp.Body = lastRespBody
369 // We need to call cancel() eventually, but we can't use
370 // "defer cancel()" because the context has to stay alive
371 // until the caller has finished reading the response body.
372 resp.Body = cancelOnClose{
373 ReadCloser: resp.Body,
382 // Last503 returns the time of the most recent HTTP 503 (Service
383 // Unavailable) response. Zero time indicates never.
384 func (c *Client) Last503() time.Time {
385 t, _ := c.last503.Load().(time.Time)
389 // globalRequestLimiter entries (one for each APIHost) don't have a
390 // hard limit on outgoing connections, but do add a delay and reduce
391 // concurrency after 503 errors.
393 globalRequestLimiter = map[string]*requestLimiter{}
394 globalRequestLimiterLock sync.Mutex
397 // Get this client's requestLimiter, or a global requestLimiter
398 // singleton for c's APIHost if this client doesn't have its own.
399 func (c *Client) getRequestLimiter() *requestLimiter {
400 if c.requestLimiter != nil {
401 return c.requestLimiter
403 globalRequestLimiterLock.Lock()
404 defer globalRequestLimiterLock.Unlock()
405 limiter := globalRequestLimiter[c.APIHost]
407 limiter = &requestLimiter{}
408 globalRequestLimiter[c.APIHost] = limiter
413 // cancelOnClose calls a provided CancelFunc when its wrapped
414 // ReadCloser's Close() method is called.
415 type cancelOnClose struct {
417 cancel context.CancelFunc
420 func (coc cancelOnClose) Close() error {
421 err := coc.ReadCloser.Close()
426 func isRedirectStatus(code int) bool {
428 case http.StatusMovedPermanently, http.StatusFound, http.StatusSeeOther, http.StatusTemporaryRedirect, http.StatusPermanentRedirect:
435 const minExponentialBackoffBase = time.Second
437 // Implements retryablehttp.Backoff using the server-provided
438 // Retry-After header if available, otherwise nearly-full jitter
439 // exponential backoff (similar to
440 // https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/),
441 // in all cases respecting the provided min and max.
442 func exponentialBackoff(min, max time.Duration, attemptNum int, resp *http.Response) time.Duration {
443 if attemptNum > 0 && min < minExponentialBackoffBase {
444 min = minExponentialBackoffBase
447 if resp != nil && (resp.StatusCode == http.StatusTooManyRequests || resp.StatusCode == http.StatusServiceUnavailable) {
448 if s := resp.Header.Get("Retry-After"); s != "" {
449 if sleep, err := strconv.ParseInt(s, 10, 64); err == nil {
450 t = time.Second * time.Duration(sleep)
451 } else if stamp, err := time.Parse(time.RFC1123, s); err == nil {
452 t = stamp.Sub(time.Now())
457 jitter := mathrand.New(mathrand.NewSource(int64(time.Now().Nanosecond()))).Float64()
458 t = min + time.Duration((math.Pow(2, float64(attemptNum))*float64(min)-float64(min))*jitter)
469 // DoAndDecode performs req and unmarshals the response (which must be
470 // JSON) into dst. Use this instead of RequestAndDecode if you need
471 // more control of the http.Request object.
473 // If the response status indicates an HTTP redirect, the Location
474 // header value is unmarshalled to dst as a RedirectLocation
476 func (c *Client) DoAndDecode(dst interface{}, req *http.Request) error {
477 resp, err := c.Do(req)
481 defer resp.Body.Close()
482 buf, err := ioutil.ReadAll(resp.Body)
487 case resp.StatusCode == http.StatusNoContent:
489 case resp.StatusCode == http.StatusOK && dst == nil:
491 case resp.StatusCode == http.StatusOK:
492 return json.Unmarshal(buf, dst)
494 // If the caller uses a client with a custom CheckRedirect
495 // func, Do() might return the 3xx response instead of
497 case isRedirectStatus(resp.StatusCode) && dst == nil:
499 case isRedirectStatus(resp.StatusCode):
500 // Copy the redirect target URL to dst.RedirectLocation.
501 buf, err := json.Marshal(map[string]string{"redirect_location": resp.Header.Get("Location")})
505 return json.Unmarshal(buf, dst)
508 return newTransactionError(req, resp, buf)
512 // Convert an arbitrary struct to url.Values. For example,
514 // Foo{Bar: []int{1,2,3}, Baz: "waz"}
518 // url.Values{`bar`:`{"a":[1,2,3]}`,`Baz`:`waz`}
520 // params itself is returned if it is already an url.Values.
521 func anythingToValues(params interface{}) (url.Values, error) {
522 if v, ok := params.(url.Values); ok {
525 // TODO: Do this more efficiently, possibly using
526 // json.Decode/Encode, so the whole thing doesn't have to get
527 // encoded, decoded, and re-encoded.
528 j, err := json.Marshal(params)
532 var generic map[string]interface{}
533 dec := json.NewDecoder(bytes.NewBuffer(j))
535 err = dec.Decode(&generic)
539 urlValues := url.Values{}
540 for k, v := range generic {
541 if v, ok := v.(string); ok {
545 if v, ok := v.(json.Number); ok {
546 urlValues.Set(k, v.String())
549 if v, ok := v.(bool); ok {
551 urlValues.Set(k, "true")
553 // "foo=false", "foo=0", and "foo="
554 // are all taken as true strings, so
555 // don't send false values at all --
556 // rely on the default being false.
560 j, err := json.Marshal(v)
564 if bytes.Equal(j, []byte("null")) {
565 // don't add it to urlValues at all
568 urlValues.Set(k, string(j))
570 return urlValues, nil
573 // RequestAndDecode performs an API request and unmarshals the
574 // response (which must be JSON) into dst. Method and body arguments
575 // are the same as for http.NewRequest(). The given path is added to
576 // the server's scheme/host/port to form the request URL. The given
577 // params are passed via POST form or query string.
579 // path must not contain a query string.
580 func (c *Client) RequestAndDecode(dst interface{}, method, path string, body io.Reader, params interface{}) error {
581 return c.RequestAndDecodeContext(context.Background(), dst, method, path, body, params)
584 // RequestAndDecodeContext does the same as RequestAndDecode, but with a context
585 func (c *Client) RequestAndDecodeContext(ctx context.Context, dst interface{}, method, path string, body io.Reader, params interface{}) error {
586 if body, ok := body.(io.Closer); ok {
587 // Ensure body is closed even if we error out early
592 return errors.New("ARVADOS_API_HOST and/or ARVADOS_API_TOKEN environment variables are not set")
594 return errors.New("arvados.Client cannot perform request: APIHost is not set")
596 urlString := c.apiURL(path)
597 urlValues, err := anythingToValues(params)
602 if urlValues == nil {
603 urlValues = url.Values{}
605 urlValues["select"] = []string{`["uuid"]`}
607 if urlValues == nil {
609 } else if body != nil || ((method == "GET" || method == "HEAD") && len(urlValues.Encode()) < 1000) {
610 // Send params in query part of URL
611 u, err := url.Parse(urlString)
615 u.RawQuery = urlValues.Encode()
616 urlString = u.String()
618 body = strings.NewReader(urlValues.Encode())
620 req, err := http.NewRequest(method, urlString, body)
624 if (method == "GET" || method == "HEAD") && body != nil {
625 req.Header.Set("X-Http-Method-Override", method)
628 req = req.WithContext(ctx)
629 req.Header.Set("Content-type", "application/x-www-form-urlencoded")
630 for k, v := range c.SendHeader {
633 return c.DoAndDecode(dst, req)
636 type resource interface {
637 resourceName() string
640 // UpdateBody returns an io.Reader suitable for use as an http.Request
641 // Body for a create or update API call.
642 func (c *Client) UpdateBody(rsc resource) io.Reader {
643 j, err := json.Marshal(rsc)
645 // Return a reader that returns errors.
647 w.CloseWithError(err)
650 v := url.Values{rsc.resourceName(): {string(j)}}
651 return bytes.NewBufferString(v.Encode())
654 // WithRequestID returns a new shallow copy of c that sends the given
655 // X-Request-Id value (instead of a new randomly generated one) with
656 // each subsequent request that doesn't provide its own via context or
658 func (c *Client) WithRequestID(reqid string) *Client {
660 cc.defaultRequestID = reqid
664 func (c *Client) httpClient() *http.Client {
666 case c.Client != nil:
669 return InsecureHTTPClient
671 return DefaultSecureClient
675 func (c *Client) apiURL(path string) string {
680 // Double-slash in URLs tend to cause subtle hidden problems
681 // (e.g., they can behave differently when a load balancer is
682 // in the picture). Here we ensure exactly one "/" regardless
683 // of whether the given APIHost or path has a superfluous one.
684 return scheme + "://" + strings.TrimSuffix(c.APIHost, "/") + "/" + strings.TrimPrefix(path, "/")
687 // DiscoveryDocument is the Arvados server's description of itself.
688 type DiscoveryDocument struct {
689 BasePath string `json:"basePath"`
690 DefaultCollectionReplication int `json:"defaultCollectionReplication"`
691 BlobSignatureTTL int64 `json:"blobSignatureTtl"`
692 GitURL string `json:"gitUrl"`
693 Schemas map[string]Schema `json:"schemas"`
694 Resources map[string]Resource `json:"resources"`
695 Revision string `json:"revision"`
698 type Resource struct {
699 Methods map[string]ResourceMethod `json:"methods"`
702 type ResourceMethod struct {
703 HTTPMethod string `json:"httpMethod"`
704 Path string `json:"path"`
705 Response MethodResponse `json:"response"`
708 type MethodResponse struct {
709 Ref string `json:"$ref"`
713 UUIDPrefix string `json:"uuidPrefix"`
716 // DiscoveryDocument returns a *DiscoveryDocument. The returned object
717 // should not be modified: the same object may be returned by
719 func (c *Client) DiscoveryDocument() (*DiscoveryDocument, error) {
723 var dd DiscoveryDocument
724 err := c.RequestAndDecode(&dd, "GET", "discovery/v1/apis/arvados/v1/rest", nil, nil)
732 var pdhRegexp = regexp.MustCompile(`^[0-9a-f]{32}\+\d+$`)
734 func (c *Client) modelForUUID(dd *DiscoveryDocument, uuid string) (string, error) {
735 if pdhRegexp.MatchString(uuid) {
736 return "Collection", nil
739 return "", fmt.Errorf("invalid UUID: %q", uuid)
743 for m, s := range dd.Schemas {
744 if s.UUIDPrefix == infix {
750 return "", fmt.Errorf("unrecognized type portion %q in UUID %q", infix, uuid)
755 func (c *Client) KindForUUID(uuid string) (string, error) {
756 dd, err := c.DiscoveryDocument()
760 model, err := c.modelForUUID(dd, uuid)
764 return "arvados#" + strings.ToLower(model[:1]) + model[1:], nil
767 func (c *Client) PathForUUID(method, uuid string) (string, error) {
768 dd, err := c.DiscoveryDocument()
772 model, err := c.modelForUUID(dd, uuid)
777 for r, rsc := range dd.Resources {
778 if rsc.Methods["get"].Response.Ref == model {
784 return "", fmt.Errorf("no resource for model: %q", model)
786 m, ok := dd.Resources[resource].Methods[method]
788 return "", fmt.Errorf("no method %q for resource %q", method, resource)
790 path := dd.BasePath + strings.Replace(m.Path, "{uuid}", uuid, -1)
797 var maxUUIDInt = (&big.Int{}).Exp(big.NewInt(36), big.NewInt(15), nil)
799 func RandomUUID(clusterID, infix string) string {
800 n, err := rand.Int(rand.Reader, maxUUIDInt)
808 return clusterID + "-" + infix + "-" + nstr