1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: Apache-2.0
26 "git.arvados.org/arvados.git/sdk/go/httpserver"
29 // A Client is an HTTP client with an API endpoint and a set of
30 // Arvados credentials.
32 // It offers methods for accessing individual Arvados APIs, and
33 // methods that implement common patterns like fetching multiple pages
34 // of results using List APIs.
36 // HTTP client used to make requests. If nil,
37 // DefaultSecureClient or InsecureHTTPClient will be used.
38 Client *http.Client `json:"-"`
40 // Protocol scheme: "http", "https", or "" (https)
43 // Hostname (or host:port) of Arvados API server.
46 // User authentication token.
49 // Accept unverified certificates. This works only if the
50 // Client field is nil: otherwise, it has no effect.
53 // Override keep service discovery with a list of base
54 // URIs. (Currently there are no Client methods for
55 // discovering keep services so this is just a convenience for
56 // callers who use a Client to initialize an
57 // arvadosclient.ArvadosClient.)
58 KeepServiceURIs []string `json:",omitempty"`
60 // HTTP headers to add/override in outgoing requests.
61 SendHeader http.Header
63 // Timeout for requests. NewClientFromConfig and
64 // NewClientFromEnv return a Client with a default 5 minute
65 // timeout. To disable this timeout and rely on each
66 // http.Request's context deadline instead, set Timeout to
72 defaultRequestID string
74 // APIHost and AuthToken were loaded from ARVADOS_* env vars
75 // (used to customize "no host/token" error messages)
79 // InsecureHTTPClient is the default http.Client used by a Client with
80 // Insecure==true and Client==nil.
81 var InsecureHTTPClient = &http.Client{
82 Transport: &http.Transport{
83 TLSClientConfig: &tls.Config{
84 InsecureSkipVerify: true}}}
86 // DefaultSecureClient is the default http.Client used by a Client otherwise.
87 var DefaultSecureClient = &http.Client{}
89 // NewClientFromConfig creates a new Client that uses the endpoints in
92 // AuthToken is left empty for the caller to populate.
93 func NewClientFromConfig(cluster *Cluster) (*Client, error) {
94 ctrlURL := cluster.Services.Controller.ExternalURL
95 if ctrlURL.Host == "" {
96 return nil, fmt.Errorf("no host in config Services.Controller.ExternalURL: %v", ctrlURL)
99 if srvaddr := os.Getenv("ARVADOS_SERVER_ADDRESS"); srvaddr != "" {
100 // When this client is used to make a request to
101 // https://{ctrlhost}:port/ (any port), it dials the
102 // indicated port on ARVADOS_SERVER_ADDRESS instead.
104 // This is invoked by arvados-server boot to ensure
105 // that server->server traffic (e.g.,
106 // keepproxy->controller) only hits local interfaces,
107 // even if the Controller.ExternalURL host is a load
108 // balancer / gateway and not a local interface
109 // address (e.g., when running on a cloud VM).
111 // This avoids unnecessary delay/cost of routing
112 // external traffic, and also allows controller to
113 // recognize other services as internal clients based
114 // on the connection source address.
115 divertedHost := (*url.URL)(&cluster.Services.Controller.ExternalURL).Hostname()
116 var dialer net.Dialer
118 Transport: &http.Transport{
119 TLSClientConfig: &tls.Config{InsecureSkipVerify: cluster.TLS.Insecure},
120 DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
121 host, port, err := net.SplitHostPort(addr)
122 if err == nil && network == "tcp" && host == divertedHost {
123 addr = net.JoinHostPort(srvaddr, port)
125 return dialer.DialContext(ctx, network, addr)
132 Scheme: ctrlURL.Scheme,
133 APIHost: ctrlURL.Host,
134 Insecure: cluster.TLS.Insecure,
135 Timeout: 5 * time.Minute,
139 // NewClientFromEnv creates a new Client that uses the default HTTP
140 // client, and loads API endpoint and credentials from ARVADOS_*
141 // environment variables (if set) and
142 // $HOME/.config/arvados/settings.conf (if readable).
144 // If a config exists in both locations, the environment variable is
147 // If there is an error (other than ENOENT) reading settings.conf,
148 // NewClientFromEnv logs the error to log.Default(), then proceeds as
149 // if settings.conf did not exist.
151 // Space characters are trimmed when reading the settings file, so
152 // these are equivalent:
154 // ARVADOS_API_HOST=localhost\n
155 // ARVADOS_API_HOST=localhost\r\n
156 // ARVADOS_API_HOST = localhost \n
157 // \tARVADOS_API_HOST = localhost\n
158 func NewClientFromEnv() *Client {
159 vars := map[string]string{}
160 home := os.Getenv("HOME")
161 conffile := home + "/.config/arvados/settings.conf"
163 // no $HOME => just use env vars
164 } else if settings, err := os.ReadFile(conffile); errors.Is(err, fs.ErrNotExist) {
165 // no config file => just use env vars
166 } else if err != nil {
167 // config file unreadable => log message, then use env vars
168 log.Printf("continuing without loading %s: %s", conffile, err)
170 for _, line := range bytes.Split(settings, []byte{'\n'}) {
171 kv := bytes.SplitN(line, []byte{'='}, 2)
172 k := string(bytes.TrimSpace(kv[0]))
173 if len(kv) != 2 || !strings.HasPrefix(k, "ARVADOS_") {
174 // Same behavior as python sdk:
175 // silently skip leading # (comments),
176 // blank lines, typos, and non-Arvados
180 vars[k] = string(bytes.TrimSpace(kv[1]))
183 for _, env := range os.Environ() {
184 if !strings.HasPrefix(env, "ARVADOS_") {
187 kv := strings.SplitN(env, "=", 2)
193 for _, s := range strings.Split(vars["ARVADOS_KEEP_SERVICES"], " ") {
196 } else if u, err := url.Parse(s); err != nil {
197 log.Printf("ARVADOS_KEEP_SERVICES: %q: %s", s, err)
198 } else if !u.IsAbs() {
199 log.Printf("ARVADOS_KEEP_SERVICES: %q: not an absolute URI", s)
201 svcs = append(svcs, s)
205 if s := strings.ToLower(vars["ARVADOS_API_HOST_INSECURE"]); s == "1" || s == "yes" || s == "true" {
210 APIHost: vars["ARVADOS_API_HOST"],
211 AuthToken: vars["ARVADOS_API_TOKEN"],
213 KeepServiceURIs: svcs,
214 Timeout: 5 * time.Minute,
219 var reqIDGen = httpserver.IDGenerator{Prefix: "req-"}
221 // Do adds Authorization and X-Request-Id headers and then calls
222 // (*http.Client)Do().
223 func (c *Client) Do(req *http.Request) (*http.Response, error) {
224 if auth, _ := req.Context().Value(contextKeyAuthorization{}).(string); auth != "" {
225 req.Header.Add("Authorization", auth)
226 } else if c.AuthToken != "" {
227 req.Header.Add("Authorization", "OAuth2 "+c.AuthToken)
230 if req.Header.Get("X-Request-Id") == "" {
232 if ctxreqid, _ := req.Context().Value(contextKeyRequestID{}).(string); ctxreqid != "" {
234 } else if c.defaultRequestID != "" {
235 reqid = c.defaultRequestID
237 reqid = reqIDGen.Next()
239 if req.Header == nil {
240 req.Header = http.Header{"X-Request-Id": {reqid}}
242 req.Header.Set("X-Request-Id", reqid)
245 var cancel context.CancelFunc
248 ctx, cancel = context.WithDeadline(ctx, time.Now().Add(c.Timeout))
249 req = req.WithContext(ctx)
251 resp, err := c.httpClient().Do(req)
252 if err == nil && cancel != nil {
253 // We need to call cancel() eventually, but we can't
254 // use "defer cancel()" because the context has to
255 // stay alive until the caller has finished reading
256 // the response body.
257 resp.Body = cancelOnClose{ReadCloser: resp.Body, cancel: cancel}
258 } else if cancel != nil {
264 // cancelOnClose calls a provided CancelFunc when its wrapped
265 // ReadCloser's Close() method is called.
266 type cancelOnClose struct {
268 cancel context.CancelFunc
271 func (coc cancelOnClose) Close() error {
272 err := coc.ReadCloser.Close()
277 func isRedirectStatus(code int) bool {
279 case http.StatusMovedPermanently, http.StatusFound, http.StatusSeeOther, http.StatusTemporaryRedirect, http.StatusPermanentRedirect:
286 // DoAndDecode performs req and unmarshals the response (which must be
287 // JSON) into dst. Use this instead of RequestAndDecode if you need
288 // more control of the http.Request object.
290 // If the response status indicates an HTTP redirect, the Location
291 // header value is unmarshalled to dst as a RedirectLocation
293 func (c *Client) DoAndDecode(dst interface{}, req *http.Request) error {
294 resp, err := c.Do(req)
298 defer resp.Body.Close()
299 buf, err := ioutil.ReadAll(resp.Body)
304 case resp.StatusCode == http.StatusNoContent:
306 case resp.StatusCode == http.StatusOK && dst == nil:
308 case resp.StatusCode == http.StatusOK:
309 return json.Unmarshal(buf, dst)
311 // If the caller uses a client with a custom CheckRedirect
312 // func, Do() might return the 3xx response instead of
314 case isRedirectStatus(resp.StatusCode) && dst == nil:
316 case isRedirectStatus(resp.StatusCode):
317 // Copy the redirect target URL to dst.RedirectLocation.
318 buf, err := json.Marshal(map[string]string{"redirect_location": resp.Header.Get("Location")})
322 return json.Unmarshal(buf, dst)
325 return newTransactionError(req, resp, buf)
329 // Convert an arbitrary struct to url.Values. For example,
331 // Foo{Bar: []int{1,2,3}, Baz: "waz"}
335 // url.Values{`bar`:`{"a":[1,2,3]}`,`Baz`:`waz`}
337 // params itself is returned if it is already an url.Values.
338 func anythingToValues(params interface{}) (url.Values, error) {
339 if v, ok := params.(url.Values); ok {
342 // TODO: Do this more efficiently, possibly using
343 // json.Decode/Encode, so the whole thing doesn't have to get
344 // encoded, decoded, and re-encoded.
345 j, err := json.Marshal(params)
349 var generic map[string]interface{}
350 dec := json.NewDecoder(bytes.NewBuffer(j))
352 err = dec.Decode(&generic)
356 urlValues := url.Values{}
357 for k, v := range generic {
358 if v, ok := v.(string); ok {
362 if v, ok := v.(json.Number); ok {
363 urlValues.Set(k, v.String())
366 if v, ok := v.(bool); ok {
368 urlValues.Set(k, "true")
370 // "foo=false", "foo=0", and "foo="
371 // are all taken as true strings, so
372 // don't send false values at all --
373 // rely on the default being false.
377 j, err := json.Marshal(v)
381 if bytes.Equal(j, []byte("null")) {
382 // don't add it to urlValues at all
385 urlValues.Set(k, string(j))
387 return urlValues, nil
390 // RequestAndDecode performs an API request and unmarshals the
391 // response (which must be JSON) into dst. Method and body arguments
392 // are the same as for http.NewRequest(). The given path is added to
393 // the server's scheme/host/port to form the request URL. The given
394 // params are passed via POST form or query string.
396 // path must not contain a query string.
397 func (c *Client) RequestAndDecode(dst interface{}, method, path string, body io.Reader, params interface{}) error {
398 return c.RequestAndDecodeContext(context.Background(), dst, method, path, body, params)
401 // RequestAndDecodeContext does the same as RequestAndDecode, but with a context
402 func (c *Client) RequestAndDecodeContext(ctx context.Context, dst interface{}, method, path string, body io.Reader, params interface{}) error {
403 if body, ok := body.(io.Closer); ok {
404 // Ensure body is closed even if we error out early
409 return errors.New("ARVADOS_API_HOST and/or ARVADOS_API_TOKEN environment variables are not set")
411 return errors.New("arvados.Client cannot perform request: APIHost is not set")
413 urlString := c.apiURL(path)
414 urlValues, err := anythingToValues(params)
418 if urlValues == nil {
420 } else if body != nil || ((method == "GET" || method == "HEAD") && len(urlValues.Encode()) < 1000) {
421 // Send params in query part of URL
422 u, err := url.Parse(urlString)
426 u.RawQuery = urlValues.Encode()
427 urlString = u.String()
429 body = strings.NewReader(urlValues.Encode())
431 req, err := http.NewRequest(method, urlString, body)
435 if (method == "GET" || method == "HEAD") && body != nil {
436 req.Header.Set("X-Http-Method-Override", method)
439 req = req.WithContext(ctx)
440 req.Header.Set("Content-type", "application/x-www-form-urlencoded")
441 for k, v := range c.SendHeader {
444 return c.DoAndDecode(dst, req)
447 type resource interface {
448 resourceName() string
451 // UpdateBody returns an io.Reader suitable for use as an http.Request
452 // Body for a create or update API call.
453 func (c *Client) UpdateBody(rsc resource) io.Reader {
454 j, err := json.Marshal(rsc)
456 // Return a reader that returns errors.
458 w.CloseWithError(err)
461 v := url.Values{rsc.resourceName(): {string(j)}}
462 return bytes.NewBufferString(v.Encode())
465 // WithRequestID returns a new shallow copy of c that sends the given
466 // X-Request-Id value (instead of a new randomly generated one) with
467 // each subsequent request that doesn't provide its own via context or
469 func (c *Client) WithRequestID(reqid string) *Client {
471 cc.defaultRequestID = reqid
475 func (c *Client) httpClient() *http.Client {
477 case c.Client != nil:
480 return InsecureHTTPClient
482 return DefaultSecureClient
486 func (c *Client) apiURL(path string) string {
491 return scheme + "://" + c.APIHost + "/" + path
494 // DiscoveryDocument is the Arvados server's description of itself.
495 type DiscoveryDocument struct {
496 BasePath string `json:"basePath"`
497 DefaultCollectionReplication int `json:"defaultCollectionReplication"`
498 BlobSignatureTTL int64 `json:"blobSignatureTtl"`
499 GitURL string `json:"gitUrl"`
500 Schemas map[string]Schema `json:"schemas"`
501 Resources map[string]Resource `json:"resources"`
504 type Resource struct {
505 Methods map[string]ResourceMethod `json:"methods"`
508 type ResourceMethod struct {
509 HTTPMethod string `json:"httpMethod"`
510 Path string `json:"path"`
511 Response MethodResponse `json:"response"`
514 type MethodResponse struct {
515 Ref string `json:"$ref"`
519 UUIDPrefix string `json:"uuidPrefix"`
522 // DiscoveryDocument returns a *DiscoveryDocument. The returned object
523 // should not be modified: the same object may be returned by
525 func (c *Client) DiscoveryDocument() (*DiscoveryDocument, error) {
529 var dd DiscoveryDocument
530 err := c.RequestAndDecode(&dd, "GET", "discovery/v1/apis/arvados/v1/rest", nil, nil)
538 var pdhRegexp = regexp.MustCompile(`^[0-9a-f]{32}\+\d+$`)
540 func (c *Client) modelForUUID(dd *DiscoveryDocument, uuid string) (string, error) {
541 if pdhRegexp.MatchString(uuid) {
542 return "Collection", nil
545 return "", fmt.Errorf("invalid UUID: %q", uuid)
549 for m, s := range dd.Schemas {
550 if s.UUIDPrefix == infix {
556 return "", fmt.Errorf("unrecognized type portion %q in UUID %q", infix, uuid)
561 func (c *Client) KindForUUID(uuid string) (string, error) {
562 dd, err := c.DiscoveryDocument()
566 model, err := c.modelForUUID(dd, uuid)
570 return "arvados#" + strings.ToLower(model[:1]) + model[1:], nil
573 func (c *Client) PathForUUID(method, uuid string) (string, error) {
574 dd, err := c.DiscoveryDocument()
578 model, err := c.modelForUUID(dd, uuid)
583 for r, rsc := range dd.Resources {
584 if rsc.Methods["get"].Response.Ref == model {
590 return "", fmt.Errorf("no resource for model: %q", model)
592 m, ok := dd.Resources[resource].Methods[method]
594 return "", fmt.Errorf("no method %q for resource %q", method, resource)
596 path := dd.BasePath + strings.Replace(m.Path, "{uuid}", uuid, -1)