1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: Apache-2.0
29 "git.arvados.org/arvados.git/sdk/go/httpserver"
32 // A Client is an HTTP client with an API endpoint and a set of
33 // Arvados credentials.
35 // It offers methods for accessing individual Arvados APIs, and
36 // methods that implement common patterns like fetching multiple pages
37 // of results using List APIs.
39 // HTTP client used to make requests. If nil,
40 // DefaultSecureClient or InsecureHTTPClient will be used.
41 Client *http.Client `json:"-"`
43 // Protocol scheme: "http", "https", or "" (https)
46 // Hostname (or host:port) of Arvados API server.
49 // User authentication token.
52 // Accept unverified certificates. This works only if the
53 // Client field is nil: otherwise, it has no effect.
56 // Override keep service discovery with a list of base
57 // URIs. (Currently there are no Client methods for
58 // discovering keep services so this is just a convenience for
59 // callers who use a Client to initialize an
60 // arvadosclient.ArvadosClient.)
61 KeepServiceURIs []string `json:",omitempty"`
63 // HTTP headers to add/override in outgoing requests.
64 SendHeader http.Header
66 // Timeout for requests. NewClientFromConfig and
67 // NewClientFromEnv return a Client with a default 5 minute
68 // timeout. To disable this timeout and rely on each
69 // http.Request's context deadline instead, set Timeout to
75 defaultRequestID string
77 // APIHost and AuthToken were loaded from ARVADOS_* env vars
78 // (used to customize "no host/token" error messages)
81 // Track/limit concurrent outgoing API calls. Note this
82 // differs from an outgoing connection limit (a feature
83 // provided by http.Transport) when concurrent calls are
84 // multiplexed on a single http2 connection.
85 requestLimiter requestLimiter
90 // InsecureHTTPClient is the default http.Client used by a Client with
91 // Insecure==true and Client==nil.
92 var InsecureHTTPClient = &http.Client{
93 Transport: &http.Transport{
94 TLSClientConfig: &tls.Config{
95 InsecureSkipVerify: true}}}
97 // DefaultSecureClient is the default http.Client used by a Client otherwise.
98 var DefaultSecureClient = &http.Client{}
100 // NewClientFromConfig creates a new Client that uses the endpoints in
101 // the given cluster.
103 // AuthToken is left empty for the caller to populate.
104 func NewClientFromConfig(cluster *Cluster) (*Client, error) {
105 ctrlURL := cluster.Services.Controller.ExternalURL
106 if ctrlURL.Host == "" {
107 return nil, fmt.Errorf("no host in config Services.Controller.ExternalURL: %v", ctrlURL)
110 if srvaddr := os.Getenv("ARVADOS_SERVER_ADDRESS"); srvaddr != "" {
111 // When this client is used to make a request to
112 // https://{ctrlhost}:port/ (any port), it dials the
113 // indicated port on ARVADOS_SERVER_ADDRESS instead.
115 // This is invoked by arvados-server boot to ensure
116 // that server->server traffic (e.g.,
117 // keepproxy->controller) only hits local interfaces,
118 // even if the Controller.ExternalURL host is a load
119 // balancer / gateway and not a local interface
120 // address (e.g., when running on a cloud VM).
122 // This avoids unnecessary delay/cost of routing
123 // external traffic, and also allows controller to
124 // recognize other services as internal clients based
125 // on the connection source address.
126 divertedHost := (*url.URL)(&cluster.Services.Controller.ExternalURL).Hostname()
127 var dialer net.Dialer
129 Transport: &http.Transport{
130 TLSClientConfig: &tls.Config{InsecureSkipVerify: cluster.TLS.Insecure},
131 DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
132 host, port, err := net.SplitHostPort(addr)
133 if err == nil && network == "tcp" && host == divertedHost {
134 addr = net.JoinHostPort(srvaddr, port)
136 return dialer.DialContext(ctx, network, addr)
143 Scheme: ctrlURL.Scheme,
144 APIHost: ctrlURL.Host,
145 Insecure: cluster.TLS.Insecure,
146 Timeout: 5 * time.Minute,
150 // NewClientFromEnv creates a new Client that uses the default HTTP
151 // client, and loads API endpoint and credentials from ARVADOS_*
152 // environment variables (if set) and
153 // $HOME/.config/arvados/settings.conf (if readable).
155 // If a config exists in both locations, the environment variable is
158 // If there is an error (other than ENOENT) reading settings.conf,
159 // NewClientFromEnv logs the error to log.Default(), then proceeds as
160 // if settings.conf did not exist.
162 // Space characters are trimmed when reading the settings file, so
163 // these are equivalent:
165 // ARVADOS_API_HOST=localhost\n
166 // ARVADOS_API_HOST=localhost\r\n
167 // ARVADOS_API_HOST = localhost \n
168 // \tARVADOS_API_HOST = localhost\n
169 func NewClientFromEnv() *Client {
170 vars := map[string]string{}
171 home := os.Getenv("HOME")
172 conffile := home + "/.config/arvados/settings.conf"
174 // no $HOME => just use env vars
175 } else if settings, err := os.ReadFile(conffile); errors.Is(err, fs.ErrNotExist) {
176 // no config file => just use env vars
177 } else if err != nil {
178 // config file unreadable => log message, then use env vars
179 log.Printf("continuing without loading %s: %s", conffile, err)
181 for _, line := range bytes.Split(settings, []byte{'\n'}) {
182 kv := bytes.SplitN(line, []byte{'='}, 2)
183 k := string(bytes.TrimSpace(kv[0]))
184 if len(kv) != 2 || !strings.HasPrefix(k, "ARVADOS_") {
185 // Same behavior as python sdk:
186 // silently skip leading # (comments),
187 // blank lines, typos, and non-Arvados
191 vars[k] = string(bytes.TrimSpace(kv[1]))
194 for _, env := range os.Environ() {
195 if !strings.HasPrefix(env, "ARVADOS_") {
198 kv := strings.SplitN(env, "=", 2)
204 for _, s := range strings.Split(vars["ARVADOS_KEEP_SERVICES"], " ") {
207 } else if u, err := url.Parse(s); err != nil {
208 log.Printf("ARVADOS_KEEP_SERVICES: %q: %s", s, err)
209 } else if !u.IsAbs() {
210 log.Printf("ARVADOS_KEEP_SERVICES: %q: not an absolute URI", s)
212 svcs = append(svcs, s)
216 if s := strings.ToLower(vars["ARVADOS_API_HOST_INSECURE"]); s == "1" || s == "yes" || s == "true" {
221 APIHost: vars["ARVADOS_API_HOST"],
222 AuthToken: vars["ARVADOS_API_TOKEN"],
224 KeepServiceURIs: svcs,
225 Timeout: 5 * time.Minute,
230 var reqIDGen = httpserver.IDGenerator{Prefix: "req-"}
232 // Do adds Authorization and X-Request-Id headers, delays in order to
233 // comply with rate-limiting restrictions, and then calls
234 // (*http.Client)Do().
235 func (c *Client) Do(req *http.Request) (*http.Response, error) {
237 if auth, _ := ctx.Value(contextKeyAuthorization{}).(string); auth != "" {
238 req.Header.Add("Authorization", auth)
239 } else if c.AuthToken != "" {
240 req.Header.Add("Authorization", "OAuth2 "+c.AuthToken)
243 if req.Header.Get("X-Request-Id") == "" {
245 if ctxreqid, _ := ctx.Value(contextKeyRequestID{}).(string); ctxreqid != "" {
247 } else if c.defaultRequestID != "" {
248 reqid = c.defaultRequestID
250 reqid = reqIDGen.Next()
252 if req.Header == nil {
253 req.Header = http.Header{"X-Request-Id": {reqid}}
255 req.Header.Set("X-Request-Id", reqid)
258 var cancel context.CancelFunc
260 ctx, cancel = context.WithDeadline(ctx, time.Now().Add(c.Timeout))
261 req = req.WithContext(ctx)
263 cancel = context.CancelFunc(func() {})
266 c.requestLimiter.Acquire(ctx)
267 if ctx.Err() != nil {
268 c.requestLimiter.Release()
269 return nil, ctx.Err()
272 // Attach Release() to cancel func, see cancelOnClose below.
275 c.requestLimiter.Release()
279 resp, err := c.httpClient().Do(req)
280 if c.requestLimiter.Report(resp, err) {
281 c.last503.Store(time.Now())
284 // We need to call cancel() eventually, but we can't
285 // use "defer cancel()" because the context has to
286 // stay alive until the caller has finished reading
287 // the response body.
288 resp.Body = cancelOnClose{ReadCloser: resp.Body, cancel: cancel}
295 // Last503 returns the time of the most recent HTTP 503 (Service
296 // Unavailable) response. Zero time indicates never.
297 func (c *Client) Last503() time.Time {
298 t, _ := c.last503.Load().(time.Time)
302 // cancelOnClose calls a provided CancelFunc when its wrapped
303 // ReadCloser's Close() method is called.
304 type cancelOnClose struct {
306 cancel context.CancelFunc
309 func (coc cancelOnClose) Close() error {
310 err := coc.ReadCloser.Close()
315 func isRedirectStatus(code int) bool {
317 case http.StatusMovedPermanently, http.StatusFound, http.StatusSeeOther, http.StatusTemporaryRedirect, http.StatusPermanentRedirect:
324 // DoAndDecode performs req and unmarshals the response (which must be
325 // JSON) into dst. Use this instead of RequestAndDecode if you need
326 // more control of the http.Request object.
328 // If the response status indicates an HTTP redirect, the Location
329 // header value is unmarshalled to dst as a RedirectLocation
331 func (c *Client) DoAndDecode(dst interface{}, req *http.Request) error {
332 resp, err := c.Do(req)
336 defer resp.Body.Close()
337 buf, err := ioutil.ReadAll(resp.Body)
342 case resp.StatusCode == http.StatusNoContent:
344 case resp.StatusCode == http.StatusOK && dst == nil:
346 case resp.StatusCode == http.StatusOK:
347 return json.Unmarshal(buf, dst)
349 // If the caller uses a client with a custom CheckRedirect
350 // func, Do() might return the 3xx response instead of
352 case isRedirectStatus(resp.StatusCode) && dst == nil:
354 case isRedirectStatus(resp.StatusCode):
355 // Copy the redirect target URL to dst.RedirectLocation.
356 buf, err := json.Marshal(map[string]string{"redirect_location": resp.Header.Get("Location")})
360 return json.Unmarshal(buf, dst)
363 return newTransactionError(req, resp, buf)
367 // Convert an arbitrary struct to url.Values. For example,
369 // Foo{Bar: []int{1,2,3}, Baz: "waz"}
373 // url.Values{`bar`:`{"a":[1,2,3]}`,`Baz`:`waz`}
375 // params itself is returned if it is already an url.Values.
376 func anythingToValues(params interface{}) (url.Values, error) {
377 if v, ok := params.(url.Values); ok {
380 // TODO: Do this more efficiently, possibly using
381 // json.Decode/Encode, so the whole thing doesn't have to get
382 // encoded, decoded, and re-encoded.
383 j, err := json.Marshal(params)
387 var generic map[string]interface{}
388 dec := json.NewDecoder(bytes.NewBuffer(j))
390 err = dec.Decode(&generic)
394 urlValues := url.Values{}
395 for k, v := range generic {
396 if v, ok := v.(string); ok {
400 if v, ok := v.(json.Number); ok {
401 urlValues.Set(k, v.String())
404 if v, ok := v.(bool); ok {
406 urlValues.Set(k, "true")
408 // "foo=false", "foo=0", and "foo="
409 // are all taken as true strings, so
410 // don't send false values at all --
411 // rely on the default being false.
415 j, err := json.Marshal(v)
419 if bytes.Equal(j, []byte("null")) {
420 // don't add it to urlValues at all
423 urlValues.Set(k, string(j))
425 return urlValues, nil
428 // RequestAndDecode performs an API request and unmarshals the
429 // response (which must be JSON) into dst. Method and body arguments
430 // are the same as for http.NewRequest(). The given path is added to
431 // the server's scheme/host/port to form the request URL. The given
432 // params are passed via POST form or query string.
434 // path must not contain a query string.
435 func (c *Client) RequestAndDecode(dst interface{}, method, path string, body io.Reader, params interface{}) error {
436 return c.RequestAndDecodeContext(context.Background(), dst, method, path, body, params)
439 // RequestAndDecodeContext does the same as RequestAndDecode, but with a context
440 func (c *Client) RequestAndDecodeContext(ctx context.Context, dst interface{}, method, path string, body io.Reader, params interface{}) error {
441 if body, ok := body.(io.Closer); ok {
442 // Ensure body is closed even if we error out early
447 return errors.New("ARVADOS_API_HOST and/or ARVADOS_API_TOKEN environment variables are not set")
449 return errors.New("arvados.Client cannot perform request: APIHost is not set")
451 urlString := c.apiURL(path)
452 urlValues, err := anythingToValues(params)
456 if urlValues == nil {
458 } else if body != nil || ((method == "GET" || method == "HEAD") && len(urlValues.Encode()) < 1000) {
459 // Send params in query part of URL
460 u, err := url.Parse(urlString)
464 u.RawQuery = urlValues.Encode()
465 urlString = u.String()
467 body = strings.NewReader(urlValues.Encode())
469 req, err := http.NewRequest(method, urlString, body)
473 if (method == "GET" || method == "HEAD") && body != nil {
474 req.Header.Set("X-Http-Method-Override", method)
477 req = req.WithContext(ctx)
478 req.Header.Set("Content-type", "application/x-www-form-urlencoded")
479 for k, v := range c.SendHeader {
482 return c.DoAndDecode(dst, req)
485 type resource interface {
486 resourceName() string
489 // UpdateBody returns an io.Reader suitable for use as an http.Request
490 // Body for a create or update API call.
491 func (c *Client) UpdateBody(rsc resource) io.Reader {
492 j, err := json.Marshal(rsc)
494 // Return a reader that returns errors.
496 w.CloseWithError(err)
499 v := url.Values{rsc.resourceName(): {string(j)}}
500 return bytes.NewBufferString(v.Encode())
503 // WithRequestID returns a new shallow copy of c that sends the given
504 // X-Request-Id value (instead of a new randomly generated one) with
505 // each subsequent request that doesn't provide its own via context or
507 func (c *Client) WithRequestID(reqid string) *Client {
509 cc.defaultRequestID = reqid
513 func (c *Client) httpClient() *http.Client {
515 case c.Client != nil:
518 return InsecureHTTPClient
520 return DefaultSecureClient
524 func (c *Client) apiURL(path string) string {
529 return scheme + "://" + c.APIHost + "/" + path
532 // DiscoveryDocument is the Arvados server's description of itself.
533 type DiscoveryDocument struct {
534 BasePath string `json:"basePath"`
535 DefaultCollectionReplication int `json:"defaultCollectionReplication"`
536 BlobSignatureTTL int64 `json:"blobSignatureTtl"`
537 GitURL string `json:"gitUrl"`
538 Schemas map[string]Schema `json:"schemas"`
539 Resources map[string]Resource `json:"resources"`
542 type Resource struct {
543 Methods map[string]ResourceMethod `json:"methods"`
546 type ResourceMethod struct {
547 HTTPMethod string `json:"httpMethod"`
548 Path string `json:"path"`
549 Response MethodResponse `json:"response"`
552 type MethodResponse struct {
553 Ref string `json:"$ref"`
557 UUIDPrefix string `json:"uuidPrefix"`
560 // DiscoveryDocument returns a *DiscoveryDocument. The returned object
561 // should not be modified: the same object may be returned by
563 func (c *Client) DiscoveryDocument() (*DiscoveryDocument, error) {
567 var dd DiscoveryDocument
568 err := c.RequestAndDecode(&dd, "GET", "discovery/v1/apis/arvados/v1/rest", nil, nil)
576 var pdhRegexp = regexp.MustCompile(`^[0-9a-f]{32}\+\d+$`)
578 func (c *Client) modelForUUID(dd *DiscoveryDocument, uuid string) (string, error) {
579 if pdhRegexp.MatchString(uuid) {
580 return "Collection", nil
583 return "", fmt.Errorf("invalid UUID: %q", uuid)
587 for m, s := range dd.Schemas {
588 if s.UUIDPrefix == infix {
594 return "", fmt.Errorf("unrecognized type portion %q in UUID %q", infix, uuid)
599 func (c *Client) KindForUUID(uuid string) (string, error) {
600 dd, err := c.DiscoveryDocument()
604 model, err := c.modelForUUID(dd, uuid)
608 return "arvados#" + strings.ToLower(model[:1]) + model[1:], nil
611 func (c *Client) PathForUUID(method, uuid string) (string, error) {
612 dd, err := c.DiscoveryDocument()
616 model, err := c.modelForUUID(dd, uuid)
621 for r, rsc := range dd.Resources {
622 if rsc.Methods["get"].Response.Ref == model {
628 return "", fmt.Errorf("no resource for model: %q", model)
630 m, ok := dd.Resources[resource].Methods[method]
632 return "", fmt.Errorf("no method %q for resource %q", method, resource)
634 path := dd.BasePath + strings.Replace(m.Path, "{uuid}", uuid, -1)
641 var maxUUIDInt = (&big.Int{}).Exp(big.NewInt(36), big.NewInt(15), nil)
643 func RandomUUID(clusterID, infix string) string {
644 n, err := rand.Int(rand.Reader, maxUUIDInt)
652 return clusterID + "-" + infix + "-" + nstr