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)
81 // InsecureHTTPClient is the default http.Client used by a Client with
82 // Insecure==true and Client==nil.
83 var InsecureHTTPClient = &http.Client{
84 Transport: &http.Transport{
85 TLSClientConfig: &tls.Config{
86 InsecureSkipVerify: true}}}
88 // DefaultSecureClient is the default http.Client used by a Client otherwise.
89 var DefaultSecureClient = &http.Client{}
91 // NewClientFromConfig creates a new Client that uses the endpoints in
94 // AuthToken is left empty for the caller to populate.
95 func NewClientFromConfig(cluster *Cluster) (*Client, error) {
96 ctrlURL := cluster.Services.Controller.ExternalURL
97 if ctrlURL.Host == "" {
98 return nil, fmt.Errorf("no host in config Services.Controller.ExternalURL: %v", ctrlURL)
101 if srvaddr := os.Getenv("ARVADOS_SERVER_ADDRESS"); srvaddr != "" {
102 // When this client is used to make a request to
103 // https://{ctrlhost}:port/ (any port), it dials the
104 // indicated port on ARVADOS_SERVER_ADDRESS instead.
106 // This is invoked by arvados-server boot to ensure
107 // that server->server traffic (e.g.,
108 // keepproxy->controller) only hits local interfaces,
109 // even if the Controller.ExternalURL host is a load
110 // balancer / gateway and not a local interface
111 // address (e.g., when running on a cloud VM).
113 // This avoids unnecessary delay/cost of routing
114 // external traffic, and also allows controller to
115 // recognize other services as internal clients based
116 // on the connection source address.
117 divertedHost := (*url.URL)(&cluster.Services.Controller.ExternalURL).Hostname()
118 var dialer net.Dialer
120 Transport: &http.Transport{
121 TLSClientConfig: &tls.Config{InsecureSkipVerify: cluster.TLS.Insecure},
122 DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
123 host, port, err := net.SplitHostPort(addr)
124 if err == nil && network == "tcp" && host == divertedHost {
125 addr = net.JoinHostPort(srvaddr, port)
127 return dialer.DialContext(ctx, network, addr)
134 Scheme: ctrlURL.Scheme,
135 APIHost: ctrlURL.Host,
136 Insecure: cluster.TLS.Insecure,
137 Timeout: 5 * time.Minute,
141 // NewClientFromEnv creates a new Client that uses the default HTTP
142 // client, and loads API endpoint and credentials from ARVADOS_*
143 // environment variables (if set) and
144 // $HOME/.config/arvados/settings.conf (if readable).
146 // If a config exists in both locations, the environment variable is
149 // If there is an error (other than ENOENT) reading settings.conf,
150 // NewClientFromEnv logs the error to log.Default(), then proceeds as
151 // if settings.conf did not exist.
153 // Space characters are trimmed when reading the settings file, so
154 // these are equivalent:
156 // ARVADOS_API_HOST=localhost\n
157 // ARVADOS_API_HOST=localhost\r\n
158 // ARVADOS_API_HOST = localhost \n
159 // \tARVADOS_API_HOST = localhost\n
160 func NewClientFromEnv() *Client {
161 vars := map[string]string{}
162 home := os.Getenv("HOME")
163 conffile := home + "/.config/arvados/settings.conf"
165 // no $HOME => just use env vars
166 } else if settings, err := os.ReadFile(conffile); errors.Is(err, fs.ErrNotExist) {
167 // no config file => just use env vars
168 } else if err != nil {
169 // config file unreadable => log message, then use env vars
170 log.Printf("continuing without loading %s: %s", conffile, err)
172 for _, line := range bytes.Split(settings, []byte{'\n'}) {
173 kv := bytes.SplitN(line, []byte{'='}, 2)
174 k := string(bytes.TrimSpace(kv[0]))
175 if len(kv) != 2 || !strings.HasPrefix(k, "ARVADOS_") {
176 // Same behavior as python sdk:
177 // silently skip leading # (comments),
178 // blank lines, typos, and non-Arvados
182 vars[k] = string(bytes.TrimSpace(kv[1]))
185 for _, env := range os.Environ() {
186 if !strings.HasPrefix(env, "ARVADOS_") {
189 kv := strings.SplitN(env, "=", 2)
195 for _, s := range strings.Split(vars["ARVADOS_KEEP_SERVICES"], " ") {
198 } else if u, err := url.Parse(s); err != nil {
199 log.Printf("ARVADOS_KEEP_SERVICES: %q: %s", s, err)
200 } else if !u.IsAbs() {
201 log.Printf("ARVADOS_KEEP_SERVICES: %q: not an absolute URI", s)
203 svcs = append(svcs, s)
207 if s := strings.ToLower(vars["ARVADOS_API_HOST_INSECURE"]); s == "1" || s == "yes" || s == "true" {
212 APIHost: vars["ARVADOS_API_HOST"],
213 AuthToken: vars["ARVADOS_API_TOKEN"],
215 KeepServiceURIs: svcs,
216 Timeout: 5 * time.Minute,
221 var reqIDGen = httpserver.IDGenerator{Prefix: "req-"}
223 // Do adds Authorization and X-Request-Id headers and then calls
224 // (*http.Client)Do().
225 func (c *Client) Do(req *http.Request) (*http.Response, error) {
226 if auth, _ := req.Context().Value(contextKeyAuthorization{}).(string); auth != "" {
227 req.Header.Add("Authorization", auth)
228 } else if c.AuthToken != "" {
229 req.Header.Add("Authorization", "OAuth2 "+c.AuthToken)
232 if req.Header.Get("X-Request-Id") == "" {
234 if ctxreqid, _ := req.Context().Value(contextKeyRequestID{}).(string); ctxreqid != "" {
236 } else if c.defaultRequestID != "" {
237 reqid = c.defaultRequestID
239 reqid = reqIDGen.Next()
241 if req.Header == nil {
242 req.Header = http.Header{"X-Request-Id": {reqid}}
244 req.Header.Set("X-Request-Id", reqid)
247 var cancel context.CancelFunc
250 ctx, cancel = context.WithDeadline(ctx, time.Now().Add(c.Timeout))
251 req = req.WithContext(ctx)
253 resp, err := c.httpClient().Do(req)
254 if err == nil && cancel != nil {
255 // We need to call cancel() eventually, but we can't
256 // use "defer cancel()" because the context has to
257 // stay alive until the caller has finished reading
258 // the response body.
259 resp.Body = cancelOnClose{ReadCloser: resp.Body, cancel: cancel}
260 } else if cancel != nil {
266 // cancelOnClose calls a provided CancelFunc when its wrapped
267 // ReadCloser's Close() method is called.
268 type cancelOnClose struct {
270 cancel context.CancelFunc
273 func (coc cancelOnClose) Close() error {
274 err := coc.ReadCloser.Close()
279 func isRedirectStatus(code int) bool {
281 case http.StatusMovedPermanently, http.StatusFound, http.StatusSeeOther, http.StatusTemporaryRedirect, http.StatusPermanentRedirect:
288 // DoAndDecode performs req and unmarshals the response (which must be
289 // JSON) into dst. Use this instead of RequestAndDecode if you need
290 // more control of the http.Request object.
292 // If the response status indicates an HTTP redirect, the Location
293 // header value is unmarshalled to dst as a RedirectLocation
295 func (c *Client) DoAndDecode(dst interface{}, req *http.Request) error {
296 resp, err := c.Do(req)
300 defer resp.Body.Close()
301 buf, err := ioutil.ReadAll(resp.Body)
306 case resp.StatusCode == http.StatusNoContent:
308 case resp.StatusCode == http.StatusOK && dst == nil:
310 case resp.StatusCode == http.StatusOK:
311 return json.Unmarshal(buf, dst)
313 // If the caller uses a client with a custom CheckRedirect
314 // func, Do() might return the 3xx response instead of
316 case isRedirectStatus(resp.StatusCode) && dst == nil:
318 case isRedirectStatus(resp.StatusCode):
319 // Copy the redirect target URL to dst.RedirectLocation.
320 buf, err := json.Marshal(map[string]string{"redirect_location": resp.Header.Get("Location")})
324 return json.Unmarshal(buf, dst)
327 return newTransactionError(req, resp, buf)
331 // Convert an arbitrary struct to url.Values. For example,
333 // Foo{Bar: []int{1,2,3}, Baz: "waz"}
337 // url.Values{`bar`:`{"a":[1,2,3]}`,`Baz`:`waz`}
339 // params itself is returned if it is already an url.Values.
340 func anythingToValues(params interface{}) (url.Values, error) {
341 if v, ok := params.(url.Values); ok {
344 // TODO: Do this more efficiently, possibly using
345 // json.Decode/Encode, so the whole thing doesn't have to get
346 // encoded, decoded, and re-encoded.
347 j, err := json.Marshal(params)
351 var generic map[string]interface{}
352 dec := json.NewDecoder(bytes.NewBuffer(j))
354 err = dec.Decode(&generic)
358 urlValues := url.Values{}
359 for k, v := range generic {
360 if v, ok := v.(string); ok {
364 if v, ok := v.(json.Number); ok {
365 urlValues.Set(k, v.String())
368 if v, ok := v.(bool); ok {
370 urlValues.Set(k, "true")
372 // "foo=false", "foo=0", and "foo="
373 // are all taken as true strings, so
374 // don't send false values at all --
375 // rely on the default being false.
379 j, err := json.Marshal(v)
383 if bytes.Equal(j, []byte("null")) {
384 // don't add it to urlValues at all
387 urlValues.Set(k, string(j))
389 return urlValues, nil
392 // RequestAndDecode performs an API request and unmarshals the
393 // response (which must be JSON) into dst. Method and body arguments
394 // are the same as for http.NewRequest(). The given path is added to
395 // the server's scheme/host/port to form the request URL. The given
396 // params are passed via POST form or query string.
398 // path must not contain a query string.
399 func (c *Client) RequestAndDecode(dst interface{}, method, path string, body io.Reader, params interface{}) error {
400 return c.RequestAndDecodeContext(context.Background(), dst, method, path, body, params)
403 // RequestAndDecodeContext does the same as RequestAndDecode, but with a context
404 func (c *Client) RequestAndDecodeContext(ctx context.Context, dst interface{}, method, path string, body io.Reader, params interface{}) error {
405 if body, ok := body.(io.Closer); ok {
406 // Ensure body is closed even if we error out early
411 return errors.New("ARVADOS_API_HOST and/or ARVADOS_API_TOKEN environment variables are not set")
413 return errors.New("arvados.Client cannot perform request: APIHost is not set")
415 urlString := c.apiURL(path)
416 urlValues, err := anythingToValues(params)
420 if urlValues == nil {
422 } else if body != nil || ((method == "GET" || method == "HEAD") && len(urlValues.Encode()) < 1000) {
423 // Send params in query part of URL
424 u, err := url.Parse(urlString)
428 u.RawQuery = urlValues.Encode()
429 urlString = u.String()
431 body = strings.NewReader(urlValues.Encode())
433 req, err := http.NewRequest(method, urlString, body)
437 if (method == "GET" || method == "HEAD") && body != nil {
438 req.Header.Set("X-Http-Method-Override", method)
441 req = req.WithContext(ctx)
442 req.Header.Set("Content-type", "application/x-www-form-urlencoded")
443 for k, v := range c.SendHeader {
446 return c.DoAndDecode(dst, req)
449 type resource interface {
450 resourceName() string
453 // UpdateBody returns an io.Reader suitable for use as an http.Request
454 // Body for a create or update API call.
455 func (c *Client) UpdateBody(rsc resource) io.Reader {
456 j, err := json.Marshal(rsc)
458 // Return a reader that returns errors.
460 w.CloseWithError(err)
463 v := url.Values{rsc.resourceName(): {string(j)}}
464 return bytes.NewBufferString(v.Encode())
467 // WithRequestID returns a new shallow copy of c that sends the given
468 // X-Request-Id value (instead of a new randomly generated one) with
469 // each subsequent request that doesn't provide its own via context or
471 func (c *Client) WithRequestID(reqid string) *Client {
473 cc.defaultRequestID = reqid
477 func (c *Client) httpClient() *http.Client {
479 case c.Client != nil:
482 return InsecureHTTPClient
484 return DefaultSecureClient
488 func (c *Client) apiURL(path string) string {
493 return scheme + "://" + c.APIHost + "/" + path
496 // DiscoveryDocument is the Arvados server's description of itself.
497 type DiscoveryDocument struct {
498 BasePath string `json:"basePath"`
499 DefaultCollectionReplication int `json:"defaultCollectionReplication"`
500 BlobSignatureTTL int64 `json:"blobSignatureTtl"`
501 GitURL string `json:"gitUrl"`
502 Schemas map[string]Schema `json:"schemas"`
503 Resources map[string]Resource `json:"resources"`
506 type Resource struct {
507 Methods map[string]ResourceMethod `json:"methods"`
510 type ResourceMethod struct {
511 HTTPMethod string `json:"httpMethod"`
512 Path string `json:"path"`
513 Response MethodResponse `json:"response"`
516 type MethodResponse struct {
517 Ref string `json:"$ref"`
521 UUIDPrefix string `json:"uuidPrefix"`
524 // DiscoveryDocument returns a *DiscoveryDocument. The returned object
525 // should not be modified: the same object may be returned by
527 func (c *Client) DiscoveryDocument() (*DiscoveryDocument, error) {
531 var dd DiscoveryDocument
532 err := c.RequestAndDecode(&dd, "GET", "discovery/v1/apis/arvados/v1/rest", nil, nil)
540 var pdhRegexp = regexp.MustCompile(`^[0-9a-f]{32}\+\d+$`)
542 func (c *Client) modelForUUID(dd *DiscoveryDocument, uuid string) (string, error) {
543 if pdhRegexp.MatchString(uuid) {
544 return "Collection", nil
547 return "", fmt.Errorf("invalid UUID: %q", uuid)
551 for m, s := range dd.Schemas {
552 if s.UUIDPrefix == infix {
558 return "", fmt.Errorf("unrecognized type portion %q in UUID %q", infix, uuid)
563 func (c *Client) KindForUUID(uuid string) (string, error) {
564 dd, err := c.DiscoveryDocument()
568 model, err := c.modelForUUID(dd, uuid)
572 return "arvados#" + strings.ToLower(model[:1]) + model[1:], nil
575 func (c *Client) PathForUUID(method, uuid string) (string, error) {
576 dd, err := c.DiscoveryDocument()
580 model, err := c.modelForUUID(dd, uuid)
585 for r, rsc := range dd.Resources {
586 if rsc.Methods["get"].Response.Ref == model {
592 return "", fmt.Errorf("no resource for model: %q", model)
594 m, ok := dd.Resources[resource].Methods[method]
596 return "", fmt.Errorf("no method %q for resource %q", method, resource)
598 path := dd.BasePath + strings.Replace(m.Path, "{uuid}", uuid, -1)
605 var maxUUIDInt = (&big.Int{}).Exp(big.NewInt(36), big.NewInt(15), nil)
607 func RandomUUID(clusterID, infix string) string {
608 n, err := rand.Int(rand.Reader, maxUUIDInt)
616 return clusterID + "-" + infix + "-" + nstr