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 // Do augments (*http.Client)Do(): adds Authorization and X-Request-Id
242 // headers, delays in order to comply with rate-limiting restrictions,
243 // and retries failed requests when appropriate.
244 func (c *Client) Do(req *http.Request) (*http.Response, error) {
246 if auth, _ := ctx.Value(contextKeyAuthorization{}).(string); auth != "" {
247 req.Header.Add("Authorization", auth)
248 } else if c.AuthToken != "" {
249 req.Header.Add("Authorization", "OAuth2 "+c.AuthToken)
252 if req.Header.Get("X-Request-Id") == "" {
254 if ctxreqid, _ := ctx.Value(contextKeyRequestID{}).(string); ctxreqid != "" {
256 } else if c.defaultRequestID != "" {
257 reqid = c.defaultRequestID
259 reqid = reqIDGen.Next()
261 if req.Header == nil {
262 req.Header = http.Header{"X-Request-Id": {reqid}}
264 req.Header.Set("X-Request-Id", reqid)
268 rreq, err := retryablehttp.FromRequest(req)
273 cancel := nopCancelFunc
274 var lastResp *http.Response
275 var lastRespBody io.ReadCloser
278 rclient := retryablehttp.NewClient()
279 rclient.HTTPClient = c.httpClient()
280 rclient.Backoff = exponentialBackoff
282 rclient.RetryWaitMax = c.Timeout / 10
283 rclient.RetryMax = 32
284 ctx, cancel = context.WithDeadline(ctx, time.Now().Add(c.Timeout))
285 rreq = rreq.WithContext(ctx)
289 rclient.CheckRetry = func(ctx context.Context, resp *http.Response, respErr error) (bool, error) {
290 if c.requestLimiter.Report(resp, respErr) {
291 c.last503.Store(time.Now())
296 retrying, err := retryablehttp.DefaultRetryPolicy(ctx, resp, respErr)
298 lastResp, lastRespBody, lastErr = resp, nil, respErr
300 // Save the response and body so we
301 // can return it instead of "deadline
302 // exceeded". retryablehttp.Client
303 // will drain and discard resp.body,
304 // so we need to stash it separately.
305 buf, err := ioutil.ReadAll(resp.Body)
307 lastRespBody = io.NopCloser(bytes.NewReader(buf))
309 lastResp, lastErr = nil, err
317 c.requestLimiter.Acquire(ctx)
318 if ctx.Err() != nil {
319 c.requestLimiter.Release()
321 return nil, ctx.Err()
323 resp, err := rclient.Do(rreq)
324 if (errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled)) && (lastResp != nil || lastErr != nil) {
325 resp, err = lastResp, lastErr
327 resp.Body = lastRespBody
331 c.requestLimiter.Release()
335 // We need to call cancel() eventually, but we can't use
336 // "defer cancel()" because the context has to stay alive
337 // until the caller has finished reading the response body.
338 resp.Body = cancelOnClose{
339 ReadCloser: resp.Body,
341 c.requestLimiter.Release()
348 // Last503 returns the time of the most recent HTTP 503 (Service
349 // Unavailable) response. Zero time indicates never.
350 func (c *Client) Last503() time.Time {
351 t, _ := c.last503.Load().(time.Time)
355 // cancelOnClose calls a provided CancelFunc when its wrapped
356 // ReadCloser's Close() method is called.
357 type cancelOnClose struct {
359 cancel context.CancelFunc
362 func (coc cancelOnClose) Close() error {
363 err := coc.ReadCloser.Close()
368 func isRedirectStatus(code int) bool {
370 case http.StatusMovedPermanently, http.StatusFound, http.StatusSeeOther, http.StatusTemporaryRedirect, http.StatusPermanentRedirect:
377 const minExponentialBackoffBase = time.Second
379 // Implements retryablehttp.Backoff using the server-provided
380 // Retry-After header if available, otherwise nearly-full jitter
381 // exponential backoff (similar to
382 // https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/),
383 // in all cases respecting the provided min and max.
384 func exponentialBackoff(min, max time.Duration, attemptNum int, resp *http.Response) time.Duration {
385 if attemptNum > 0 && min < minExponentialBackoffBase {
386 min = minExponentialBackoffBase
389 if resp != nil && (resp.StatusCode == http.StatusTooManyRequests || resp.StatusCode == http.StatusServiceUnavailable) {
390 if s := resp.Header.Get("Retry-After"); s != "" {
391 if sleep, err := strconv.ParseInt(s, 10, 64); err == nil {
392 t = time.Second * time.Duration(sleep)
393 } else if stamp, err := time.Parse(time.RFC1123, s); err == nil {
394 t = stamp.Sub(time.Now())
399 jitter := mathrand.New(mathrand.NewSource(int64(time.Now().Nanosecond()))).Float64()
400 t = min + time.Duration((math.Pow(2, float64(attemptNum))*float64(min)-float64(min))*jitter)
411 // DoAndDecode performs req and unmarshals the response (which must be
412 // JSON) into dst. Use this instead of RequestAndDecode if you need
413 // more control of the http.Request object.
415 // If the response status indicates an HTTP redirect, the Location
416 // header value is unmarshalled to dst as a RedirectLocation
418 func (c *Client) DoAndDecode(dst interface{}, req *http.Request) error {
419 resp, err := c.Do(req)
423 defer resp.Body.Close()
424 buf, err := ioutil.ReadAll(resp.Body)
429 case resp.StatusCode == http.StatusNoContent:
431 case resp.StatusCode == http.StatusOK && dst == nil:
433 case resp.StatusCode == http.StatusOK:
434 return json.Unmarshal(buf, dst)
436 // If the caller uses a client with a custom CheckRedirect
437 // func, Do() might return the 3xx response instead of
439 case isRedirectStatus(resp.StatusCode) && dst == nil:
441 case isRedirectStatus(resp.StatusCode):
442 // Copy the redirect target URL to dst.RedirectLocation.
443 buf, err := json.Marshal(map[string]string{"redirect_location": resp.Header.Get("Location")})
447 return json.Unmarshal(buf, dst)
450 return newTransactionError(req, resp, buf)
454 // Convert an arbitrary struct to url.Values. For example,
456 // Foo{Bar: []int{1,2,3}, Baz: "waz"}
460 // url.Values{`bar`:`{"a":[1,2,3]}`,`Baz`:`waz`}
462 // params itself is returned if it is already an url.Values.
463 func anythingToValues(params interface{}) (url.Values, error) {
464 if v, ok := params.(url.Values); ok {
467 // TODO: Do this more efficiently, possibly using
468 // json.Decode/Encode, so the whole thing doesn't have to get
469 // encoded, decoded, and re-encoded.
470 j, err := json.Marshal(params)
474 var generic map[string]interface{}
475 dec := json.NewDecoder(bytes.NewBuffer(j))
477 err = dec.Decode(&generic)
481 urlValues := url.Values{}
482 for k, v := range generic {
483 if v, ok := v.(string); ok {
487 if v, ok := v.(json.Number); ok {
488 urlValues.Set(k, v.String())
491 if v, ok := v.(bool); ok {
493 urlValues.Set(k, "true")
495 // "foo=false", "foo=0", and "foo="
496 // are all taken as true strings, so
497 // don't send false values at all --
498 // rely on the default being false.
502 j, err := json.Marshal(v)
506 if bytes.Equal(j, []byte("null")) {
507 // don't add it to urlValues at all
510 urlValues.Set(k, string(j))
512 return urlValues, nil
515 // RequestAndDecode performs an API request and unmarshals the
516 // response (which must be JSON) into dst. Method and body arguments
517 // are the same as for http.NewRequest(). The given path is added to
518 // the server's scheme/host/port to form the request URL. The given
519 // params are passed via POST form or query string.
521 // path must not contain a query string.
522 func (c *Client) RequestAndDecode(dst interface{}, method, path string, body io.Reader, params interface{}) error {
523 return c.RequestAndDecodeContext(context.Background(), dst, method, path, body, params)
526 // RequestAndDecodeContext does the same as RequestAndDecode, but with a context
527 func (c *Client) RequestAndDecodeContext(ctx context.Context, dst interface{}, method, path string, body io.Reader, params interface{}) error {
528 if body, ok := body.(io.Closer); ok {
529 // Ensure body is closed even if we error out early
534 return errors.New("ARVADOS_API_HOST and/or ARVADOS_API_TOKEN environment variables are not set")
536 return errors.New("arvados.Client cannot perform request: APIHost is not set")
538 urlString := c.apiURL(path)
539 urlValues, err := anythingToValues(params)
544 if urlValues == nil {
545 urlValues = url.Values{}
547 urlValues["select"] = []string{`["uuid"]`}
549 if urlValues == nil {
551 } else if body != nil || ((method == "GET" || method == "HEAD") && len(urlValues.Encode()) < 1000) {
552 // Send params in query part of URL
553 u, err := url.Parse(urlString)
557 u.RawQuery = urlValues.Encode()
558 urlString = u.String()
560 body = strings.NewReader(urlValues.Encode())
562 req, err := http.NewRequest(method, urlString, body)
566 if (method == "GET" || method == "HEAD") && body != nil {
567 req.Header.Set("X-Http-Method-Override", method)
570 req = req.WithContext(ctx)
571 req.Header.Set("Content-type", "application/x-www-form-urlencoded")
572 for k, v := range c.SendHeader {
575 return c.DoAndDecode(dst, req)
578 type resource interface {
579 resourceName() string
582 // UpdateBody returns an io.Reader suitable for use as an http.Request
583 // Body for a create or update API call.
584 func (c *Client) UpdateBody(rsc resource) io.Reader {
585 j, err := json.Marshal(rsc)
587 // Return a reader that returns errors.
589 w.CloseWithError(err)
592 v := url.Values{rsc.resourceName(): {string(j)}}
593 return bytes.NewBufferString(v.Encode())
596 // WithRequestID returns a new shallow copy of c that sends the given
597 // X-Request-Id value (instead of a new randomly generated one) with
598 // each subsequent request that doesn't provide its own via context or
600 func (c *Client) WithRequestID(reqid string) *Client {
602 cc.defaultRequestID = reqid
606 func (c *Client) httpClient() *http.Client {
608 case c.Client != nil:
611 return InsecureHTTPClient
613 return DefaultSecureClient
617 func (c *Client) apiURL(path string) string {
622 return scheme + "://" + c.APIHost + "/" + path
625 // DiscoveryDocument is the Arvados server's description of itself.
626 type DiscoveryDocument struct {
627 BasePath string `json:"basePath"`
628 DefaultCollectionReplication int `json:"defaultCollectionReplication"`
629 BlobSignatureTTL int64 `json:"blobSignatureTtl"`
630 GitURL string `json:"gitUrl"`
631 Schemas map[string]Schema `json:"schemas"`
632 Resources map[string]Resource `json:"resources"`
635 type Resource struct {
636 Methods map[string]ResourceMethod `json:"methods"`
639 type ResourceMethod struct {
640 HTTPMethod string `json:"httpMethod"`
641 Path string `json:"path"`
642 Response MethodResponse `json:"response"`
645 type MethodResponse struct {
646 Ref string `json:"$ref"`
650 UUIDPrefix string `json:"uuidPrefix"`
653 // DiscoveryDocument returns a *DiscoveryDocument. The returned object
654 // should not be modified: the same object may be returned by
656 func (c *Client) DiscoveryDocument() (*DiscoveryDocument, error) {
660 var dd DiscoveryDocument
661 err := c.RequestAndDecode(&dd, "GET", "discovery/v1/apis/arvados/v1/rest", nil, nil)
669 var pdhRegexp = regexp.MustCompile(`^[0-9a-f]{32}\+\d+$`)
671 func (c *Client) modelForUUID(dd *DiscoveryDocument, uuid string) (string, error) {
672 if pdhRegexp.MatchString(uuid) {
673 return "Collection", nil
676 return "", fmt.Errorf("invalid UUID: %q", uuid)
680 for m, s := range dd.Schemas {
681 if s.UUIDPrefix == infix {
687 return "", fmt.Errorf("unrecognized type portion %q in UUID %q", infix, uuid)
692 func (c *Client) KindForUUID(uuid string) (string, error) {
693 dd, err := c.DiscoveryDocument()
697 model, err := c.modelForUUID(dd, uuid)
701 return "arvados#" + strings.ToLower(model[:1]) + model[1:], nil
704 func (c *Client) PathForUUID(method, uuid string) (string, error) {
705 dd, err := c.DiscoveryDocument()
709 model, err := c.modelForUUID(dd, uuid)
714 for r, rsc := range dd.Resources {
715 if rsc.Methods["get"].Response.Ref == model {
721 return "", fmt.Errorf("no resource for model: %q", model)
723 m, ok := dd.Resources[resource].Methods[method]
725 return "", fmt.Errorf("no method %q for resource %q", method, resource)
727 path := dd.BasePath + strings.Replace(m.Path, "{uuid}", uuid, -1)
734 var maxUUIDInt = (&big.Int{}).Exp(big.NewInt(36), big.NewInt(15), nil)
736 func RandomUUID(clusterID, infix string) string {
737 n, err := rand.Int(rand.Reader, maxUUIDInt)
745 return clusterID + "-" + infix + "-" + nstr