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"
37 // A Client is an HTTP client with an API endpoint and a set of
38 // Arvados credentials.
40 // It offers methods for accessing individual Arvados APIs, and
41 // methods that implement common patterns like fetching multiple pages
42 // of results using List APIs.
44 // HTTP client used to make requests. If nil,
45 // DefaultSecureClient or InsecureHTTPClient will be used.
46 Client *http.Client `json:"-"`
48 // Protocol scheme: "http", "https", or "" (https)
51 // Hostname (or host:port) of Arvados API server.
54 // User authentication token.
57 // Accept unverified certificates. This works only if the
58 // Client field is nil: otherwise, it has no effect.
61 // Override keep service discovery with a list of base
62 // URIs. (Currently there are no Client methods for
63 // discovering keep services so this is just a convenience for
64 // callers who use a Client to initialize an
65 // arvadosclient.ArvadosClient.)
66 KeepServiceURIs []string `json:",omitempty"`
68 // HTTP headers to add/override in outgoing requests.
69 SendHeader http.Header
71 // Timeout for requests. NewClientFromConfig and
72 // NewClientFromEnv return a Client with a default 5 minute
73 // timeout. Within this time, retryable errors are
74 // automatically retried with exponential backoff.
76 // To disable automatic retries, set Timeout to zero and use a
77 // context deadline to establish a maximum request time.
80 // Maximum disk cache size in bytes or percent of total
81 // filesystem size. If zero, use default, currently 10% of
83 DiskCacheSize ByteSizeOrPercent
87 defaultRequestID string
89 // APIHost and AuthToken were loaded from ARVADOS_* env vars
90 // (used to customize "no host/token" error messages)
93 // Track/limit concurrent outgoing API calls. Note this
94 // differs from an outgoing connection limit (a feature
95 // provided by http.Transport) when concurrent calls are
96 // multiplexed on a single http2 connection.
98 // getRequestLimiter() should always be used, because this can
100 requestLimiter *requestLimiter
105 // InsecureHTTPClient is the default http.Client used by a Client with
106 // Insecure==true and Client==nil.
107 var InsecureHTTPClient = &http.Client{
108 Transport: &http.Transport{
109 TLSClientConfig: &tls.Config{
110 InsecureSkipVerify: true}}}
112 // DefaultSecureClient is the default http.Client used by a Client otherwise.
113 var DefaultSecureClient = &http.Client{}
115 // NewClientFromConfig creates a new Client that uses the endpoints in
116 // the given cluster.
118 // AuthToken is left empty for the caller to populate.
119 func NewClientFromConfig(cluster *Cluster) (*Client, error) {
120 ctrlURL := cluster.Services.Controller.ExternalURL
121 if ctrlURL.Host == "" {
122 return nil, fmt.Errorf("no host in config Services.Controller.ExternalURL: %v", ctrlURL)
125 if srvaddr := os.Getenv("ARVADOS_SERVER_ADDRESS"); srvaddr != "" {
126 // When this client is used to make a request to
127 // https://{ctrlhost}:port/ (any port), it dials the
128 // indicated port on ARVADOS_SERVER_ADDRESS instead.
130 // This is invoked by arvados-server boot to ensure
131 // that server->server traffic (e.g.,
132 // keepproxy->controller) only hits local interfaces,
133 // even if the Controller.ExternalURL host is a load
134 // balancer / gateway and not a local interface
135 // address (e.g., when running on a cloud VM).
137 // This avoids unnecessary delay/cost of routing
138 // external traffic, and also allows controller to
139 // recognize other services as internal clients based
140 // on the connection source address.
141 divertedHost := (*url.URL)(&cluster.Services.Controller.ExternalURL).Hostname()
142 var dialer net.Dialer
144 Transport: &http.Transport{
145 TLSClientConfig: &tls.Config{InsecureSkipVerify: cluster.TLS.Insecure},
146 DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
147 host, port, err := net.SplitHostPort(addr)
148 if err == nil && network == "tcp" && host == divertedHost {
149 addr = net.JoinHostPort(srvaddr, port)
151 return dialer.DialContext(ctx, network, addr)
158 Scheme: ctrlURL.Scheme,
159 APIHost: ctrlURL.Host,
160 Insecure: cluster.TLS.Insecure,
161 Timeout: 5 * time.Minute,
162 DiskCacheSize: cluster.Collections.WebDAVCache.DiskCacheSize,
163 requestLimiter: &requestLimiter{maxlimit: int64(cluster.API.MaxConcurrentRequests / 4)},
167 // NewClientFromEnv creates a new Client that uses the default HTTP
168 // client, and loads API endpoint and credentials from ARVADOS_*
169 // environment variables (if set) and
170 // $HOME/.config/arvados/settings.conf (if readable).
172 // If a config exists in both locations, the environment variable is
175 // If there is an error (other than ENOENT) reading settings.conf,
176 // NewClientFromEnv logs the error to log.Default(), then proceeds as
177 // if settings.conf did not exist.
179 // Space characters are trimmed when reading the settings file, so
180 // these are equivalent:
182 // ARVADOS_API_HOST=localhost\n
183 // ARVADOS_API_HOST=localhost\r\n
184 // ARVADOS_API_HOST = localhost \n
185 // \tARVADOS_API_HOST = localhost\n
186 func NewClientFromEnv() *Client {
187 vars := map[string]string{}
188 home := os.Getenv("HOME")
189 conffile := home + "/.config/arvados/settings.conf"
191 // no $HOME => just use env vars
192 } else if settings, err := os.ReadFile(conffile); errors.Is(err, fs.ErrNotExist) {
193 // no config file => just use env vars
194 } else if err != nil {
195 // config file unreadable => log message, then use env vars
196 log.Printf("continuing without loading %s: %s", conffile, err)
198 for _, line := range bytes.Split(settings, []byte{'\n'}) {
199 kv := bytes.SplitN(line, []byte{'='}, 2)
200 k := string(bytes.TrimSpace(kv[0]))
201 if len(kv) != 2 || !strings.HasPrefix(k, "ARVADOS_") {
202 // Same behavior as python sdk:
203 // silently skip leading # (comments),
204 // blank lines, typos, and non-Arvados
208 vars[k] = string(bytes.TrimSpace(kv[1]))
211 for _, env := range os.Environ() {
212 if !strings.HasPrefix(env, "ARVADOS_") {
215 kv := strings.SplitN(env, "=", 2)
221 for _, s := range strings.Split(vars["ARVADOS_KEEP_SERVICES"], " ") {
224 } else if u, err := url.Parse(s); err != nil {
225 log.Printf("ARVADOS_KEEP_SERVICES: %q: %s", s, err)
226 } else if !u.IsAbs() {
227 log.Printf("ARVADOS_KEEP_SERVICES: %q: not an absolute URI", s)
229 svcs = append(svcs, s)
233 if s := strings.ToLower(vars["ARVADOS_API_HOST_INSECURE"]); s == "1" || s == "yes" || s == "true" {
238 APIHost: vars["ARVADOS_API_HOST"],
239 AuthToken: vars["ARVADOS_API_TOKEN"],
241 KeepServiceURIs: svcs,
242 Timeout: 5 * time.Minute,
247 var reqIDGen = httpserver.IDGenerator{Prefix: "req-"}
249 var nopCancelFunc context.CancelFunc = func() {}
251 var reqErrorRe = regexp.MustCompile(`net/http: invalid header `)
253 // Do augments (*http.Client)Do(): adds Authorization and X-Request-Id
254 // headers, delays in order to comply with rate-limiting restrictions,
255 // and retries failed requests when appropriate.
256 func (c *Client) Do(req *http.Request) (*http.Response, error) {
258 if auth, _ := ctx.Value(contextKeyAuthorization{}).(string); auth != "" {
259 req.Header.Add("Authorization", auth)
260 } else if c.AuthToken != "" {
261 req.Header.Add("Authorization", "OAuth2 "+c.AuthToken)
264 if req.Header.Get("X-Request-Id") == "" {
266 if ctxreqid, _ := ctx.Value(contextKeyRequestID{}).(string); ctxreqid != "" {
268 } else if c.defaultRequestID != "" {
269 reqid = c.defaultRequestID
271 reqid = reqIDGen.Next()
273 if req.Header == nil {
274 req.Header = http.Header{"X-Request-Id": {reqid}}
276 req.Header.Set("X-Request-Id", reqid)
280 rreq, err := retryablehttp.FromRequest(req)
285 cancel := nopCancelFunc
286 var lastResp *http.Response
287 var lastRespBody io.ReadCloser
289 var checkRetryCalled int
291 rclient := retryablehttp.NewClient()
292 rclient.HTTPClient = c.httpClient()
293 rclient.Backoff = exponentialBackoff
295 rclient.RetryWaitMax = c.Timeout / 10
296 rclient.RetryMax = 32
297 ctx, cancel = context.WithDeadline(ctx, time.Now().Add(c.Timeout))
298 rreq = rreq.WithContext(ctx)
302 rclient.CheckRetry = func(ctx context.Context, resp *http.Response, respErr error) (bool, error) {
304 if c.getRequestLimiter().Report(resp, respErr) {
305 c.last503.Store(time.Now())
310 if respErr != nil && reqErrorRe.MatchString(respErr.Error()) {
313 retrying, err := retryablehttp.DefaultRetryPolicy(ctx, resp, respErr)
315 lastResp, lastRespBody, lastErr = resp, nil, respErr
317 // Save the response and body so we
318 // can return it instead of "deadline
319 // exceeded". retryablehttp.Client
320 // will drain and discard resp.body,
321 // so we need to stash it separately.
322 buf, err := ioutil.ReadAll(resp.Body)
324 lastRespBody = io.NopCloser(bytes.NewReader(buf))
326 lastResp, lastErr = nil, err
334 limiter := c.getRequestLimiter()
336 if ctx.Err() != nil {
339 return nil, ctx.Err()
341 resp, err := rclient.Do(rreq)
342 if (errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled)) && (lastResp != nil || lastErr != nil) {
345 if checkRetryCalled > 0 && err != nil {
346 // Mimic retryablehttp's "giving up after X
347 // attempts" message, even if we gave up
348 // because of time rather than maxretries.
349 err = fmt.Errorf("%s %s giving up after %d attempt(s): %w", req.Method, req.URL.String(), checkRetryCalled, err)
352 resp.Body = lastRespBody
360 // We need to call cancel() eventually, but we can't use
361 // "defer cancel()" because the context has to stay alive
362 // until the caller has finished reading the response body.
363 resp.Body = cancelOnClose{
364 ReadCloser: resp.Body,
373 // Last503 returns the time of the most recent HTTP 503 (Service
374 // Unavailable) response. Zero time indicates never.
375 func (c *Client) Last503() time.Time {
376 t, _ := c.last503.Load().(time.Time)
380 // globalRequestLimiter entries (one for each APIHost) don't have a
381 // hard limit on outgoing connections, but do add a delay and reduce
382 // concurrency after 503 errors.
384 globalRequestLimiter = map[string]*requestLimiter{}
385 globalRequestLimiterLock sync.Mutex
388 // Get this client's requestLimiter, or a global requestLimiter
389 // singleton for c's APIHost if this client doesn't have its own.
390 func (c *Client) getRequestLimiter() *requestLimiter {
391 if c.requestLimiter != nil {
392 return c.requestLimiter
394 globalRequestLimiterLock.Lock()
395 defer globalRequestLimiterLock.Unlock()
396 limiter := globalRequestLimiter[c.APIHost]
398 limiter = &requestLimiter{}
399 globalRequestLimiter[c.APIHost] = limiter
404 // cancelOnClose calls a provided CancelFunc when its wrapped
405 // ReadCloser's Close() method is called.
406 type cancelOnClose struct {
408 cancel context.CancelFunc
411 func (coc cancelOnClose) Close() error {
412 err := coc.ReadCloser.Close()
417 func isRedirectStatus(code int) bool {
419 case http.StatusMovedPermanently, http.StatusFound, http.StatusSeeOther, http.StatusTemporaryRedirect, http.StatusPermanentRedirect:
426 const minExponentialBackoffBase = time.Second
428 // Implements retryablehttp.Backoff using the server-provided
429 // Retry-After header if available, otherwise nearly-full jitter
430 // exponential backoff (similar to
431 // https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/),
432 // in all cases respecting the provided min and max.
433 func exponentialBackoff(min, max time.Duration, attemptNum int, resp *http.Response) time.Duration {
434 if attemptNum > 0 && min < minExponentialBackoffBase {
435 min = minExponentialBackoffBase
438 if resp != nil && (resp.StatusCode == http.StatusTooManyRequests || resp.StatusCode == http.StatusServiceUnavailable) {
439 if s := resp.Header.Get("Retry-After"); s != "" {
440 if sleep, err := strconv.ParseInt(s, 10, 64); err == nil {
441 t = time.Second * time.Duration(sleep)
442 } else if stamp, err := time.Parse(time.RFC1123, s); err == nil {
443 t = stamp.Sub(time.Now())
448 jitter := mathrand.New(mathrand.NewSource(int64(time.Now().Nanosecond()))).Float64()
449 t = min + time.Duration((math.Pow(2, float64(attemptNum))*float64(min)-float64(min))*jitter)
460 // DoAndDecode performs req and unmarshals the response (which must be
461 // JSON) into dst. Use this instead of RequestAndDecode if you need
462 // more control of the http.Request object.
464 // If the response status indicates an HTTP redirect, the Location
465 // header value is unmarshalled to dst as a RedirectLocation
467 func (c *Client) DoAndDecode(dst interface{}, req *http.Request) error {
468 resp, err := c.Do(req)
472 defer resp.Body.Close()
473 buf, err := ioutil.ReadAll(resp.Body)
478 case resp.StatusCode == http.StatusNoContent:
480 case resp.StatusCode == http.StatusOK && dst == nil:
482 case resp.StatusCode == http.StatusOK:
483 return json.Unmarshal(buf, dst)
485 // If the caller uses a client with a custom CheckRedirect
486 // func, Do() might return the 3xx response instead of
488 case isRedirectStatus(resp.StatusCode) && dst == nil:
490 case isRedirectStatus(resp.StatusCode):
491 // Copy the redirect target URL to dst.RedirectLocation.
492 buf, err := json.Marshal(map[string]string{"redirect_location": resp.Header.Get("Location")})
496 return json.Unmarshal(buf, dst)
499 return newTransactionError(req, resp, buf)
503 // Convert an arbitrary struct to url.Values. For example,
505 // Foo{Bar: []int{1,2,3}, Baz: "waz"}
509 // url.Values{`bar`:`{"a":[1,2,3]}`,`Baz`:`waz`}
511 // params itself is returned if it is already an url.Values.
512 func anythingToValues(params interface{}) (url.Values, error) {
513 if v, ok := params.(url.Values); ok {
516 // TODO: Do this more efficiently, possibly using
517 // json.Decode/Encode, so the whole thing doesn't have to get
518 // encoded, decoded, and re-encoded.
519 j, err := json.Marshal(params)
523 var generic map[string]interface{}
524 dec := json.NewDecoder(bytes.NewBuffer(j))
526 err = dec.Decode(&generic)
530 urlValues := url.Values{}
531 for k, v := range generic {
532 if v, ok := v.(string); ok {
536 if v, ok := v.(json.Number); ok {
537 urlValues.Set(k, v.String())
540 if v, ok := v.(bool); ok {
542 urlValues.Set(k, "true")
544 // "foo=false", "foo=0", and "foo="
545 // are all taken as true strings, so
546 // don't send false values at all --
547 // rely on the default being false.
551 j, err := json.Marshal(v)
555 if bytes.Equal(j, []byte("null")) {
556 // don't add it to urlValues at all
559 urlValues.Set(k, string(j))
561 return urlValues, nil
564 // RequestAndDecode performs an API request and unmarshals the
565 // response (which must be JSON) into dst. Method and body arguments
566 // are the same as for http.NewRequest(). The given path is added to
567 // the server's scheme/host/port to form the request URL. The given
568 // params are passed via POST form or query string.
570 // path must not contain a query string.
571 func (c *Client) RequestAndDecode(dst interface{}, method, path string, body io.Reader, params interface{}) error {
572 return c.RequestAndDecodeContext(context.Background(), dst, method, path, body, params)
575 // RequestAndDecodeContext does the same as RequestAndDecode, but with a context
576 func (c *Client) RequestAndDecodeContext(ctx context.Context, dst interface{}, method, path string, body io.Reader, params interface{}) error {
577 if body, ok := body.(io.Closer); ok {
578 // Ensure body is closed even if we error out early
583 return errors.New("ARVADOS_API_HOST and/or ARVADOS_API_TOKEN environment variables are not set")
585 return errors.New("arvados.Client cannot perform request: APIHost is not set")
587 urlString := c.apiURL(path)
588 urlValues, err := anythingToValues(params)
593 if urlValues == nil {
594 urlValues = url.Values{}
596 urlValues["select"] = []string{`["uuid"]`}
598 if urlValues == nil {
600 } else if body != nil || ((method == "GET" || method == "HEAD") && len(urlValues.Encode()) < 1000) {
601 // Send params in query part of URL
602 u, err := url.Parse(urlString)
606 u.RawQuery = urlValues.Encode()
607 urlString = u.String()
609 body = strings.NewReader(urlValues.Encode())
611 req, err := http.NewRequest(method, urlString, body)
615 if (method == "GET" || method == "HEAD") && body != nil {
616 req.Header.Set("X-Http-Method-Override", method)
619 req = req.WithContext(ctx)
620 req.Header.Set("Content-type", "application/x-www-form-urlencoded")
621 for k, v := range c.SendHeader {
624 return c.DoAndDecode(dst, req)
627 type resource interface {
628 resourceName() string
631 // UpdateBody returns an io.Reader suitable for use as an http.Request
632 // Body for a create or update API call.
633 func (c *Client) UpdateBody(rsc resource) io.Reader {
634 j, err := json.Marshal(rsc)
636 // Return a reader that returns errors.
638 w.CloseWithError(err)
641 v := url.Values{rsc.resourceName(): {string(j)}}
642 return bytes.NewBufferString(v.Encode())
645 // WithRequestID returns a new shallow copy of c that sends the given
646 // X-Request-Id value (instead of a new randomly generated one) with
647 // each subsequent request that doesn't provide its own via context or
649 func (c *Client) WithRequestID(reqid string) *Client {
651 cc.defaultRequestID = reqid
655 func (c *Client) httpClient() *http.Client {
657 case c.Client != nil:
660 return InsecureHTTPClient
662 return DefaultSecureClient
666 func (c *Client) apiURL(path string) string {
671 // Double-slash in URLs tend to cause subtle hidden problems
672 // (e.g., they can behave differently when a load balancer is
673 // in the picture). Here we ensure exactly one "/" regardless
674 // of whether the given APIHost or path has a superfluous one.
675 return scheme + "://" + strings.TrimSuffix(c.APIHost, "/") + "/" + strings.TrimPrefix(path, "/")
678 // DiscoveryDocument is the Arvados server's description of itself.
679 type DiscoveryDocument struct {
680 BasePath string `json:"basePath"`
681 DefaultCollectionReplication int `json:"defaultCollectionReplication"`
682 BlobSignatureTTL int64 `json:"blobSignatureTtl"`
683 GitURL string `json:"gitUrl"`
684 Schemas map[string]Schema `json:"schemas"`
685 Resources map[string]Resource `json:"resources"`
686 Revision string `json:"revision"`
689 type Resource struct {
690 Methods map[string]ResourceMethod `json:"methods"`
693 type ResourceMethod struct {
694 HTTPMethod string `json:"httpMethod"`
695 Path string `json:"path"`
696 Response MethodResponse `json:"response"`
699 type MethodResponse struct {
700 Ref string `json:"$ref"`
704 UUIDPrefix string `json:"uuidPrefix"`
707 // DiscoveryDocument returns a *DiscoveryDocument. The returned object
708 // should not be modified: the same object may be returned by
710 func (c *Client) DiscoveryDocument() (*DiscoveryDocument, error) {
714 var dd DiscoveryDocument
715 err := c.RequestAndDecode(&dd, "GET", "discovery/v1/apis/arvados/v1/rest", nil, nil)
723 var pdhRegexp = regexp.MustCompile(`^[0-9a-f]{32}\+\d+$`)
725 func (c *Client) modelForUUID(dd *DiscoveryDocument, uuid string) (string, error) {
726 if pdhRegexp.MatchString(uuid) {
727 return "Collection", nil
730 return "", fmt.Errorf("invalid UUID: %q", uuid)
734 for m, s := range dd.Schemas {
735 if s.UUIDPrefix == infix {
741 return "", fmt.Errorf("unrecognized type portion %q in UUID %q", infix, uuid)
746 func (c *Client) KindForUUID(uuid string) (string, error) {
747 dd, err := c.DiscoveryDocument()
751 model, err := c.modelForUUID(dd, uuid)
755 return "arvados#" + strings.ToLower(model[:1]) + model[1:], nil
758 func (c *Client) PathForUUID(method, uuid string) (string, error) {
759 dd, err := c.DiscoveryDocument()
763 model, err := c.modelForUUID(dd, uuid)
768 for r, rsc := range dd.Resources {
769 if rsc.Methods["get"].Response.Ref == model {
775 return "", fmt.Errorf("no resource for model: %q", model)
777 m, ok := dd.Resources[resource].Methods[method]
779 return "", fmt.Errorf("no method %q for resource %q", method, resource)
781 path := dd.BasePath + strings.Replace(m.Path, "{uuid}", uuid, -1)
788 var maxUUIDInt = (&big.Int{}).Exp(big.NewInt(36), big.NewInt(15), nil)
790 func RandomUUID(clusterID, infix string) string {
791 n, err := rand.Int(rand.Reader, maxUUIDInt)
799 return clusterID + "-" + infix + "-" + nstr