1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: Apache-2.0
32 "git.arvados.org/arvados.git/sdk/go/httpserver"
33 "github.com/hashicorp/go-retryablehttp"
36 // A Client is an HTTP client with an API endpoint and a set of
37 // Arvados credentials.
39 // It offers methods for accessing individual Arvados APIs, and
40 // methods that implement common patterns like fetching multiple pages
41 // of results using List APIs.
43 // HTTP client used to make requests. If nil,
44 // DefaultSecureClient or InsecureHTTPClient will be used.
45 Client *http.Client `json:"-"`
47 // Protocol scheme: "http", "https", or "" (https)
50 // Hostname (or host:port) of Arvados API server.
53 // User authentication token.
56 // Accept unverified certificates. This works only if the
57 // Client field is nil: otherwise, it has no effect.
60 // Override keep service discovery with a list of base
61 // URIs. (Currently there are no Client methods for
62 // discovering keep services so this is just a convenience for
63 // callers who use a Client to initialize an
64 // arvadosclient.ArvadosClient.)
65 KeepServiceURIs []string `json:",omitempty"`
67 // HTTP headers to add/override in outgoing requests.
68 SendHeader http.Header
70 // Timeout for requests. NewClientFromConfig and
71 // NewClientFromEnv return a Client with a default 5 minute
72 // timeout. Within this time, retryable errors are
73 // automatically retried with exponential backoff.
75 // To disable automatic retries, set Timeout to zero and use a
76 // context deadline to establish a maximum request time.
81 defaultRequestID string
83 // APIHost and AuthToken were loaded from ARVADOS_* env vars
84 // (used to customize "no host/token" error messages)
87 // Track/limit concurrent outgoing API calls. Note this
88 // differs from an outgoing connection limit (a feature
89 // provided by http.Transport) when concurrent calls are
90 // multiplexed on a single http2 connection.
91 requestLimiter requestLimiter
96 // InsecureHTTPClient is the default http.Client used by a Client with
97 // Insecure==true and Client==nil.
98 var InsecureHTTPClient = &http.Client{
99 Transport: &http.Transport{
100 TLSClientConfig: &tls.Config{
101 InsecureSkipVerify: true}}}
103 // DefaultSecureClient is the default http.Client used by a Client otherwise.
104 var DefaultSecureClient = &http.Client{}
106 // NewClientFromConfig creates a new Client that uses the endpoints in
107 // the given cluster.
109 // AuthToken is left empty for the caller to populate.
110 func NewClientFromConfig(cluster *Cluster) (*Client, error) {
111 ctrlURL := cluster.Services.Controller.ExternalURL
112 if ctrlURL.Host == "" {
113 return nil, fmt.Errorf("no host in config Services.Controller.ExternalURL: %v", ctrlURL)
116 if srvaddr := os.Getenv("ARVADOS_SERVER_ADDRESS"); srvaddr != "" {
117 // When this client is used to make a request to
118 // https://{ctrlhost}:port/ (any port), it dials the
119 // indicated port on ARVADOS_SERVER_ADDRESS instead.
121 // This is invoked by arvados-server boot to ensure
122 // that server->server traffic (e.g.,
123 // keepproxy->controller) only hits local interfaces,
124 // even if the Controller.ExternalURL host is a load
125 // balancer / gateway and not a local interface
126 // address (e.g., when running on a cloud VM).
128 // This avoids unnecessary delay/cost of routing
129 // external traffic, and also allows controller to
130 // recognize other services as internal clients based
131 // on the connection source address.
132 divertedHost := (*url.URL)(&cluster.Services.Controller.ExternalURL).Hostname()
133 var dialer net.Dialer
135 Transport: &http.Transport{
136 TLSClientConfig: &tls.Config{InsecureSkipVerify: cluster.TLS.Insecure},
137 DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
138 host, port, err := net.SplitHostPort(addr)
139 if err == nil && network == "tcp" && host == divertedHost {
140 addr = net.JoinHostPort(srvaddr, port)
142 return dialer.DialContext(ctx, network, addr)
149 Scheme: ctrlURL.Scheme,
150 APIHost: ctrlURL.Host,
151 Insecure: cluster.TLS.Insecure,
152 Timeout: 5 * time.Minute,
153 requestLimiter: requestLimiter{maxlimit: int64(cluster.API.MaxConcurrentRequests / 4)},
157 // NewClientFromEnv creates a new Client that uses the default HTTP
158 // client, and loads API endpoint and credentials from ARVADOS_*
159 // environment variables (if set) and
160 // $HOME/.config/arvados/settings.conf (if readable).
162 // If a config exists in both locations, the environment variable is
165 // If there is an error (other than ENOENT) reading settings.conf,
166 // NewClientFromEnv logs the error to log.Default(), then proceeds as
167 // if settings.conf did not exist.
169 // Space characters are trimmed when reading the settings file, so
170 // these are equivalent:
172 // ARVADOS_API_HOST=localhost\n
173 // ARVADOS_API_HOST=localhost\r\n
174 // ARVADOS_API_HOST = localhost \n
175 // \tARVADOS_API_HOST = localhost\n
176 func NewClientFromEnv() *Client {
177 vars := map[string]string{}
178 home := os.Getenv("HOME")
179 conffile := home + "/.config/arvados/settings.conf"
181 // no $HOME => just use env vars
182 } else if settings, err := os.ReadFile(conffile); errors.Is(err, fs.ErrNotExist) {
183 // no config file => just use env vars
184 } else if err != nil {
185 // config file unreadable => log message, then use env vars
186 log.Printf("continuing without loading %s: %s", conffile, err)
188 for _, line := range bytes.Split(settings, []byte{'\n'}) {
189 kv := bytes.SplitN(line, []byte{'='}, 2)
190 k := string(bytes.TrimSpace(kv[0]))
191 if len(kv) != 2 || !strings.HasPrefix(k, "ARVADOS_") {
192 // Same behavior as python sdk:
193 // silently skip leading # (comments),
194 // blank lines, typos, and non-Arvados
198 vars[k] = string(bytes.TrimSpace(kv[1]))
201 for _, env := range os.Environ() {
202 if !strings.HasPrefix(env, "ARVADOS_") {
205 kv := strings.SplitN(env, "=", 2)
211 for _, s := range strings.Split(vars["ARVADOS_KEEP_SERVICES"], " ") {
214 } else if u, err := url.Parse(s); err != nil {
215 log.Printf("ARVADOS_KEEP_SERVICES: %q: %s", s, err)
216 } else if !u.IsAbs() {
217 log.Printf("ARVADOS_KEEP_SERVICES: %q: not an absolute URI", s)
219 svcs = append(svcs, s)
223 if s := strings.ToLower(vars["ARVADOS_API_HOST_INSECURE"]); s == "1" || s == "yes" || s == "true" {
228 APIHost: vars["ARVADOS_API_HOST"],
229 AuthToken: vars["ARVADOS_API_TOKEN"],
231 KeepServiceURIs: svcs,
232 Timeout: 5 * time.Minute,
237 var reqIDGen = httpserver.IDGenerator{Prefix: "req-"}
239 var nopCancelFunc context.CancelFunc = func() {}
241 var reqErrorRe = regexp.MustCompile(`net/http: invalid header `)
243 // Do augments (*http.Client)Do(): adds Authorization and X-Request-Id
244 // headers, delays in order to comply with rate-limiting restrictions,
245 // and retries failed requests when appropriate.
246 func (c *Client) Do(req *http.Request) (*http.Response, error) {
248 if auth, _ := ctx.Value(contextKeyAuthorization{}).(string); auth != "" {
249 req.Header.Add("Authorization", auth)
250 } else if c.AuthToken != "" {
251 req.Header.Add("Authorization", "OAuth2 "+c.AuthToken)
254 if req.Header.Get("X-Request-Id") == "" {
256 if ctxreqid, _ := ctx.Value(contextKeyRequestID{}).(string); ctxreqid != "" {
258 } else if c.defaultRequestID != "" {
259 reqid = c.defaultRequestID
261 reqid = reqIDGen.Next()
263 if req.Header == nil {
264 req.Header = http.Header{"X-Request-Id": {reqid}}
266 req.Header.Set("X-Request-Id", reqid)
270 rreq, err := retryablehttp.FromRequest(req)
275 cancel := nopCancelFunc
276 var lastResp *http.Response
277 var lastRespBody io.ReadCloser
279 var checkRetryCalled int
281 rclient := retryablehttp.NewClient()
282 rclient.HTTPClient = c.httpClient()
283 rclient.Backoff = exponentialBackoff
285 rclient.RetryWaitMax = c.Timeout / 10
286 rclient.RetryMax = 32
287 ctx, cancel = context.WithDeadline(ctx, time.Now().Add(c.Timeout))
288 rreq = rreq.WithContext(ctx)
292 rclient.CheckRetry = func(ctx context.Context, resp *http.Response, respErr error) (bool, error) {
294 if c.requestLimiter.Report(resp, respErr) {
295 c.last503.Store(time.Now())
300 if respErr != nil && reqErrorRe.MatchString(respErr.Error()) {
303 retrying, err := retryablehttp.DefaultRetryPolicy(ctx, resp, respErr)
305 lastResp, lastRespBody, lastErr = resp, nil, respErr
307 // Save the response and body so we
308 // can return it instead of "deadline
309 // exceeded". retryablehttp.Client
310 // will drain and discard resp.body,
311 // so we need to stash it separately.
312 buf, err := ioutil.ReadAll(resp.Body)
314 lastRespBody = io.NopCloser(bytes.NewReader(buf))
316 lastResp, lastErr = nil, err
324 c.requestLimiter.Acquire(ctx)
325 if ctx.Err() != nil {
326 c.requestLimiter.Release()
328 return nil, ctx.Err()
330 resp, err := rclient.Do(rreq)
331 if (errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled)) && (lastResp != nil || lastErr != nil) {
334 if checkRetryCalled > 0 && err != nil {
335 // Mimic retryablehttp's "giving up after X
336 // attempts" message, even if we gave up
337 // because of time rather than maxretries.
338 err = fmt.Errorf("%s %s giving up after %d attempt(s): %w", req.Method, req.URL.String(), checkRetryCalled, err)
341 resp.Body = lastRespBody
345 c.requestLimiter.Release()
349 // We need to call cancel() eventually, but we can't use
350 // "defer cancel()" because the context has to stay alive
351 // until the caller has finished reading the response body.
352 resp.Body = cancelOnClose{
353 ReadCloser: resp.Body,
355 c.requestLimiter.Release()
362 // Last503 returns the time of the most recent HTTP 503 (Service
363 // Unavailable) response. Zero time indicates never.
364 func (c *Client) Last503() time.Time {
365 t, _ := c.last503.Load().(time.Time)
369 // cancelOnClose calls a provided CancelFunc when its wrapped
370 // ReadCloser's Close() method is called.
371 type cancelOnClose struct {
373 cancel context.CancelFunc
376 func (coc cancelOnClose) Close() error {
377 err := coc.ReadCloser.Close()
382 func isRedirectStatus(code int) bool {
384 case http.StatusMovedPermanently, http.StatusFound, http.StatusSeeOther, http.StatusTemporaryRedirect, http.StatusPermanentRedirect:
391 const minExponentialBackoffBase = time.Second
393 // Implements retryablehttp.Backoff using the server-provided
394 // Retry-After header if available, otherwise nearly-full jitter
395 // exponential backoff (similar to
396 // https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/),
397 // in all cases respecting the provided min and max.
398 func exponentialBackoff(min, max time.Duration, attemptNum int, resp *http.Response) time.Duration {
399 if attemptNum > 0 && min < minExponentialBackoffBase {
400 min = minExponentialBackoffBase
403 if resp != nil && (resp.StatusCode == http.StatusTooManyRequests || resp.StatusCode == http.StatusServiceUnavailable) {
404 if s := resp.Header.Get("Retry-After"); s != "" {
405 if sleep, err := strconv.ParseInt(s, 10, 64); err == nil {
406 t = time.Second * time.Duration(sleep)
407 } else if stamp, err := time.Parse(time.RFC1123, s); err == nil {
408 t = stamp.Sub(time.Now())
413 jitter := mathrand.New(mathrand.NewSource(int64(time.Now().Nanosecond()))).Float64()
414 t = min + time.Duration((math.Pow(2, float64(attemptNum))*float64(min)-float64(min))*jitter)
425 // DoAndDecode performs req and unmarshals the response (which must be
426 // JSON) into dst. Use this instead of RequestAndDecode if you need
427 // more control of the http.Request object.
429 // If the response status indicates an HTTP redirect, the Location
430 // header value is unmarshalled to dst as a RedirectLocation
432 func (c *Client) DoAndDecode(dst interface{}, req *http.Request) error {
433 resp, err := c.Do(req)
437 defer resp.Body.Close()
438 buf, err := ioutil.ReadAll(resp.Body)
443 case resp.StatusCode == http.StatusNoContent:
445 case resp.StatusCode == http.StatusOK && dst == nil:
447 case resp.StatusCode == http.StatusOK:
448 return json.Unmarshal(buf, dst)
450 // If the caller uses a client with a custom CheckRedirect
451 // func, Do() might return the 3xx response instead of
453 case isRedirectStatus(resp.StatusCode) && dst == nil:
455 case isRedirectStatus(resp.StatusCode):
456 // Copy the redirect target URL to dst.RedirectLocation.
457 buf, err := json.Marshal(map[string]string{"redirect_location": resp.Header.Get("Location")})
461 return json.Unmarshal(buf, dst)
464 return newTransactionError(req, resp, buf)
468 // Convert an arbitrary struct to url.Values. For example,
470 // Foo{Bar: []int{1,2,3}, Baz: "waz"}
474 // url.Values{`bar`:`{"a":[1,2,3]}`,`Baz`:`waz`}
476 // params itself is returned if it is already an url.Values.
477 func anythingToValues(params interface{}) (url.Values, error) {
478 if v, ok := params.(url.Values); ok {
481 // TODO: Do this more efficiently, possibly using
482 // json.Decode/Encode, so the whole thing doesn't have to get
483 // encoded, decoded, and re-encoded.
484 j, err := json.Marshal(params)
488 var generic map[string]interface{}
489 dec := json.NewDecoder(bytes.NewBuffer(j))
491 err = dec.Decode(&generic)
495 urlValues := url.Values{}
496 for k, v := range generic {
497 if v, ok := v.(string); ok {
501 if v, ok := v.(json.Number); ok {
502 urlValues.Set(k, v.String())
505 if v, ok := v.(bool); ok {
507 urlValues.Set(k, "true")
509 // "foo=false", "foo=0", and "foo="
510 // are all taken as true strings, so
511 // don't send false values at all --
512 // rely on the default being false.
516 j, err := json.Marshal(v)
520 if bytes.Equal(j, []byte("null")) {
521 // don't add it to urlValues at all
524 urlValues.Set(k, string(j))
526 return urlValues, nil
529 // RequestAndDecode performs an API request and unmarshals the
530 // response (which must be JSON) into dst. Method and body arguments
531 // are the same as for http.NewRequest(). The given path is added to
532 // the server's scheme/host/port to form the request URL. The given
533 // params are passed via POST form or query string.
535 // path must not contain a query string.
536 func (c *Client) RequestAndDecode(dst interface{}, method, path string, body io.Reader, params interface{}) error {
537 return c.RequestAndDecodeContext(context.Background(), dst, method, path, body, params)
540 // RequestAndDecodeContext does the same as RequestAndDecode, but with a context
541 func (c *Client) RequestAndDecodeContext(ctx context.Context, dst interface{}, method, path string, body io.Reader, params interface{}) error {
542 if body, ok := body.(io.Closer); ok {
543 // Ensure body is closed even if we error out early
548 return errors.New("ARVADOS_API_HOST and/or ARVADOS_API_TOKEN environment variables are not set")
550 return errors.New("arvados.Client cannot perform request: APIHost is not set")
552 urlString := c.apiURL(path)
553 urlValues, err := anythingToValues(params)
558 if urlValues == nil {
559 urlValues = url.Values{}
561 urlValues["select"] = []string{`["uuid"]`}
563 if urlValues == nil {
565 } else if body != nil || ((method == "GET" || method == "HEAD") && len(urlValues.Encode()) < 1000) {
566 // Send params in query part of URL
567 u, err := url.Parse(urlString)
571 u.RawQuery = urlValues.Encode()
572 urlString = u.String()
574 body = strings.NewReader(urlValues.Encode())
576 req, err := http.NewRequest(method, urlString, body)
580 if (method == "GET" || method == "HEAD") && body != nil {
581 req.Header.Set("X-Http-Method-Override", method)
584 req = req.WithContext(ctx)
585 req.Header.Set("Content-type", "application/x-www-form-urlencoded")
586 for k, v := range c.SendHeader {
589 return c.DoAndDecode(dst, req)
592 type resource interface {
593 resourceName() string
596 // UpdateBody returns an io.Reader suitable for use as an http.Request
597 // Body for a create or update API call.
598 func (c *Client) UpdateBody(rsc resource) io.Reader {
599 j, err := json.Marshal(rsc)
601 // Return a reader that returns errors.
603 w.CloseWithError(err)
606 v := url.Values{rsc.resourceName(): {string(j)}}
607 return bytes.NewBufferString(v.Encode())
610 // WithRequestID returns a new shallow copy of c that sends the given
611 // X-Request-Id value (instead of a new randomly generated one) with
612 // each subsequent request that doesn't provide its own via context or
614 func (c *Client) WithRequestID(reqid string) *Client {
616 cc.defaultRequestID = reqid
620 func (c *Client) httpClient() *http.Client {
622 case c.Client != nil:
625 return InsecureHTTPClient
627 return DefaultSecureClient
631 func (c *Client) apiURL(path string) string {
636 // Double-slash in URLs tend to cause subtle hidden problems
637 // (e.g., they can behave differently when a load balancer is
638 // in the picture). Here we ensure exactly one "/" regardless
639 // of whether the given APIHost or path has a superfluous one.
640 return scheme + "://" + strings.TrimSuffix(c.APIHost, "/") + "/" + strings.TrimPrefix(path, "/")
643 // DiscoveryDocument is the Arvados server's description of itself.
644 type DiscoveryDocument struct {
645 BasePath string `json:"basePath"`
646 DefaultCollectionReplication int `json:"defaultCollectionReplication"`
647 BlobSignatureTTL int64 `json:"blobSignatureTtl"`
648 GitURL string `json:"gitUrl"`
649 Schemas map[string]Schema `json:"schemas"`
650 Resources map[string]Resource `json:"resources"`
651 Revision string `json:"revision"`
654 type Resource struct {
655 Methods map[string]ResourceMethod `json:"methods"`
658 type ResourceMethod struct {
659 HTTPMethod string `json:"httpMethod"`
660 Path string `json:"path"`
661 Response MethodResponse `json:"response"`
664 type MethodResponse struct {
665 Ref string `json:"$ref"`
669 UUIDPrefix string `json:"uuidPrefix"`
672 // DiscoveryDocument returns a *DiscoveryDocument. The returned object
673 // should not be modified: the same object may be returned by
675 func (c *Client) DiscoveryDocument() (*DiscoveryDocument, error) {
679 var dd DiscoveryDocument
680 err := c.RequestAndDecode(&dd, "GET", "discovery/v1/apis/arvados/v1/rest", nil, nil)
688 var pdhRegexp = regexp.MustCompile(`^[0-9a-f]{32}\+\d+$`)
690 func (c *Client) modelForUUID(dd *DiscoveryDocument, uuid string) (string, error) {
691 if pdhRegexp.MatchString(uuid) {
692 return "Collection", nil
695 return "", fmt.Errorf("invalid UUID: %q", uuid)
699 for m, s := range dd.Schemas {
700 if s.UUIDPrefix == infix {
706 return "", fmt.Errorf("unrecognized type portion %q in UUID %q", infix, uuid)
711 func (c *Client) KindForUUID(uuid string) (string, error) {
712 dd, err := c.DiscoveryDocument()
716 model, err := c.modelForUUID(dd, uuid)
720 return "arvados#" + strings.ToLower(model[:1]) + model[1:], nil
723 func (c *Client) PathForUUID(method, uuid string) (string, error) {
724 dd, err := c.DiscoveryDocument()
728 model, err := c.modelForUUID(dd, uuid)
733 for r, rsc := range dd.Resources {
734 if rsc.Methods["get"].Response.Ref == model {
740 return "", fmt.Errorf("no resource for model: %q", model)
742 m, ok := dd.Resources[resource].Methods[method]
744 return "", fmt.Errorf("no method %q for resource %q", method, resource)
746 path := dd.BasePath + strings.Replace(m.Path, "{uuid}", uuid, -1)
753 var maxUUIDInt = (&big.Int{}).Exp(big.NewInt(36), big.NewInt(15), nil)
755 func RandomUUID(clusterID, infix string) string {
756 n, err := rand.Int(rand.Reader, maxUUIDInt)
764 return clusterID + "-" + infix + "-" + nstr