1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: Apache-2.0
28 "git.arvados.org/arvados.git/sdk/go/httpserver"
31 // A Client is an HTTP client with an API endpoint and a set of
32 // Arvados credentials.
34 // It offers methods for accessing individual Arvados APIs, and
35 // methods that implement common patterns like fetching multiple pages
36 // of results using List APIs.
38 // HTTP client used to make requests. If nil,
39 // DefaultSecureClient or InsecureHTTPClient will be used.
40 Client *http.Client `json:"-"`
42 // Protocol scheme: "http", "https", or "" (https)
45 // Hostname (or host:port) of Arvados API server.
48 // User authentication token.
51 // Accept unverified certificates. This works only if the
52 // Client field is nil: otherwise, it has no effect.
55 // Override keep service discovery with a list of base
56 // URIs. (Currently there are no Client methods for
57 // discovering keep services so this is just a convenience for
58 // callers who use a Client to initialize an
59 // arvadosclient.ArvadosClient.)
60 KeepServiceURIs []string `json:",omitempty"`
62 // HTTP headers to add/override in outgoing requests.
63 SendHeader http.Header
65 // Timeout for requests. NewClientFromConfig and
66 // NewClientFromEnv return a Client with a default 5 minute
67 // timeout. To disable this timeout and rely on each
68 // http.Request's context deadline instead, set Timeout to
74 defaultRequestID string
76 // APIHost and AuthToken were loaded from ARVADOS_* env vars
77 // (used to customize "no host/token" error messages)
80 // Track/limit concurrent outgoing API calls. Note this
81 // differs from an outgoing connection limit (a feature
82 // provided by http.Transport) when concurrent calls are
83 // multiplexed on a single http2 connection.
87 // InsecureHTTPClient is the default http.Client used by a Client with
88 // Insecure==true and Client==nil.
89 var InsecureHTTPClient = &http.Client{
90 Transport: &http.Transport{
91 TLSClientConfig: &tls.Config{
92 InsecureSkipVerify: true}}}
94 // DefaultSecureClient is the default http.Client used by a Client otherwise.
95 var DefaultSecureClient = &http.Client{}
97 // NewClientFromConfig creates a new Client that uses the endpoints in
100 // AuthToken is left empty for the caller to populate.
101 func NewClientFromConfig(cluster *Cluster) (*Client, error) {
102 ctrlURL := cluster.Services.Controller.ExternalURL
103 if ctrlURL.Host == "" {
104 return nil, fmt.Errorf("no host in config Services.Controller.ExternalURL: %v", ctrlURL)
107 if srvaddr := os.Getenv("ARVADOS_SERVER_ADDRESS"); srvaddr != "" {
108 // When this client is used to make a request to
109 // https://{ctrlhost}:port/ (any port), it dials the
110 // indicated port on ARVADOS_SERVER_ADDRESS instead.
112 // This is invoked by arvados-server boot to ensure
113 // that server->server traffic (e.g.,
114 // keepproxy->controller) only hits local interfaces,
115 // even if the Controller.ExternalURL host is a load
116 // balancer / gateway and not a local interface
117 // address (e.g., when running on a cloud VM).
119 // This avoids unnecessary delay/cost of routing
120 // external traffic, and also allows controller to
121 // recognize other services as internal clients based
122 // on the connection source address.
123 divertedHost := (*url.URL)(&cluster.Services.Controller.ExternalURL).Hostname()
124 var dialer net.Dialer
126 Transport: &http.Transport{
127 TLSClientConfig: &tls.Config{InsecureSkipVerify: cluster.TLS.Insecure},
128 DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
129 host, port, err := net.SplitHostPort(addr)
130 if err == nil && network == "tcp" && host == divertedHost {
131 addr = net.JoinHostPort(srvaddr, port)
133 return dialer.DialContext(ctx, network, addr)
140 Scheme: ctrlURL.Scheme,
141 APIHost: ctrlURL.Host,
142 Insecure: cluster.TLS.Insecure,
143 Timeout: 5 * time.Minute,
147 // NewClientFromEnv creates a new Client that uses the default HTTP
148 // client, and loads API endpoint and credentials from ARVADOS_*
149 // environment variables (if set) and
150 // $HOME/.config/arvados/settings.conf (if readable).
152 // If a config exists in both locations, the environment variable is
155 // If there is an error (other than ENOENT) reading settings.conf,
156 // NewClientFromEnv logs the error to log.Default(), then proceeds as
157 // if settings.conf did not exist.
159 // Space characters are trimmed when reading the settings file, so
160 // these are equivalent:
162 // ARVADOS_API_HOST=localhost\n
163 // ARVADOS_API_HOST=localhost\r\n
164 // ARVADOS_API_HOST = localhost \n
165 // \tARVADOS_API_HOST = localhost\n
166 func NewClientFromEnv() *Client {
167 vars := map[string]string{}
168 home := os.Getenv("HOME")
169 conffile := home + "/.config/arvados/settings.conf"
171 // no $HOME => just use env vars
172 } else if settings, err := os.ReadFile(conffile); errors.Is(err, fs.ErrNotExist) {
173 // no config file => just use env vars
174 } else if err != nil {
175 // config file unreadable => log message, then use env vars
176 log.Printf("continuing without loading %s: %s", conffile, err)
178 for _, line := range bytes.Split(settings, []byte{'\n'}) {
179 kv := bytes.SplitN(line, []byte{'='}, 2)
180 k := string(bytes.TrimSpace(kv[0]))
181 if len(kv) != 2 || !strings.HasPrefix(k, "ARVADOS_") {
182 // Same behavior as python sdk:
183 // silently skip leading # (comments),
184 // blank lines, typos, and non-Arvados
188 vars[k] = string(bytes.TrimSpace(kv[1]))
191 for _, env := range os.Environ() {
192 if !strings.HasPrefix(env, "ARVADOS_") {
195 kv := strings.SplitN(env, "=", 2)
201 for _, s := range strings.Split(vars["ARVADOS_KEEP_SERVICES"], " ") {
204 } else if u, err := url.Parse(s); err != nil {
205 log.Printf("ARVADOS_KEEP_SERVICES: %q: %s", s, err)
206 } else if !u.IsAbs() {
207 log.Printf("ARVADOS_KEEP_SERVICES: %q: not an absolute URI", s)
209 svcs = append(svcs, s)
213 if s := strings.ToLower(vars["ARVADOS_API_HOST_INSECURE"]); s == "1" || s == "yes" || s == "true" {
218 APIHost: vars["ARVADOS_API_HOST"],
219 AuthToken: vars["ARVADOS_API_TOKEN"],
221 KeepServiceURIs: svcs,
222 Timeout: 5 * time.Minute,
227 var reqIDGen = httpserver.IDGenerator{Prefix: "req-"}
229 // Do adds Authorization and X-Request-Id headers, delays in order to
230 // comply with rate-limiting restrictions, and then calls
231 // (*http.Client)Do().
232 func (c *Client) Do(req *http.Request) (*http.Response, error) {
234 if auth, _ := ctx.Value(contextKeyAuthorization{}).(string); auth != "" {
235 req.Header.Add("Authorization", auth)
236 } else if c.AuthToken != "" {
237 req.Header.Add("Authorization", "OAuth2 "+c.AuthToken)
240 if req.Header.Get("X-Request-Id") == "" {
242 if ctxreqid, _ := ctx.Value(contextKeyRequestID{}).(string); ctxreqid != "" {
244 } else if c.defaultRequestID != "" {
245 reqid = c.defaultRequestID
247 reqid = reqIDGen.Next()
249 if req.Header == nil {
250 req.Header = http.Header{"X-Request-Id": {reqid}}
252 req.Header.Set("X-Request-Id", reqid)
255 var cancel context.CancelFunc
257 ctx, cancel = context.WithDeadline(ctx, time.Now().Add(c.Timeout))
258 req = req.WithContext(ctx)
260 cancel = context.CancelFunc(func() {})
263 c.requestLimiter.Acquire(ctx)
264 if ctx.Err() != nil {
265 c.requestLimiter.Release()
266 return nil, ctx.Err()
269 // Attach Release() to cancel func, see cancelOnClose below.
272 c.requestLimiter.Release()
276 resp, err := c.httpClient().Do(req)
277 c.requestLimiter.Report(resp, err)
279 // We need to call cancel() eventually, but we can't
280 // use "defer cancel()" because the context has to
281 // stay alive until the caller has finished reading
282 // the response body.
283 resp.Body = cancelOnClose{ReadCloser: resp.Body, cancel: cancel}
290 // cancelOnClose calls a provided CancelFunc when its wrapped
291 // ReadCloser's Close() method is called.
292 type cancelOnClose struct {
294 cancel context.CancelFunc
297 func (coc cancelOnClose) Close() error {
298 err := coc.ReadCloser.Close()
303 func isRedirectStatus(code int) bool {
305 case http.StatusMovedPermanently, http.StatusFound, http.StatusSeeOther, http.StatusTemporaryRedirect, http.StatusPermanentRedirect:
312 // DoAndDecode performs req and unmarshals the response (which must be
313 // JSON) into dst. Use this instead of RequestAndDecode if you need
314 // more control of the http.Request object.
316 // If the response status indicates an HTTP redirect, the Location
317 // header value is unmarshalled to dst as a RedirectLocation
319 func (c *Client) DoAndDecode(dst interface{}, req *http.Request) error {
320 resp, err := c.Do(req)
324 defer resp.Body.Close()
325 buf, err := ioutil.ReadAll(resp.Body)
330 case resp.StatusCode == http.StatusNoContent:
332 case resp.StatusCode == http.StatusOK && dst == nil:
334 case resp.StatusCode == http.StatusOK:
335 return json.Unmarshal(buf, dst)
337 // If the caller uses a client with a custom CheckRedirect
338 // func, Do() might return the 3xx response instead of
340 case isRedirectStatus(resp.StatusCode) && dst == nil:
342 case isRedirectStatus(resp.StatusCode):
343 // Copy the redirect target URL to dst.RedirectLocation.
344 buf, err := json.Marshal(map[string]string{"redirect_location": resp.Header.Get("Location")})
348 return json.Unmarshal(buf, dst)
351 return newTransactionError(req, resp, buf)
355 // Convert an arbitrary struct to url.Values. For example,
357 // Foo{Bar: []int{1,2,3}, Baz: "waz"}
361 // url.Values{`bar`:`{"a":[1,2,3]}`,`Baz`:`waz`}
363 // params itself is returned if it is already an url.Values.
364 func anythingToValues(params interface{}) (url.Values, error) {
365 if v, ok := params.(url.Values); ok {
368 // TODO: Do this more efficiently, possibly using
369 // json.Decode/Encode, so the whole thing doesn't have to get
370 // encoded, decoded, and re-encoded.
371 j, err := json.Marshal(params)
375 var generic map[string]interface{}
376 dec := json.NewDecoder(bytes.NewBuffer(j))
378 err = dec.Decode(&generic)
382 urlValues := url.Values{}
383 for k, v := range generic {
384 if v, ok := v.(string); ok {
388 if v, ok := v.(json.Number); ok {
389 urlValues.Set(k, v.String())
392 if v, ok := v.(bool); ok {
394 urlValues.Set(k, "true")
396 // "foo=false", "foo=0", and "foo="
397 // are all taken as true strings, so
398 // don't send false values at all --
399 // rely on the default being false.
403 j, err := json.Marshal(v)
407 if bytes.Equal(j, []byte("null")) {
408 // don't add it to urlValues at all
411 urlValues.Set(k, string(j))
413 return urlValues, nil
416 // RequestAndDecode performs an API request and unmarshals the
417 // response (which must be JSON) into dst. Method and body arguments
418 // are the same as for http.NewRequest(). The given path is added to
419 // the server's scheme/host/port to form the request URL. The given
420 // params are passed via POST form or query string.
422 // path must not contain a query string.
423 func (c *Client) RequestAndDecode(dst interface{}, method, path string, body io.Reader, params interface{}) error {
424 return c.RequestAndDecodeContext(context.Background(), dst, method, path, body, params)
427 // RequestAndDecodeContext does the same as RequestAndDecode, but with a context
428 func (c *Client) RequestAndDecodeContext(ctx context.Context, dst interface{}, method, path string, body io.Reader, params interface{}) error {
429 if body, ok := body.(io.Closer); ok {
430 // Ensure body is closed even if we error out early
435 return errors.New("ARVADOS_API_HOST and/or ARVADOS_API_TOKEN environment variables are not set")
437 return errors.New("arvados.Client cannot perform request: APIHost is not set")
439 urlString := c.apiURL(path)
440 urlValues, err := anythingToValues(params)
444 if urlValues == nil {
446 } else if body != nil || ((method == "GET" || method == "HEAD") && len(urlValues.Encode()) < 1000) {
447 // Send params in query part of URL
448 u, err := url.Parse(urlString)
452 u.RawQuery = urlValues.Encode()
453 urlString = u.String()
455 body = strings.NewReader(urlValues.Encode())
457 req, err := http.NewRequest(method, urlString, body)
461 if (method == "GET" || method == "HEAD") && body != nil {
462 req.Header.Set("X-Http-Method-Override", method)
465 req = req.WithContext(ctx)
466 req.Header.Set("Content-type", "application/x-www-form-urlencoded")
467 for k, v := range c.SendHeader {
470 return c.DoAndDecode(dst, req)
473 type resource interface {
474 resourceName() string
477 // UpdateBody returns an io.Reader suitable for use as an http.Request
478 // Body for a create or update API call.
479 func (c *Client) UpdateBody(rsc resource) io.Reader {
480 j, err := json.Marshal(rsc)
482 // Return a reader that returns errors.
484 w.CloseWithError(err)
487 v := url.Values{rsc.resourceName(): {string(j)}}
488 return bytes.NewBufferString(v.Encode())
491 // WithRequestID returns a new shallow copy of c that sends the given
492 // X-Request-Id value (instead of a new randomly generated one) with
493 // each subsequent request that doesn't provide its own via context or
495 func (c *Client) WithRequestID(reqid string) *Client {
497 cc.defaultRequestID = reqid
501 func (c *Client) httpClient() *http.Client {
503 case c.Client != nil:
506 return InsecureHTTPClient
508 return DefaultSecureClient
512 func (c *Client) apiURL(path string) string {
517 return scheme + "://" + c.APIHost + "/" + path
520 // DiscoveryDocument is the Arvados server's description of itself.
521 type DiscoveryDocument struct {
522 BasePath string `json:"basePath"`
523 DefaultCollectionReplication int `json:"defaultCollectionReplication"`
524 BlobSignatureTTL int64 `json:"blobSignatureTtl"`
525 GitURL string `json:"gitUrl"`
526 Schemas map[string]Schema `json:"schemas"`
527 Resources map[string]Resource `json:"resources"`
530 type Resource struct {
531 Methods map[string]ResourceMethod `json:"methods"`
534 type ResourceMethod struct {
535 HTTPMethod string `json:"httpMethod"`
536 Path string `json:"path"`
537 Response MethodResponse `json:"response"`
540 type MethodResponse struct {
541 Ref string `json:"$ref"`
545 UUIDPrefix string `json:"uuidPrefix"`
548 // DiscoveryDocument returns a *DiscoveryDocument. The returned object
549 // should not be modified: the same object may be returned by
551 func (c *Client) DiscoveryDocument() (*DiscoveryDocument, error) {
555 var dd DiscoveryDocument
556 err := c.RequestAndDecode(&dd, "GET", "discovery/v1/apis/arvados/v1/rest", nil, nil)
564 var pdhRegexp = regexp.MustCompile(`^[0-9a-f]{32}\+\d+$`)
566 func (c *Client) modelForUUID(dd *DiscoveryDocument, uuid string) (string, error) {
567 if pdhRegexp.MatchString(uuid) {
568 return "Collection", nil
571 return "", fmt.Errorf("invalid UUID: %q", uuid)
575 for m, s := range dd.Schemas {
576 if s.UUIDPrefix == infix {
582 return "", fmt.Errorf("unrecognized type portion %q in UUID %q", infix, uuid)
587 func (c *Client) KindForUUID(uuid string) (string, error) {
588 dd, err := c.DiscoveryDocument()
592 model, err := c.modelForUUID(dd, uuid)
596 return "arvados#" + strings.ToLower(model[:1]) + model[1:], nil
599 func (c *Client) PathForUUID(method, uuid string) (string, error) {
600 dd, err := c.DiscoveryDocument()
604 model, err := c.modelForUUID(dd, uuid)
609 for r, rsc := range dd.Resources {
610 if rsc.Methods["get"].Response.Ref == model {
616 return "", fmt.Errorf("no resource for model: %q", model)
618 m, ok := dd.Resources[resource].Methods[method]
620 return "", fmt.Errorf("no method %q for resource %q", method, resource)
622 path := dd.BasePath + strings.Replace(m.Path, "{uuid}", uuid, -1)
629 var maxUUIDInt = (&big.Int{}).Exp(big.NewInt(36), big.NewInt(15), nil)
631 func RandomUUID(clusterID, infix string) string {
632 n, err := rand.Int(rand.Reader, maxUUIDInt)
640 return clusterID + "-" + infix + "-" + nstr