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.
82 defaultRequestID string
84 // APIHost and AuthToken were loaded from ARVADOS_* env vars
85 // (used to customize "no host/token" error messages)
88 // Track/limit concurrent outgoing API calls. Note this
89 // differs from an outgoing connection limit (a feature
90 // provided by http.Transport) when concurrent calls are
91 // multiplexed on a single http2 connection.
93 // getRequestLimiter() should always be used, because this can
95 requestLimiter *requestLimiter
100 // InsecureHTTPClient is the default http.Client used by a Client with
101 // Insecure==true and Client==nil.
102 var InsecureHTTPClient = &http.Client{
103 Transport: &http.Transport{
104 TLSClientConfig: &tls.Config{
105 InsecureSkipVerify: true}}}
107 // DefaultSecureClient is the default http.Client used by a Client otherwise.
108 var DefaultSecureClient = &http.Client{}
110 // NewClientFromConfig creates a new Client that uses the endpoints in
111 // the given cluster.
113 // AuthToken is left empty for the caller to populate.
114 func NewClientFromConfig(cluster *Cluster) (*Client, error) {
115 ctrlURL := cluster.Services.Controller.ExternalURL
116 if ctrlURL.Host == "" {
117 return nil, fmt.Errorf("no host in config Services.Controller.ExternalURL: %v", ctrlURL)
120 if srvaddr := os.Getenv("ARVADOS_SERVER_ADDRESS"); srvaddr != "" {
121 // When this client is used to make a request to
122 // https://{ctrlhost}:port/ (any port), it dials the
123 // indicated port on ARVADOS_SERVER_ADDRESS instead.
125 // This is invoked by arvados-server boot to ensure
126 // that server->server traffic (e.g.,
127 // keepproxy->controller) only hits local interfaces,
128 // even if the Controller.ExternalURL host is a load
129 // balancer / gateway and not a local interface
130 // address (e.g., when running on a cloud VM).
132 // This avoids unnecessary delay/cost of routing
133 // external traffic, and also allows controller to
134 // recognize other services as internal clients based
135 // on the connection source address.
136 divertedHost := (*url.URL)(&cluster.Services.Controller.ExternalURL).Hostname()
137 var dialer net.Dialer
139 Transport: &http.Transport{
140 TLSClientConfig: &tls.Config{InsecureSkipVerify: cluster.TLS.Insecure},
141 DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
142 host, port, err := net.SplitHostPort(addr)
143 if err == nil && network == "tcp" && host == divertedHost {
144 addr = net.JoinHostPort(srvaddr, port)
146 return dialer.DialContext(ctx, network, addr)
153 Scheme: ctrlURL.Scheme,
154 APIHost: ctrlURL.Host,
155 Insecure: cluster.TLS.Insecure,
156 Timeout: 5 * time.Minute,
157 requestLimiter: &requestLimiter{maxlimit: int64(cluster.API.MaxConcurrentRequests / 4)},
161 // NewClientFromEnv creates a new Client that uses the default HTTP
162 // client, and loads API endpoint and credentials from ARVADOS_*
163 // environment variables (if set) and
164 // $HOME/.config/arvados/settings.conf (if readable).
166 // If a config exists in both locations, the environment variable is
169 // If there is an error (other than ENOENT) reading settings.conf,
170 // NewClientFromEnv logs the error to log.Default(), then proceeds as
171 // if settings.conf did not exist.
173 // Space characters are trimmed when reading the settings file, so
174 // these are equivalent:
176 // ARVADOS_API_HOST=localhost\n
177 // ARVADOS_API_HOST=localhost\r\n
178 // ARVADOS_API_HOST = localhost \n
179 // \tARVADOS_API_HOST = localhost\n
180 func NewClientFromEnv() *Client {
181 vars := map[string]string{}
182 home := os.Getenv("HOME")
183 conffile := home + "/.config/arvados/settings.conf"
185 // no $HOME => just use env vars
186 } else if settings, err := os.ReadFile(conffile); errors.Is(err, fs.ErrNotExist) {
187 // no config file => just use env vars
188 } else if err != nil {
189 // config file unreadable => log message, then use env vars
190 log.Printf("continuing without loading %s: %s", conffile, err)
192 for _, line := range bytes.Split(settings, []byte{'\n'}) {
193 kv := bytes.SplitN(line, []byte{'='}, 2)
194 k := string(bytes.TrimSpace(kv[0]))
195 if len(kv) != 2 || !strings.HasPrefix(k, "ARVADOS_") {
196 // Same behavior as python sdk:
197 // silently skip leading # (comments),
198 // blank lines, typos, and non-Arvados
202 vars[k] = string(bytes.TrimSpace(kv[1]))
205 for _, env := range os.Environ() {
206 if !strings.HasPrefix(env, "ARVADOS_") {
209 kv := strings.SplitN(env, "=", 2)
215 for _, s := range strings.Split(vars["ARVADOS_KEEP_SERVICES"], " ") {
218 } else if u, err := url.Parse(s); err != nil {
219 log.Printf("ARVADOS_KEEP_SERVICES: %q: %s", s, err)
220 } else if !u.IsAbs() {
221 log.Printf("ARVADOS_KEEP_SERVICES: %q: not an absolute URI", s)
223 svcs = append(svcs, s)
227 if s := strings.ToLower(vars["ARVADOS_API_HOST_INSECURE"]); s == "1" || s == "yes" || s == "true" {
232 APIHost: vars["ARVADOS_API_HOST"],
233 AuthToken: vars["ARVADOS_API_TOKEN"],
235 KeepServiceURIs: svcs,
236 Timeout: 5 * time.Minute,
241 var reqIDGen = httpserver.IDGenerator{Prefix: "req-"}
243 var nopCancelFunc context.CancelFunc = func() {}
245 var reqErrorRe = regexp.MustCompile(`net/http: invalid header `)
247 // Do augments (*http.Client)Do(): adds Authorization and X-Request-Id
248 // headers, delays in order to comply with rate-limiting restrictions,
249 // and retries failed requests when appropriate.
250 func (c *Client) Do(req *http.Request) (*http.Response, error) {
252 if auth, _ := ctx.Value(contextKeyAuthorization{}).(string); auth != "" {
253 req.Header.Add("Authorization", auth)
254 } else if c.AuthToken != "" {
255 req.Header.Add("Authorization", "OAuth2 "+c.AuthToken)
258 if req.Header.Get("X-Request-Id") == "" {
260 if ctxreqid, _ := ctx.Value(contextKeyRequestID{}).(string); ctxreqid != "" {
262 } else if c.defaultRequestID != "" {
263 reqid = c.defaultRequestID
265 reqid = reqIDGen.Next()
267 if req.Header == nil {
268 req.Header = http.Header{"X-Request-Id": {reqid}}
270 req.Header.Set("X-Request-Id", reqid)
274 rreq, err := retryablehttp.FromRequest(req)
279 cancel := nopCancelFunc
280 var lastResp *http.Response
281 var lastRespBody io.ReadCloser
283 var checkRetryCalled int
285 rclient := retryablehttp.NewClient()
286 rclient.HTTPClient = c.httpClient()
287 rclient.Backoff = exponentialBackoff
289 rclient.RetryWaitMax = c.Timeout / 10
290 rclient.RetryMax = 32
291 ctx, cancel = context.WithDeadline(ctx, time.Now().Add(c.Timeout))
292 rreq = rreq.WithContext(ctx)
296 rclient.CheckRetry = func(ctx context.Context, resp *http.Response, respErr error) (bool, error) {
298 if c.getRequestLimiter().Report(resp, respErr) {
299 c.last503.Store(time.Now())
304 if respErr != nil && reqErrorRe.MatchString(respErr.Error()) {
307 retrying, err := retryablehttp.DefaultRetryPolicy(ctx, resp, respErr)
309 lastResp, lastRespBody, lastErr = resp, nil, respErr
311 // Save the response and body so we
312 // can return it instead of "deadline
313 // exceeded". retryablehttp.Client
314 // will drain and discard resp.body,
315 // so we need to stash it separately.
316 buf, err := ioutil.ReadAll(resp.Body)
318 lastRespBody = io.NopCloser(bytes.NewReader(buf))
320 lastResp, lastErr = nil, err
328 limiter := c.getRequestLimiter()
330 if ctx.Err() != nil {
333 return nil, ctx.Err()
335 resp, err := rclient.Do(rreq)
336 if (errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled)) && (lastResp != nil || lastErr != nil) {
339 if checkRetryCalled > 0 && err != nil {
340 // Mimic retryablehttp's "giving up after X
341 // attempts" message, even if we gave up
342 // because of time rather than maxretries.
343 err = fmt.Errorf("%s %s giving up after %d attempt(s): %w", req.Method, req.URL.String(), checkRetryCalled, err)
346 resp.Body = lastRespBody
354 // We need to call cancel() eventually, but we can't use
355 // "defer cancel()" because the context has to stay alive
356 // until the caller has finished reading the response body.
357 resp.Body = cancelOnClose{
358 ReadCloser: resp.Body,
367 // Last503 returns the time of the most recent HTTP 503 (Service
368 // Unavailable) response. Zero time indicates never.
369 func (c *Client) Last503() time.Time {
370 t, _ := c.last503.Load().(time.Time)
374 // globalRequestLimiter entries (one for each APIHost) don't have a
375 // hard limit on outgoing connections, but do add a delay and reduce
376 // concurrency after 503 errors.
378 globalRequestLimiter = map[string]*requestLimiter{}
379 globalRequestLimiterLock sync.Mutex
382 // Get this client's requestLimiter, or a global requestLimiter
383 // singleton for c's APIHost if this client doesn't have its own.
384 func (c *Client) getRequestLimiter() *requestLimiter {
385 if c.requestLimiter != nil {
386 return c.requestLimiter
388 globalRequestLimiterLock.Lock()
389 defer globalRequestLimiterLock.Unlock()
390 limiter := globalRequestLimiter[c.APIHost]
392 limiter = &requestLimiter{}
393 globalRequestLimiter[c.APIHost] = limiter
398 // cancelOnClose calls a provided CancelFunc when its wrapped
399 // ReadCloser's Close() method is called.
400 type cancelOnClose struct {
402 cancel context.CancelFunc
405 func (coc cancelOnClose) Close() error {
406 err := coc.ReadCloser.Close()
411 func isRedirectStatus(code int) bool {
413 case http.StatusMovedPermanently, http.StatusFound, http.StatusSeeOther, http.StatusTemporaryRedirect, http.StatusPermanentRedirect:
420 const minExponentialBackoffBase = time.Second
422 // Implements retryablehttp.Backoff using the server-provided
423 // Retry-After header if available, otherwise nearly-full jitter
424 // exponential backoff (similar to
425 // https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/),
426 // in all cases respecting the provided min and max.
427 func exponentialBackoff(min, max time.Duration, attemptNum int, resp *http.Response) time.Duration {
428 if attemptNum > 0 && min < minExponentialBackoffBase {
429 min = minExponentialBackoffBase
432 if resp != nil && (resp.StatusCode == http.StatusTooManyRequests || resp.StatusCode == http.StatusServiceUnavailable) {
433 if s := resp.Header.Get("Retry-After"); s != "" {
434 if sleep, err := strconv.ParseInt(s, 10, 64); err == nil {
435 t = time.Second * time.Duration(sleep)
436 } else if stamp, err := time.Parse(time.RFC1123, s); err == nil {
437 t = stamp.Sub(time.Now())
442 jitter := mathrand.New(mathrand.NewSource(int64(time.Now().Nanosecond()))).Float64()
443 t = min + time.Duration((math.Pow(2, float64(attemptNum))*float64(min)-float64(min))*jitter)
454 // DoAndDecode performs req and unmarshals the response (which must be
455 // JSON) into dst. Use this instead of RequestAndDecode if you need
456 // more control of the http.Request object.
458 // If the response status indicates an HTTP redirect, the Location
459 // header value is unmarshalled to dst as a RedirectLocation
461 func (c *Client) DoAndDecode(dst interface{}, req *http.Request) error {
462 resp, err := c.Do(req)
466 defer resp.Body.Close()
467 buf, err := ioutil.ReadAll(resp.Body)
472 case resp.StatusCode == http.StatusNoContent:
474 case resp.StatusCode == http.StatusOK && dst == nil:
476 case resp.StatusCode == http.StatusOK:
477 return json.Unmarshal(buf, dst)
479 // If the caller uses a client with a custom CheckRedirect
480 // func, Do() might return the 3xx response instead of
482 case isRedirectStatus(resp.StatusCode) && dst == nil:
484 case isRedirectStatus(resp.StatusCode):
485 // Copy the redirect target URL to dst.RedirectLocation.
486 buf, err := json.Marshal(map[string]string{"redirect_location": resp.Header.Get("Location")})
490 return json.Unmarshal(buf, dst)
493 return newTransactionError(req, resp, buf)
497 // Convert an arbitrary struct to url.Values. For example,
499 // Foo{Bar: []int{1,2,3}, Baz: "waz"}
503 // url.Values{`bar`:`{"a":[1,2,3]}`,`Baz`:`waz`}
505 // params itself is returned if it is already an url.Values.
506 func anythingToValues(params interface{}) (url.Values, error) {
507 if v, ok := params.(url.Values); ok {
510 // TODO: Do this more efficiently, possibly using
511 // json.Decode/Encode, so the whole thing doesn't have to get
512 // encoded, decoded, and re-encoded.
513 j, err := json.Marshal(params)
517 var generic map[string]interface{}
518 dec := json.NewDecoder(bytes.NewBuffer(j))
520 err = dec.Decode(&generic)
524 urlValues := url.Values{}
525 for k, v := range generic {
526 if v, ok := v.(string); ok {
530 if v, ok := v.(json.Number); ok {
531 urlValues.Set(k, v.String())
534 if v, ok := v.(bool); ok {
536 urlValues.Set(k, "true")
538 // "foo=false", "foo=0", and "foo="
539 // are all taken as true strings, so
540 // don't send false values at all --
541 // rely on the default being false.
545 j, err := json.Marshal(v)
549 if bytes.Equal(j, []byte("null")) {
550 // don't add it to urlValues at all
553 urlValues.Set(k, string(j))
555 return urlValues, nil
558 // RequestAndDecode performs an API request and unmarshals the
559 // response (which must be JSON) into dst. Method and body arguments
560 // are the same as for http.NewRequest(). The given path is added to
561 // the server's scheme/host/port to form the request URL. The given
562 // params are passed via POST form or query string.
564 // path must not contain a query string.
565 func (c *Client) RequestAndDecode(dst interface{}, method, path string, body io.Reader, params interface{}) error {
566 return c.RequestAndDecodeContext(context.Background(), dst, method, path, body, params)
569 // RequestAndDecodeContext does the same as RequestAndDecode, but with a context
570 func (c *Client) RequestAndDecodeContext(ctx context.Context, dst interface{}, method, path string, body io.Reader, params interface{}) error {
571 if body, ok := body.(io.Closer); ok {
572 // Ensure body is closed even if we error out early
577 return errors.New("ARVADOS_API_HOST and/or ARVADOS_API_TOKEN environment variables are not set")
579 return errors.New("arvados.Client cannot perform request: APIHost is not set")
581 urlString := c.apiURL(path)
582 urlValues, err := anythingToValues(params)
587 if urlValues == nil {
588 urlValues = url.Values{}
590 urlValues["select"] = []string{`["uuid"]`}
592 if urlValues == nil {
594 } else if body != nil || ((method == "GET" || method == "HEAD") && len(urlValues.Encode()) < 1000) {
595 // Send params in query part of URL
596 u, err := url.Parse(urlString)
600 u.RawQuery = urlValues.Encode()
601 urlString = u.String()
603 body = strings.NewReader(urlValues.Encode())
605 req, err := http.NewRequest(method, urlString, body)
609 if (method == "GET" || method == "HEAD") && body != nil {
610 req.Header.Set("X-Http-Method-Override", method)
613 req = req.WithContext(ctx)
614 req.Header.Set("Content-type", "application/x-www-form-urlencoded")
615 for k, v := range c.SendHeader {
618 return c.DoAndDecode(dst, req)
621 type resource interface {
622 resourceName() string
625 // UpdateBody returns an io.Reader suitable for use as an http.Request
626 // Body for a create or update API call.
627 func (c *Client) UpdateBody(rsc resource) io.Reader {
628 j, err := json.Marshal(rsc)
630 // Return a reader that returns errors.
632 w.CloseWithError(err)
635 v := url.Values{rsc.resourceName(): {string(j)}}
636 return bytes.NewBufferString(v.Encode())
639 // WithRequestID returns a new shallow copy of c that sends the given
640 // X-Request-Id value (instead of a new randomly generated one) with
641 // each subsequent request that doesn't provide its own via context or
643 func (c *Client) WithRequestID(reqid string) *Client {
645 cc.defaultRequestID = reqid
649 func (c *Client) httpClient() *http.Client {
651 case c.Client != nil:
654 return InsecureHTTPClient
656 return DefaultSecureClient
660 func (c *Client) apiURL(path string) string {
665 // Double-slash in URLs tend to cause subtle hidden problems
666 // (e.g., they can behave differently when a load balancer is
667 // in the picture). Here we ensure exactly one "/" regardless
668 // of whether the given APIHost or path has a superfluous one.
669 return scheme + "://" + strings.TrimSuffix(c.APIHost, "/") + "/" + strings.TrimPrefix(path, "/")
672 // DiscoveryDocument is the Arvados server's description of itself.
673 type DiscoveryDocument struct {
674 BasePath string `json:"basePath"`
675 DefaultCollectionReplication int `json:"defaultCollectionReplication"`
676 BlobSignatureTTL int64 `json:"blobSignatureTtl"`
677 GitURL string `json:"gitUrl"`
678 Schemas map[string]Schema `json:"schemas"`
679 Resources map[string]Resource `json:"resources"`
680 Revision string `json:"revision"`
683 type Resource struct {
684 Methods map[string]ResourceMethod `json:"methods"`
687 type ResourceMethod struct {
688 HTTPMethod string `json:"httpMethod"`
689 Path string `json:"path"`
690 Response MethodResponse `json:"response"`
693 type MethodResponse struct {
694 Ref string `json:"$ref"`
698 UUIDPrefix string `json:"uuidPrefix"`
701 // DiscoveryDocument returns a *DiscoveryDocument. The returned object
702 // should not be modified: the same object may be returned by
704 func (c *Client) DiscoveryDocument() (*DiscoveryDocument, error) {
708 var dd DiscoveryDocument
709 err := c.RequestAndDecode(&dd, "GET", "discovery/v1/apis/arvados/v1/rest", nil, nil)
717 var pdhRegexp = regexp.MustCompile(`^[0-9a-f]{32}\+\d+$`)
719 func (c *Client) modelForUUID(dd *DiscoveryDocument, uuid string) (string, error) {
720 if pdhRegexp.MatchString(uuid) {
721 return "Collection", nil
724 return "", fmt.Errorf("invalid UUID: %q", uuid)
728 for m, s := range dd.Schemas {
729 if s.UUIDPrefix == infix {
735 return "", fmt.Errorf("unrecognized type portion %q in UUID %q", infix, uuid)
740 func (c *Client) KindForUUID(uuid string) (string, error) {
741 dd, err := c.DiscoveryDocument()
745 model, err := c.modelForUUID(dd, uuid)
749 return "arvados#" + strings.ToLower(model[:1]) + model[1:], nil
752 func (c *Client) PathForUUID(method, uuid string) (string, error) {
753 dd, err := c.DiscoveryDocument()
757 model, err := c.modelForUUID(dd, uuid)
762 for r, rsc := range dd.Resources {
763 if rsc.Methods["get"].Response.Ref == model {
769 return "", fmt.Errorf("no resource for model: %q", model)
771 m, ok := dd.Resources[resource].Methods[method]
773 return "", fmt.Errorf("no method %q for resource %q", method, resource)
775 path := dd.BasePath + strings.Replace(m.Path, "{uuid}", uuid, -1)
782 var maxUUIDInt = (&big.Int{}).Exp(big.NewInt(36), big.NewInt(15), nil)
784 func RandomUUID(clusterID, infix string) string {
785 n, err := rand.Int(rand.Reader, maxUUIDInt)
793 return clusterID + "-" + infix + "-" + nstr