1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: Apache-2.0
25 "git.arvados.org/arvados.git/sdk/go/httpserver"
28 // A Client is an HTTP client with an API endpoint and a set of
29 // Arvados credentials.
31 // It offers methods for accessing individual Arvados APIs, and
32 // methods that implement common patterns like fetching multiple pages
33 // of results using List APIs.
35 // HTTP client used to make requests. If nil,
36 // DefaultSecureClient or InsecureHTTPClient will be used.
37 Client *http.Client `json:"-"`
39 // Protocol scheme: "http", "https", or "" (https)
42 // Hostname (or host:port) of Arvados API server.
45 // User authentication token.
48 // Accept unverified certificates. This works only if the
49 // Client field is nil: otherwise, it has no effect.
52 // Override keep service discovery with a list of base
53 // URIs. (Currently there are no Client methods for
54 // discovering keep services so this is just a convenience for
55 // callers who use a Client to initialize an
56 // arvadosclient.ArvadosClient.)
57 KeepServiceURIs []string `json:",omitempty"`
59 // HTTP headers to add/override in outgoing requests.
60 SendHeader http.Header
62 // Timeout for requests. NewClientFromConfig and
63 // NewClientFromEnv return a Client with a default 5 minute
64 // timeout. To disable this timeout and rely on each
65 // http.Request's context deadline instead, set Timeout to
71 defaultRequestID string
73 // APIHost and AuthToken were loaded from ARVADOS_* env vars
74 // (used to customize "no host/token" error messages)
78 // InsecureHTTPClient is the default http.Client used by a Client with
79 // Insecure==true and Client==nil.
80 var InsecureHTTPClient = &http.Client{
81 Transport: &http.Transport{
82 TLSClientConfig: &tls.Config{
83 InsecureSkipVerify: true}}}
85 // DefaultSecureClient is the default http.Client used by a Client otherwise.
86 var DefaultSecureClient = &http.Client{}
88 // NewClientFromConfig creates a new Client that uses the endpoints in
91 // AuthToken is left empty for the caller to populate.
92 func NewClientFromConfig(cluster *Cluster) (*Client, error) {
93 ctrlURL := cluster.Services.Controller.ExternalURL
94 if ctrlURL.Host == "" {
95 return nil, fmt.Errorf("no host in config Services.Controller.ExternalURL: %v", ctrlURL)
98 Scheme: ctrlURL.Scheme,
99 APIHost: ctrlURL.Host,
100 Insecure: cluster.TLS.Insecure,
101 Timeout: 5 * time.Minute,
105 // NewClientFromEnv creates a new Client that uses the default HTTP
106 // client, and loads API endpoint and credentials from ARVADOS_*
107 // environment variables (if set) and
108 // $HOME/.config/arvados/settings.conf (if readable).
110 // If a config exists in both locations, the environment variable is
113 // If there is an error (other than ENOENT) reading settings.conf,
114 // NewClientFromEnv logs the error to log.Default(), then proceeds as
115 // if settings.conf did not exist.
117 // Space characters are trimmed when reading the settings file, so
118 // these are equivalent:
120 // ARVADOS_API_HOST=localhost\n
121 // ARVADOS_API_HOST=localhost\r\n
122 // ARVADOS_API_HOST = localhost \n
123 // \tARVADOS_API_HOST = localhost\n
124 func NewClientFromEnv() *Client {
125 vars := map[string]string{}
126 home := os.Getenv("HOME")
127 conffile := home + "/.config/arvados/settings.conf"
129 // no $HOME => just use env vars
130 } else if settings, err := os.ReadFile(conffile); errors.Is(err, fs.ErrNotExist) {
131 // no config file => just use env vars
132 } else if err != nil {
133 // config file unreadable => log message, then use env vars
134 log.Printf("continuing without loading %s: %s", conffile, err)
136 for _, line := range bytes.Split(settings, []byte{'\n'}) {
137 kv := bytes.SplitN(line, []byte{'='}, 2)
138 k := string(bytes.TrimSpace(kv[0]))
139 if len(kv) != 2 || !strings.HasPrefix(k, "ARVADOS_") {
140 // Same behavior as python sdk:
141 // silently skip leading # (comments),
142 // blank lines, typos, and non-Arvados
146 vars[k] = string(bytes.TrimSpace(kv[1]))
149 for _, env := range os.Environ() {
150 if !strings.HasPrefix(env, "ARVADOS_") {
153 kv := strings.SplitN(env, "=", 2)
159 for _, s := range strings.Split(vars["ARVADOS_KEEP_SERVICES"], " ") {
162 } else if u, err := url.Parse(s); err != nil {
163 log.Printf("ARVADOS_KEEP_SERVICES: %q: %s", s, err)
164 } else if !u.IsAbs() {
165 log.Printf("ARVADOS_KEEP_SERVICES: %q: not an absolute URI", s)
167 svcs = append(svcs, s)
171 if s := strings.ToLower(vars["ARVADOS_API_HOST_INSECURE"]); s == "1" || s == "yes" || s == "true" {
176 APIHost: vars["ARVADOS_API_HOST"],
177 AuthToken: vars["ARVADOS_API_TOKEN"],
179 KeepServiceURIs: svcs,
180 Timeout: 5 * time.Minute,
185 var reqIDGen = httpserver.IDGenerator{Prefix: "req-"}
187 // Do adds Authorization and X-Request-Id headers and then calls
188 // (*http.Client)Do().
189 func (c *Client) Do(req *http.Request) (*http.Response, error) {
190 if auth, _ := req.Context().Value(contextKeyAuthorization{}).(string); auth != "" {
191 req.Header.Add("Authorization", auth)
192 } else if c.AuthToken != "" {
193 req.Header.Add("Authorization", "OAuth2 "+c.AuthToken)
196 if req.Header.Get("X-Request-Id") == "" {
198 if ctxreqid, _ := req.Context().Value(contextKeyRequestID{}).(string); ctxreqid != "" {
200 } else if c.defaultRequestID != "" {
201 reqid = c.defaultRequestID
203 reqid = reqIDGen.Next()
205 if req.Header == nil {
206 req.Header = http.Header{"X-Request-Id": {reqid}}
208 req.Header.Set("X-Request-Id", reqid)
211 var cancel context.CancelFunc
214 ctx, cancel = context.WithDeadline(ctx, time.Now().Add(c.Timeout))
215 req = req.WithContext(ctx)
217 resp, err := c.httpClient().Do(req)
218 if err == nil && cancel != nil {
219 // We need to call cancel() eventually, but we can't
220 // use "defer cancel()" because the context has to
221 // stay alive until the caller has finished reading
222 // the response body.
223 resp.Body = cancelOnClose{ReadCloser: resp.Body, cancel: cancel}
224 } else if cancel != nil {
230 // cancelOnClose calls a provided CancelFunc when its wrapped
231 // ReadCloser's Close() method is called.
232 type cancelOnClose struct {
234 cancel context.CancelFunc
237 func (coc cancelOnClose) Close() error {
238 err := coc.ReadCloser.Close()
243 func isRedirectStatus(code int) bool {
245 case http.StatusMovedPermanently, http.StatusFound, http.StatusSeeOther, http.StatusTemporaryRedirect, http.StatusPermanentRedirect:
252 // DoAndDecode performs req and unmarshals the response (which must be
253 // JSON) into dst. Use this instead of RequestAndDecode if you need
254 // more control of the http.Request object.
256 // If the response status indicates an HTTP redirect, the Location
257 // header value is unmarshalled to dst as a RedirectLocation
259 func (c *Client) DoAndDecode(dst interface{}, req *http.Request) error {
260 resp, err := c.Do(req)
264 defer resp.Body.Close()
265 buf, err := ioutil.ReadAll(resp.Body)
270 case resp.StatusCode == http.StatusNoContent:
272 case resp.StatusCode == http.StatusOK && dst == nil:
274 case resp.StatusCode == http.StatusOK:
275 return json.Unmarshal(buf, dst)
277 // If the caller uses a client with a custom CheckRedirect
278 // func, Do() might return the 3xx response instead of
280 case isRedirectStatus(resp.StatusCode) && dst == nil:
282 case isRedirectStatus(resp.StatusCode):
283 // Copy the redirect target URL to dst.RedirectLocation.
284 buf, err := json.Marshal(map[string]string{"redirect_location": resp.Header.Get("Location")})
288 return json.Unmarshal(buf, dst)
291 return newTransactionError(req, resp, buf)
295 // Convert an arbitrary struct to url.Values. For example,
297 // Foo{Bar: []int{1,2,3}, Baz: "waz"}
301 // url.Values{`bar`:`{"a":[1,2,3]}`,`Baz`:`waz`}
303 // params itself is returned if it is already an url.Values.
304 func anythingToValues(params interface{}) (url.Values, error) {
305 if v, ok := params.(url.Values); ok {
308 // TODO: Do this more efficiently, possibly using
309 // json.Decode/Encode, so the whole thing doesn't have to get
310 // encoded, decoded, and re-encoded.
311 j, err := json.Marshal(params)
315 var generic map[string]interface{}
316 dec := json.NewDecoder(bytes.NewBuffer(j))
318 err = dec.Decode(&generic)
322 urlValues := url.Values{}
323 for k, v := range generic {
324 if v, ok := v.(string); ok {
328 if v, ok := v.(json.Number); ok {
329 urlValues.Set(k, v.String())
332 if v, ok := v.(bool); ok {
334 urlValues.Set(k, "true")
336 // "foo=false", "foo=0", and "foo="
337 // are all taken as true strings, so
338 // don't send false values at all --
339 // rely on the default being false.
343 j, err := json.Marshal(v)
347 if bytes.Equal(j, []byte("null")) {
348 // don't add it to urlValues at all
351 urlValues.Set(k, string(j))
353 return urlValues, nil
356 // RequestAndDecode performs an API request and unmarshals the
357 // response (which must be JSON) into dst. Method and body arguments
358 // are the same as for http.NewRequest(). The given path is added to
359 // the server's scheme/host/port to form the request URL. The given
360 // params are passed via POST form or query string.
362 // path must not contain a query string.
363 func (c *Client) RequestAndDecode(dst interface{}, method, path string, body io.Reader, params interface{}) error {
364 return c.RequestAndDecodeContext(context.Background(), dst, method, path, body, params)
367 // RequestAndDecodeContext does the same as RequestAndDecode, but with a context
368 func (c *Client) RequestAndDecodeContext(ctx context.Context, dst interface{}, method, path string, body io.Reader, params interface{}) error {
369 if body, ok := body.(io.Closer); ok {
370 // Ensure body is closed even if we error out early
375 return errors.New("ARVADOS_API_HOST and/or ARVADOS_API_TOKEN environment variables are not set")
377 return errors.New("arvados.Client cannot perform request: APIHost is not set")
379 urlString := c.apiURL(path)
380 urlValues, err := anythingToValues(params)
384 if urlValues == nil {
386 } else if body != nil || ((method == "GET" || method == "HEAD") && len(urlValues.Encode()) < 1000) {
387 // Send params in query part of URL
388 u, err := url.Parse(urlString)
392 u.RawQuery = urlValues.Encode()
393 urlString = u.String()
395 body = strings.NewReader(urlValues.Encode())
397 req, err := http.NewRequest(method, urlString, body)
401 if (method == "GET" || method == "HEAD") && body != nil {
402 req.Header.Set("X-Http-Method-Override", method)
405 req = req.WithContext(ctx)
406 req.Header.Set("Content-type", "application/x-www-form-urlencoded")
407 for k, v := range c.SendHeader {
410 return c.DoAndDecode(dst, req)
413 type resource interface {
414 resourceName() string
417 // UpdateBody returns an io.Reader suitable for use as an http.Request
418 // Body for a create or update API call.
419 func (c *Client) UpdateBody(rsc resource) io.Reader {
420 j, err := json.Marshal(rsc)
422 // Return a reader that returns errors.
424 w.CloseWithError(err)
427 v := url.Values{rsc.resourceName(): {string(j)}}
428 return bytes.NewBufferString(v.Encode())
431 // WithRequestID returns a new shallow copy of c that sends the given
432 // X-Request-Id value (instead of a new randomly generated one) with
433 // each subsequent request that doesn't provide its own via context or
435 func (c *Client) WithRequestID(reqid string) *Client {
437 cc.defaultRequestID = reqid
441 func (c *Client) httpClient() *http.Client {
443 case c.Client != nil:
446 return InsecureHTTPClient
448 return DefaultSecureClient
452 func (c *Client) apiURL(path string) string {
457 return scheme + "://" + c.APIHost + "/" + path
460 // DiscoveryDocument is the Arvados server's description of itself.
461 type DiscoveryDocument struct {
462 BasePath string `json:"basePath"`
463 DefaultCollectionReplication int `json:"defaultCollectionReplication"`
464 BlobSignatureTTL int64 `json:"blobSignatureTtl"`
465 GitURL string `json:"gitUrl"`
466 Schemas map[string]Schema `json:"schemas"`
467 Resources map[string]Resource `json:"resources"`
470 type Resource struct {
471 Methods map[string]ResourceMethod `json:"methods"`
474 type ResourceMethod struct {
475 HTTPMethod string `json:"httpMethod"`
476 Path string `json:"path"`
477 Response MethodResponse `json:"response"`
480 type MethodResponse struct {
481 Ref string `json:"$ref"`
485 UUIDPrefix string `json:"uuidPrefix"`
488 // DiscoveryDocument returns a *DiscoveryDocument. The returned object
489 // should not be modified: the same object may be returned by
491 func (c *Client) DiscoveryDocument() (*DiscoveryDocument, error) {
495 var dd DiscoveryDocument
496 err := c.RequestAndDecode(&dd, "GET", "discovery/v1/apis/arvados/v1/rest", nil, nil)
504 var pdhRegexp = regexp.MustCompile(`^[0-9a-f]{32}\+\d+$`)
506 func (c *Client) modelForUUID(dd *DiscoveryDocument, uuid string) (string, error) {
507 if pdhRegexp.MatchString(uuid) {
508 return "Collection", nil
511 return "", fmt.Errorf("invalid UUID: %q", uuid)
515 for m, s := range dd.Schemas {
516 if s.UUIDPrefix == infix {
522 return "", fmt.Errorf("unrecognized type portion %q in UUID %q", infix, uuid)
527 func (c *Client) KindForUUID(uuid string) (string, error) {
528 dd, err := c.DiscoveryDocument()
532 model, err := c.modelForUUID(dd, uuid)
536 return "arvados#" + strings.ToLower(model[:1]) + model[1:], nil
539 func (c *Client) PathForUUID(method, uuid string) (string, error) {
540 dd, err := c.DiscoveryDocument()
544 model, err := c.modelForUUID(dd, uuid)
549 for r, rsc := range dd.Resources {
550 if rsc.Methods["get"].Response.Ref == model {
556 return "", fmt.Errorf("no resource for model: %q", model)
558 m, ok := dd.Resources[resource].Methods[method]
560 return "", fmt.Errorf("no method %q for resource %q", method, resource)
562 path := dd.BasePath + strings.Replace(m.Path, "{uuid}", uuid, -1)