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
91 defaultRequestID string
93 // APIHost and AuthToken were loaded from ARVADOS_* env vars
94 // (used to customize "no host/token" error messages)
97 // Track/limit concurrent outgoing API calls. Note this
98 // differs from an outgoing connection limit (a feature
99 // provided by http.Transport) when concurrent calls are
100 // multiplexed on a single http2 connection.
102 // getRequestLimiter() should always be used, because this can
104 requestLimiter *requestLimiter
109 // InsecureHTTPClient is the default http.Client used by a Client with
110 // Insecure==true and Client==nil.
111 var InsecureHTTPClient = &http.Client{
112 Transport: &http.Transport{
113 TLSClientConfig: &tls.Config{
114 InsecureSkipVerify: true}}}
116 // DefaultSecureClient is the default http.Client used by a Client otherwise.
117 var DefaultSecureClient = &http.Client{}
119 // NewClientFromConfig creates a new Client that uses the endpoints in
120 // the given cluster.
122 // AuthToken is left empty for the caller to populate.
123 func NewClientFromConfig(cluster *Cluster) (*Client, error) {
124 ctrlURL := cluster.Services.Controller.ExternalURL
125 if ctrlURL.Host == "" {
126 return nil, fmt.Errorf("no host in config Services.Controller.ExternalURL: %v", ctrlURL)
129 if srvaddr := os.Getenv("ARVADOS_SERVER_ADDRESS"); srvaddr != "" {
130 // When this client is used to make a request to
131 // https://{ctrlhost}:port/ (any port), it dials the
132 // indicated port on ARVADOS_SERVER_ADDRESS instead.
134 // This is invoked by arvados-server boot to ensure
135 // that server->server traffic (e.g.,
136 // keepproxy->controller) only hits local interfaces,
137 // even if the Controller.ExternalURL host is a load
138 // balancer / gateway and not a local interface
139 // address (e.g., when running on a cloud VM).
141 // This avoids unnecessary delay/cost of routing
142 // external traffic, and also allows controller to
143 // recognize other services as internal clients based
144 // on the connection source address.
145 divertedHost := (*url.URL)(&cluster.Services.Controller.ExternalURL).Hostname()
146 var dialer net.Dialer
148 Transport: &http.Transport{
149 TLSClientConfig: &tls.Config{InsecureSkipVerify: cluster.TLS.Insecure},
150 DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
151 host, port, err := net.SplitHostPort(addr)
152 if err == nil && network == "tcp" && host == divertedHost {
153 addr = net.JoinHostPort(srvaddr, port)
155 return dialer.DialContext(ctx, network, addr)
162 Scheme: ctrlURL.Scheme,
163 APIHost: ctrlURL.Host,
164 Insecure: cluster.TLS.Insecure,
165 Timeout: 5 * time.Minute,
166 DiskCacheSize: cluster.Collections.WebDAVCache.DiskCacheSize,
167 requestLimiter: &requestLimiter{maxlimit: int64(cluster.API.MaxConcurrentRequests / 4)},
171 // NewClientFromEnv creates a new Client that uses the default HTTP
172 // client, and loads API endpoint and credentials from ARVADOS_*
173 // environment variables (if set) and
174 // $HOME/.config/arvados/settings.conf (if readable).
176 // If a config exists in both locations, the environment variable is
179 // If there is an error (other than ENOENT) reading settings.conf,
180 // NewClientFromEnv logs the error to log.Default(), then proceeds as
181 // if settings.conf did not exist.
183 // Space characters are trimmed when reading the settings file, so
184 // these are equivalent:
186 // ARVADOS_API_HOST=localhost\n
187 // ARVADOS_API_HOST=localhost\r\n
188 // ARVADOS_API_HOST = localhost \n
189 // \tARVADOS_API_HOST = localhost\n
190 func NewClientFromEnv() *Client {
191 vars := map[string]string{}
192 home := os.Getenv("HOME")
193 conffile := home + "/.config/arvados/settings.conf"
195 // no $HOME => just use env vars
196 } else if settings, err := os.ReadFile(conffile); errors.Is(err, fs.ErrNotExist) {
197 // no config file => just use env vars
198 } else if err != nil {
199 // config file unreadable => log message, then use env vars
200 log.Printf("continuing without loading %s: %s", conffile, err)
202 for _, line := range bytes.Split(settings, []byte{'\n'}) {
203 kv := bytes.SplitN(line, []byte{'='}, 2)
204 k := string(bytes.TrimSpace(kv[0]))
205 if len(kv) != 2 || !strings.HasPrefix(k, "ARVADOS_") {
206 // Same behavior as python sdk:
207 // silently skip leading # (comments),
208 // blank lines, typos, and non-Arvados
212 vars[k] = string(bytes.TrimSpace(kv[1]))
215 for _, env := range os.Environ() {
216 if !strings.HasPrefix(env, "ARVADOS_") {
219 kv := strings.SplitN(env, "=", 2)
225 for _, s := range strings.Split(vars["ARVADOS_KEEP_SERVICES"], " ") {
228 } else if u, err := url.Parse(s); err != nil {
229 log.Printf("ARVADOS_KEEP_SERVICES: %q: %s", s, err)
230 } else if !u.IsAbs() {
231 log.Printf("ARVADOS_KEEP_SERVICES: %q: not an absolute URI", s)
233 svcs = append(svcs, s)
237 if s := strings.ToLower(vars["ARVADOS_API_HOST_INSECURE"]); s == "1" || s == "yes" || s == "true" {
242 APIHost: vars["ARVADOS_API_HOST"],
243 AuthToken: vars["ARVADOS_API_TOKEN"],
245 KeepServiceURIs: svcs,
246 Timeout: 5 * time.Minute,
251 var reqIDGen = httpserver.IDGenerator{Prefix: "req-"}
253 var nopCancelFunc context.CancelFunc = func() {}
255 // Do augments (*http.Client)Do(): adds Authorization and X-Request-Id
256 // headers, delays in order to comply with rate-limiting restrictions,
257 // and retries failed requests when appropriate.
258 func (c *Client) Do(req *http.Request) (*http.Response, error) {
260 if auth, _ := ctx.Value(contextKeyAuthorization{}).(string); auth != "" {
261 req.Header.Add("Authorization", auth)
262 } else if c.AuthToken != "" {
263 req.Header.Add("Authorization", "OAuth2 "+c.AuthToken)
266 if req.Header.Get("X-Request-Id") == "" {
268 if ctxreqid, _ := ctx.Value(contextKeyRequestID{}).(string); ctxreqid != "" {
270 } else if c.defaultRequestID != "" {
271 reqid = c.defaultRequestID
273 reqid = reqIDGen.Next()
275 if req.Header == nil {
276 req.Header = http.Header{"X-Request-Id": {reqid}}
278 req.Header.Set("X-Request-Id", reqid)
282 rreq, err := retryablehttp.FromRequest(req)
287 cancel := nopCancelFunc
288 var lastResp *http.Response
289 var lastRespBody io.ReadCloser
291 var checkRetryCalled int
293 rclient := retryablehttp.NewClient()
294 rclient.HTTPClient = c.httpClient()
295 rclient.Backoff = exponentialBackoff
297 rclient.RetryWaitMax = c.Timeout / 10
298 rclient.RetryMax = 32
299 ctx, cancel = context.WithDeadline(ctx, time.Now().Add(c.Timeout))
300 rreq = rreq.WithContext(ctx)
304 rclient.CheckRetry = func(ctx context.Context, resp *http.Response, respErr error) (bool, error) {
306 if c.getRequestLimiter().Report(resp, respErr) {
307 c.last503.Store(time.Now())
312 retrying, err := retryablehttp.DefaultRetryPolicy(ctx, resp, respErr)
314 lastResp, lastRespBody, lastErr = resp, nil, respErr
316 // Save the response and body so we
317 // can return it instead of "deadline
318 // exceeded". retryablehttp.Client
319 // will drain and discard resp.body,
320 // so we need to stash it separately.
321 buf, err := ioutil.ReadAll(resp.Body)
323 lastRespBody = io.NopCloser(bytes.NewReader(buf))
325 lastResp, lastErr = nil, err
333 limiter := c.getRequestLimiter()
335 if ctx.Err() != nil {
338 return nil, ctx.Err()
340 resp, err := rclient.Do(rreq)
341 if (errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled)) && (lastResp != nil || lastErr != nil) {
344 if checkRetryCalled > 0 && err != nil {
345 // Mimic retryablehttp's "giving up after X
346 // attempts" message, even if we gave up
347 // because of time rather than maxretries.
348 err = fmt.Errorf("%s %s giving up after %d attempt(s): %w", req.Method, req.URL.String(), checkRetryCalled, err)
351 resp.Body = lastRespBody
359 // We need to call cancel() eventually, but we can't use
360 // "defer cancel()" because the context has to stay alive
361 // until the caller has finished reading the response body.
362 resp.Body = cancelOnClose{
363 ReadCloser: resp.Body,
372 // Last503 returns the time of the most recent HTTP 503 (Service
373 // Unavailable) response. Zero time indicates never.
374 func (c *Client) Last503() time.Time {
375 t, _ := c.last503.Load().(time.Time)
379 // globalRequestLimiter entries (one for each APIHost) don't have a
380 // hard limit on outgoing connections, but do add a delay and reduce
381 // concurrency after 503 errors.
383 globalRequestLimiter = map[string]*requestLimiter{}
384 globalRequestLimiterLock sync.Mutex
387 // Get this client's requestLimiter, or a global requestLimiter
388 // singleton for c's APIHost if this client doesn't have its own.
389 func (c *Client) getRequestLimiter() *requestLimiter {
390 if c.requestLimiter != nil {
391 return c.requestLimiter
393 globalRequestLimiterLock.Lock()
394 defer globalRequestLimiterLock.Unlock()
395 limiter := globalRequestLimiter[c.APIHost]
397 limiter = &requestLimiter{}
398 globalRequestLimiter[c.APIHost] = limiter
403 // cancelOnClose calls a provided CancelFunc when its wrapped
404 // ReadCloser's Close() method is called.
405 type cancelOnClose struct {
407 cancel context.CancelFunc
410 func (coc cancelOnClose) Close() error {
411 err := coc.ReadCloser.Close()
416 func isRedirectStatus(code int) bool {
418 case http.StatusMovedPermanently, http.StatusFound, http.StatusSeeOther, http.StatusTemporaryRedirect, http.StatusPermanentRedirect:
425 const minExponentialBackoffBase = time.Second
427 // Implements retryablehttp.Backoff using the server-provided
428 // Retry-After header if available, otherwise nearly-full jitter
429 // exponential backoff (similar to
430 // https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/),
431 // in all cases respecting the provided min and max.
432 func exponentialBackoff(min, max time.Duration, attemptNum int, resp *http.Response) time.Duration {
433 if attemptNum > 0 && min < minExponentialBackoffBase {
434 min = minExponentialBackoffBase
437 if resp != nil && (resp.StatusCode == http.StatusTooManyRequests || resp.StatusCode == http.StatusServiceUnavailable) {
438 if s := resp.Header.Get("Retry-After"); s != "" {
439 if sleep, err := strconv.ParseInt(s, 10, 64); err == nil {
440 t = time.Second * time.Duration(sleep)
441 } else if stamp, err := time.Parse(time.RFC1123, s); err == nil {
442 t = stamp.Sub(time.Now())
447 jitter := mathrand.New(mathrand.NewSource(int64(time.Now().Nanosecond()))).Float64()
448 t = min + time.Duration((math.Pow(2, float64(attemptNum))*float64(min)-float64(min))*jitter)
459 // DoAndDecode performs req and unmarshals the response (which must be
460 // JSON) into dst. Use this instead of RequestAndDecode if you need
461 // more control of the http.Request object.
463 // If the response status indicates an HTTP redirect, the Location
464 // header value is unmarshalled to dst as a RedirectLocation
466 func (c *Client) DoAndDecode(dst interface{}, req *http.Request) error {
467 resp, err := c.Do(req)
471 defer resp.Body.Close()
472 buf, err := ioutil.ReadAll(resp.Body)
477 case resp.StatusCode == http.StatusNoContent:
479 case resp.StatusCode == http.StatusOK && dst == nil:
481 case resp.StatusCode == http.StatusOK:
482 return json.Unmarshal(buf, dst)
484 // If the caller uses a client with a custom CheckRedirect
485 // func, Do() might return the 3xx response instead of
487 case isRedirectStatus(resp.StatusCode) && dst == nil:
489 case isRedirectStatus(resp.StatusCode):
490 // Copy the redirect target URL to dst.RedirectLocation.
491 buf, err := json.Marshal(map[string]string{"redirect_location": resp.Header.Get("Location")})
495 return json.Unmarshal(buf, dst)
498 return newTransactionError(req, resp, buf)
502 // Convert an arbitrary struct to url.Values. For example,
504 // Foo{Bar: []int{1,2,3}, Baz: "waz"}
508 // url.Values{`bar`:`{"a":[1,2,3]}`,`Baz`:`waz`}
510 // params itself is returned if it is already an url.Values.
511 func anythingToValues(params interface{}) (url.Values, error) {
512 if v, ok := params.(url.Values); ok {
515 // TODO: Do this more efficiently, possibly using
516 // json.Decode/Encode, so the whole thing doesn't have to get
517 // encoded, decoded, and re-encoded.
518 j, err := json.Marshal(params)
522 var generic map[string]interface{}
523 dec := json.NewDecoder(bytes.NewBuffer(j))
525 err = dec.Decode(&generic)
529 urlValues := url.Values{}
530 for k, v := range generic {
531 if v, ok := v.(string); ok {
535 if v, ok := v.(json.Number); ok {
536 urlValues.Set(k, v.String())
539 if v, ok := v.(bool); ok {
541 urlValues.Set(k, "true")
543 // "foo=false", "foo=0", and "foo="
544 // are all taken as true strings, so
545 // don't send false values at all --
546 // rely on the default being false.
550 j, err := json.Marshal(v)
554 if bytes.Equal(j, []byte("null")) {
555 // don't add it to urlValues at all
558 urlValues.Set(k, string(j))
560 return urlValues, nil
563 // RequestAndDecode performs an API request and unmarshals the
564 // response (which must be JSON) into dst. Method and body arguments
565 // are the same as for http.NewRequest(). The given path is added to
566 // the server's scheme/host/port to form the request URL. The given
567 // params are passed via POST form or query string.
569 // path must not contain a query string.
570 func (c *Client) RequestAndDecode(dst interface{}, method, path string, body io.Reader, params interface{}) error {
571 return c.RequestAndDecodeContext(context.Background(), dst, method, path, body, params)
574 // RequestAndDecodeContext does the same as RequestAndDecode, but with a context
575 func (c *Client) RequestAndDecodeContext(ctx context.Context, dst interface{}, method, path string, body io.Reader, params interface{}) error {
576 if body, ok := body.(io.Closer); ok {
577 // Ensure body is closed even if we error out early
582 return errors.New("ARVADOS_API_HOST and/or ARVADOS_API_TOKEN environment variables are not set")
584 return errors.New("arvados.Client cannot perform request: APIHost is not set")
586 urlString := c.apiURL(path)
587 urlValues, err := anythingToValues(params)
592 if urlValues == nil {
593 urlValues = url.Values{}
595 urlValues["select"] = []string{`["uuid"]`}
597 if urlValues == nil {
599 } else if body != nil || ((method == "GET" || method == "HEAD") && len(urlValues.Encode()) < 1000) {
600 // Send params in query part of URL
601 u, err := url.Parse(urlString)
605 u.RawQuery = urlValues.Encode()
606 urlString = u.String()
608 body = strings.NewReader(urlValues.Encode())
610 req, err := http.NewRequest(method, urlString, body)
614 if (method == "GET" || method == "HEAD") && body != nil {
615 req.Header.Set("X-Http-Method-Override", method)
618 req = req.WithContext(ctx)
619 req.Header.Set("Content-type", "application/x-www-form-urlencoded")
620 for k, v := range c.SendHeader {
623 return c.DoAndDecode(dst, req)
626 type resource interface {
627 resourceName() string
630 // UpdateBody returns an io.Reader suitable for use as an http.Request
631 // Body for a create or update API call.
632 func (c *Client) UpdateBody(rsc resource) io.Reader {
633 j, err := json.Marshal(rsc)
635 // Return a reader that returns errors.
637 w.CloseWithError(err)
640 v := url.Values{rsc.resourceName(): {string(j)}}
641 return bytes.NewBufferString(v.Encode())
644 // WithRequestID returns a new shallow copy of c that sends the given
645 // X-Request-Id value (instead of a new randomly generated one) with
646 // each subsequent request that doesn't provide its own via context or
648 func (c *Client) WithRequestID(reqid string) *Client {
650 cc.defaultRequestID = reqid
654 func (c *Client) httpClient() *http.Client {
656 case c.Client != nil:
659 return InsecureHTTPClient
661 return DefaultSecureClient
665 func (c *Client) apiURL(path string) string {
670 // Double-slash in URLs tend to cause subtle hidden problems
671 // (e.g., they can behave differently when a load balancer is
672 // in the picture). Here we ensure exactly one "/" regardless
673 // of whether the given APIHost or path has a superfluous one.
674 return scheme + "://" + strings.TrimSuffix(c.APIHost, "/") + "/" + strings.TrimPrefix(path, "/")
677 // DiscoveryDocument is the Arvados server's description of itself.
678 type DiscoveryDocument struct {
679 BasePath string `json:"basePath"`
680 DefaultCollectionReplication int `json:"defaultCollectionReplication"`
681 BlobSignatureTTL int64 `json:"blobSignatureTtl"`
682 GitURL string `json:"gitUrl"`
683 Schemas map[string]Schema `json:"schemas"`
684 Resources map[string]Resource `json:"resources"`
685 Revision string `json:"revision"`
688 type Resource struct {
689 Methods map[string]ResourceMethod `json:"methods"`
692 type ResourceMethod struct {
693 HTTPMethod string `json:"httpMethod"`
694 Path string `json:"path"`
695 Response MethodResponse `json:"response"`
698 type MethodResponse struct {
699 Ref string `json:"$ref"`
703 UUIDPrefix string `json:"uuidPrefix"`
706 // DiscoveryDocument returns a *DiscoveryDocument. The returned object
707 // should not be modified: the same object may be returned by
709 func (c *Client) DiscoveryDocument() (*DiscoveryDocument, error) {
713 var dd DiscoveryDocument
714 err := c.RequestAndDecode(&dd, "GET", "discovery/v1/apis/arvados/v1/rest", nil, nil)
722 var pdhRegexp = regexp.MustCompile(`^[0-9a-f]{32}\+\d+$`)
724 func (c *Client) modelForUUID(dd *DiscoveryDocument, uuid string) (string, error) {
725 if pdhRegexp.MatchString(uuid) {
726 return "Collection", nil
729 return "", fmt.Errorf("invalid UUID: %q", uuid)
733 for m, s := range dd.Schemas {
734 if s.UUIDPrefix == infix {
740 return "", fmt.Errorf("unrecognized type portion %q in UUID %q", infix, uuid)
745 func (c *Client) KindForUUID(uuid string) (string, error) {
746 dd, err := c.DiscoveryDocument()
750 model, err := c.modelForUUID(dd, uuid)
754 return "arvados#" + strings.ToLower(model[:1]) + model[1:], nil
757 func (c *Client) PathForUUID(method, uuid string) (string, error) {
758 dd, err := c.DiscoveryDocument()
762 model, err := c.modelForUUID(dd, uuid)
767 for r, rsc := range dd.Resources {
768 if rsc.Methods["get"].Response.Ref == model {
774 return "", fmt.Errorf("no resource for model: %q", model)
776 m, ok := dd.Resources[resource].Methods[method]
778 return "", fmt.Errorf("no method %q for resource %q", method, resource)
780 path := dd.BasePath + strings.Replace(m.Path, "{uuid}", uuid, -1)
787 var maxUUIDInt = (&big.Int{}).Exp(big.NewInt(36), big.NewInt(15), nil)
789 func RandomUUID(clusterID, infix string) string {
790 n, err := rand.Int(rand.Reader, maxUUIDInt)
798 return clusterID + "-" + infix + "-" + nstr