1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: Apache-2.0
24 "git.arvados.org/arvados.git/sdk/go/httpserver"
27 // A Client is an HTTP client with an API endpoint and a set of
28 // Arvados credentials.
30 // It offers methods for accessing individual Arvados APIs, and
31 // methods that implement common patterns like fetching multiple pages
32 // of results using List APIs.
34 // HTTP client used to make requests. If nil,
35 // DefaultSecureClient or InsecureHTTPClient will be used.
36 Client *http.Client `json:"-"`
38 // Protocol scheme: "http", "https", or "" (https)
41 // Hostname (or host:port) of Arvados API server.
44 // User authentication token.
47 // Accept unverified certificates. This works only if the
48 // Client field is nil: otherwise, it has no effect.
51 // Override keep service discovery with a list of base
52 // URIs. (Currently there are no Client methods for
53 // discovering keep services so this is just a convenience for
54 // callers who use a Client to initialize an
55 // arvadosclient.ArvadosClient.)
56 KeepServiceURIs []string `json:",omitempty"`
58 // HTTP headers to add/override in outgoing requests.
59 SendHeader http.Header
61 // Timeout for requests. NewClientFromConfig and
62 // NewClientFromEnv return a Client with a default 5 minute
63 // timeout. To disable this timeout and rely on each
64 // http.Request's context deadline instead, set Timeout to
70 defaultRequestID string
72 // APIHost and AuthToken were loaded from ARVADOS_* env vars
73 // (used to customize "no host/token" error messages)
77 // InsecureHTTPClient is the default http.Client used by a Client with
78 // Insecure==true and Client==nil.
79 var InsecureHTTPClient = &http.Client{
80 Transport: &http.Transport{
81 TLSClientConfig: &tls.Config{
82 InsecureSkipVerify: true}}}
84 // DefaultSecureClient is the default http.Client used by a Client otherwise.
85 var DefaultSecureClient = &http.Client{}
87 // NewClientFromConfig creates a new Client that uses the endpoints in
90 // AuthToken is left empty for the caller to populate.
91 func NewClientFromConfig(cluster *Cluster) (*Client, error) {
92 ctrlURL := cluster.Services.Controller.ExternalURL
93 if ctrlURL.Host == "" {
94 return nil, fmt.Errorf("no host in config Services.Controller.ExternalURL: %v", ctrlURL)
97 Scheme: ctrlURL.Scheme,
98 APIHost: ctrlURL.Host,
99 Insecure: cluster.TLS.Insecure,
100 Timeout: 5 * time.Minute,
104 // NewClientFromEnv creates a new Client that uses the default HTTP
105 // client with the API endpoint and credentials given by the
106 // ARVADOS_API_* environment variables.
107 func NewClientFromEnv() *Client {
109 for _, s := range strings.Split(os.Getenv("ARVADOS_KEEP_SERVICES"), " ") {
112 } else if u, err := url.Parse(s); err != nil {
113 log.Printf("ARVADOS_KEEP_SERVICES: %q: %s", s, err)
114 } else if !u.IsAbs() {
115 log.Printf("ARVADOS_KEEP_SERVICES: %q: not an absolute URI", s)
117 svcs = append(svcs, s)
121 if s := strings.ToLower(os.Getenv("ARVADOS_API_HOST_INSECURE")); s == "1" || s == "yes" || s == "true" {
126 APIHost: os.Getenv("ARVADOS_API_HOST"),
127 AuthToken: os.Getenv("ARVADOS_API_TOKEN"),
129 KeepServiceURIs: svcs,
130 Timeout: 5 * time.Minute,
135 var reqIDGen = httpserver.IDGenerator{Prefix: "req-"}
137 // Do adds Authorization and X-Request-Id headers and then calls
138 // (*http.Client)Do().
139 func (c *Client) Do(req *http.Request) (*http.Response, error) {
140 if auth, _ := req.Context().Value(contextKeyAuthorization{}).(string); auth != "" {
141 req.Header.Add("Authorization", auth)
142 } else if c.AuthToken != "" {
143 req.Header.Add("Authorization", "OAuth2 "+c.AuthToken)
146 if req.Header.Get("X-Request-Id") == "" {
148 if ctxreqid, _ := req.Context().Value(contextKeyRequestID{}).(string); ctxreqid != "" {
150 } else if c.defaultRequestID != "" {
151 reqid = c.defaultRequestID
153 reqid = reqIDGen.Next()
155 if req.Header == nil {
156 req.Header = http.Header{"X-Request-Id": {reqid}}
158 req.Header.Set("X-Request-Id", reqid)
161 var cancel context.CancelFunc
164 ctx, cancel = context.WithDeadline(ctx, time.Now().Add(c.Timeout))
165 req = req.WithContext(ctx)
167 resp, err := c.httpClient().Do(req)
168 if err == nil && cancel != nil {
169 // We need to call cancel() eventually, but we can't
170 // use "defer cancel()" because the context has to
171 // stay alive until the caller has finished reading
172 // the response body.
173 resp.Body = cancelOnClose{ReadCloser: resp.Body, cancel: cancel}
174 } else if cancel != nil {
180 // cancelOnClose calls a provided CancelFunc when its wrapped
181 // ReadCloser's Close() method is called.
182 type cancelOnClose struct {
184 cancel context.CancelFunc
187 func (coc cancelOnClose) Close() error {
188 err := coc.ReadCloser.Close()
193 func isRedirectStatus(code int) bool {
195 case http.StatusMovedPermanently, http.StatusFound, http.StatusSeeOther, http.StatusTemporaryRedirect, http.StatusPermanentRedirect:
202 // DoAndDecode performs req and unmarshals the response (which must be
203 // JSON) into dst. Use this instead of RequestAndDecode if you need
204 // more control of the http.Request object.
206 // If the response status indicates an HTTP redirect, the Location
207 // header value is unmarshalled to dst as a RedirectLocation
209 func (c *Client) DoAndDecode(dst interface{}, req *http.Request) error {
210 resp, err := c.Do(req)
214 defer resp.Body.Close()
215 buf, err := ioutil.ReadAll(resp.Body)
220 case resp.StatusCode == http.StatusOK && dst == nil:
222 case resp.StatusCode == http.StatusOK:
223 return json.Unmarshal(buf, dst)
225 // If the caller uses a client with a custom CheckRedirect
226 // func, Do() might return the 3xx response instead of
228 case isRedirectStatus(resp.StatusCode) && dst == nil:
230 case isRedirectStatus(resp.StatusCode):
231 // Copy the redirect target URL to dst.RedirectLocation.
232 buf, err := json.Marshal(map[string]string{"redirect_location": resp.Header.Get("Location")})
236 return json.Unmarshal(buf, dst)
239 return newTransactionError(req, resp, buf)
243 // Convert an arbitrary struct to url.Values. For example,
245 // Foo{Bar: []int{1,2,3}, Baz: "waz"}
249 // url.Values{`bar`:`{"a":[1,2,3]}`,`Baz`:`waz`}
251 // params itself is returned if it is already an url.Values.
252 func anythingToValues(params interface{}) (url.Values, error) {
253 if v, ok := params.(url.Values); ok {
256 // TODO: Do this more efficiently, possibly using
257 // json.Decode/Encode, so the whole thing doesn't have to get
258 // encoded, decoded, and re-encoded.
259 j, err := json.Marshal(params)
263 var generic map[string]interface{}
264 dec := json.NewDecoder(bytes.NewBuffer(j))
266 err = dec.Decode(&generic)
270 urlValues := url.Values{}
271 for k, v := range generic {
272 if v, ok := v.(string); ok {
276 if v, ok := v.(json.Number); ok {
277 urlValues.Set(k, v.String())
280 if v, ok := v.(bool); ok {
282 urlValues.Set(k, "true")
284 // "foo=false", "foo=0", and "foo="
285 // are all taken as true strings, so
286 // don't send false values at all --
287 // rely on the default being false.
291 j, err := json.Marshal(v)
295 if bytes.Equal(j, []byte("null")) {
296 // don't add it to urlValues at all
299 urlValues.Set(k, string(j))
301 return urlValues, nil
304 // RequestAndDecode performs an API request and unmarshals the
305 // response (which must be JSON) into dst. Method and body arguments
306 // are the same as for http.NewRequest(). The given path is added to
307 // the server's scheme/host/port to form the request URL. The given
308 // params are passed via POST form or query string.
310 // path must not contain a query string.
311 func (c *Client) RequestAndDecode(dst interface{}, method, path string, body io.Reader, params interface{}) error {
312 return c.RequestAndDecodeContext(context.Background(), dst, method, path, body, params)
315 // RequestAndDecodeContext does the same as RequestAndDecode, but with a context
316 func (c *Client) RequestAndDecodeContext(ctx context.Context, dst interface{}, method, path string, body io.Reader, params interface{}) error {
317 if body, ok := body.(io.Closer); ok {
318 // Ensure body is closed even if we error out early
323 return errors.New("ARVADOS_API_HOST and/or ARVADOS_API_TOKEN environment variables are not set")
325 return errors.New("arvados.Client cannot perform request: APIHost is not set")
327 urlString := c.apiURL(path)
328 urlValues, err := anythingToValues(params)
332 if urlValues == nil {
334 } else if body != nil || ((method == "GET" || method == "HEAD") && len(urlValues.Encode()) < 1000) {
335 // Send params in query part of URL
336 u, err := url.Parse(urlString)
340 u.RawQuery = urlValues.Encode()
341 urlString = u.String()
343 body = strings.NewReader(urlValues.Encode())
345 req, err := http.NewRequest(method, urlString, body)
349 if (method == "GET" || method == "HEAD") && body != nil {
350 req.Header.Set("X-Http-Method-Override", method)
353 req = req.WithContext(ctx)
354 req.Header.Set("Content-type", "application/x-www-form-urlencoded")
355 for k, v := range c.SendHeader {
358 return c.DoAndDecode(dst, req)
361 type resource interface {
362 resourceName() string
365 // UpdateBody returns an io.Reader suitable for use as an http.Request
366 // Body for a create or update API call.
367 func (c *Client) UpdateBody(rsc resource) io.Reader {
368 j, err := json.Marshal(rsc)
370 // Return a reader that returns errors.
372 w.CloseWithError(err)
375 v := url.Values{rsc.resourceName(): {string(j)}}
376 return bytes.NewBufferString(v.Encode())
379 // WithRequestID returns a new shallow copy of c that sends the given
380 // X-Request-Id value (instead of a new randomly generated one) with
381 // each subsequent request that doesn't provide its own via context or
383 func (c *Client) WithRequestID(reqid string) *Client {
385 cc.defaultRequestID = reqid
389 func (c *Client) httpClient() *http.Client {
391 case c.Client != nil:
394 return InsecureHTTPClient
396 return DefaultSecureClient
400 func (c *Client) apiURL(path string) string {
405 return scheme + "://" + c.APIHost + "/" + path
408 // DiscoveryDocument is the Arvados server's description of itself.
409 type DiscoveryDocument struct {
410 BasePath string `json:"basePath"`
411 DefaultCollectionReplication int `json:"defaultCollectionReplication"`
412 BlobSignatureTTL int64 `json:"blobSignatureTtl"`
413 GitURL string `json:"gitUrl"`
414 Schemas map[string]Schema `json:"schemas"`
415 Resources map[string]Resource `json:"resources"`
418 type Resource struct {
419 Methods map[string]ResourceMethod `json:"methods"`
422 type ResourceMethod struct {
423 HTTPMethod string `json:"httpMethod"`
424 Path string `json:"path"`
425 Response MethodResponse `json:"response"`
428 type MethodResponse struct {
429 Ref string `json:"$ref"`
433 UUIDPrefix string `json:"uuidPrefix"`
436 // DiscoveryDocument returns a *DiscoveryDocument. The returned object
437 // should not be modified: the same object may be returned by
439 func (c *Client) DiscoveryDocument() (*DiscoveryDocument, error) {
443 var dd DiscoveryDocument
444 err := c.RequestAndDecode(&dd, "GET", "discovery/v1/apis/arvados/v1/rest", nil, nil)
452 var pdhRegexp = regexp.MustCompile(`^[0-9a-f]{32}\+\d+$`)
454 func (c *Client) modelForUUID(dd *DiscoveryDocument, uuid string) (string, error) {
455 if pdhRegexp.MatchString(uuid) {
456 return "Collection", nil
459 return "", fmt.Errorf("invalid UUID: %q", uuid)
463 for m, s := range dd.Schemas {
464 if s.UUIDPrefix == infix {
470 return "", fmt.Errorf("unrecognized type portion %q in UUID %q", infix, uuid)
475 func (c *Client) KindForUUID(uuid string) (string, error) {
476 dd, err := c.DiscoveryDocument()
480 model, err := c.modelForUUID(dd, uuid)
484 return "arvados#" + strings.ToLower(model[:1]) + model[1:], nil
487 func (c *Client) PathForUUID(method, uuid string) (string, error) {
488 dd, err := c.DiscoveryDocument()
492 model, err := c.modelForUUID(dd, uuid)
497 for r, rsc := range dd.Resources {
498 if rsc.Methods["get"].Response.Ref == model {
504 return "", fmt.Errorf("no resource for model: %q", model)
506 m, ok := dd.Resources[resource].Methods[method]
508 return "", fmt.Errorf("no method %q for resource %q", method, resource)
510 path := dd.BasePath + strings.Replace(m.Path, "{uuid}", uuid, -1)