1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: Apache-2.0
23 "git.arvados.org/arvados.git/sdk/go/httpserver"
26 // A Client is an HTTP client with an API endpoint and a set of
27 // Arvados credentials.
29 // It offers methods for accessing individual Arvados APIs, and
30 // methods that implement common patterns like fetching multiple pages
31 // of results using List APIs.
33 // HTTP client used to make requests. If nil,
34 // DefaultSecureClient or InsecureHTTPClient will be used.
35 Client *http.Client `json:"-"`
37 // Protocol scheme: "http", "https", or "" (https)
40 // Hostname (or host:port) of Arvados API server.
43 // User authentication token.
46 // Accept unverified certificates. This works only if the
47 // Client field is nil: otherwise, it has no effect.
50 // Override keep service discovery with a list of base
51 // URIs. (Currently there are no Client methods for
52 // discovering keep services so this is just a convenience for
53 // callers who use a Client to initialize an
54 // arvadosclient.ArvadosClient.)
55 KeepServiceURIs []string `json:",omitempty"`
57 // HTTP headers to add/override in outgoing requests.
58 SendHeader http.Header
60 // Timeout for requests. NewClientFromConfig and
61 // NewClientFromEnv return a Client with a default 5 minute
62 // timeout. To disable this timeout and rely on each
63 // http.Request's context deadline instead, set Timeout to
69 defaultRequestID string
72 // The default http.Client used by a Client with Insecure==true and
74 var InsecureHTTPClient = &http.Client{
75 Transport: &http.Transport{
76 TLSClientConfig: &tls.Config{
77 InsecureSkipVerify: true}}}
79 // The default http.Client used by a Client otherwise.
80 var DefaultSecureClient = &http.Client{}
82 // NewClientFromConfig creates a new Client that uses the endpoints in
85 // AuthToken is left empty for the caller to populate.
86 func NewClientFromConfig(cluster *Cluster) (*Client, error) {
87 ctrlURL := cluster.Services.Controller.ExternalURL
88 if ctrlURL.Host == "" {
89 return nil, fmt.Errorf("no host in config Services.Controller.ExternalURL: %v", ctrlURL)
92 Scheme: ctrlURL.Scheme,
93 APIHost: ctrlURL.Host,
94 Insecure: cluster.TLS.Insecure,
95 Timeout: 5 * time.Minute,
99 // NewClientFromEnv creates a new Client that uses the default HTTP
100 // client with the API endpoint and credentials given by the
101 // ARVADOS_API_* environment variables.
102 func NewClientFromEnv() *Client {
104 for _, s := range strings.Split(os.Getenv("ARVADOS_KEEP_SERVICES"), " ") {
107 } else if u, err := url.Parse(s); err != nil {
108 log.Printf("ARVADOS_KEEP_SERVICES: %q: %s", s, err)
109 } else if !u.IsAbs() {
110 log.Printf("ARVADOS_KEEP_SERVICES: %q: not an absolute URI", s)
112 svcs = append(svcs, s)
116 if s := strings.ToLower(os.Getenv("ARVADOS_API_HOST_INSECURE")); s == "1" || s == "yes" || s == "true" {
121 APIHost: os.Getenv("ARVADOS_API_HOST"),
122 AuthToken: os.Getenv("ARVADOS_API_TOKEN"),
124 KeepServiceURIs: svcs,
125 Timeout: 5 * time.Minute,
129 var reqIDGen = httpserver.IDGenerator{Prefix: "req-"}
131 // Do adds Authorization and X-Request-Id headers and then calls
132 // (*http.Client)Do().
133 func (c *Client) Do(req *http.Request) (*http.Response, error) {
134 if auth, _ := req.Context().Value(contextKeyAuthorization{}).(string); auth != "" {
135 req.Header.Add("Authorization", auth)
136 } else if c.AuthToken != "" {
137 req.Header.Add("Authorization", "OAuth2 "+c.AuthToken)
140 if req.Header.Get("X-Request-Id") == "" {
142 if ctxreqid, _ := req.Context().Value(contextKeyRequestID{}).(string); ctxreqid != "" {
144 } else if c.defaultRequestID != "" {
145 reqid = c.defaultRequestID
147 reqid = reqIDGen.Next()
149 if req.Header == nil {
150 req.Header = http.Header{"X-Request-Id": {reqid}}
152 req.Header.Set("X-Request-Id", reqid)
155 var cancel context.CancelFunc
158 ctx, cancel = context.WithDeadline(ctx, time.Now().Add(c.Timeout))
159 req = req.WithContext(ctx)
161 resp, err := c.httpClient().Do(req)
162 if err == nil && cancel != nil {
163 // We need to call cancel() eventually, but we can't
164 // use "defer cancel()" because the context has to
165 // stay alive until the caller has finished reading
166 // the response body.
167 resp.Body = cancelOnClose{ReadCloser: resp.Body, cancel: cancel}
168 } else if cancel != nil {
174 // cancelOnClose calls a provided CancelFunc when its wrapped
175 // ReadCloser's Close() method is called.
176 type cancelOnClose struct {
178 cancel context.CancelFunc
181 func (coc cancelOnClose) Close() error {
182 err := coc.ReadCloser.Close()
187 func isRedirectStatus(code int) bool {
189 case http.StatusMovedPermanently, http.StatusFound, http.StatusSeeOther, http.StatusTemporaryRedirect, http.StatusPermanentRedirect:
196 // DoAndDecode performs req and unmarshals the response (which must be
197 // JSON) into dst. Use this instead of RequestAndDecode if you need
198 // more control of the http.Request object.
200 // If the response status indicates an HTTP redirect, the Location
201 // header value is unmarshalled to dst as a RedirectLocation
203 func (c *Client) DoAndDecode(dst interface{}, req *http.Request) error {
204 resp, err := c.Do(req)
208 defer resp.Body.Close()
209 buf, err := ioutil.ReadAll(resp.Body)
214 case resp.StatusCode == http.StatusOK && dst == nil:
216 case resp.StatusCode == http.StatusOK:
217 return json.Unmarshal(buf, dst)
219 // If the caller uses a client with a custom CheckRedirect
220 // func, Do() might return the 3xx response instead of
222 case isRedirectStatus(resp.StatusCode) && dst == nil:
224 case isRedirectStatus(resp.StatusCode):
225 // Copy the redirect target URL to dst.RedirectLocation.
226 buf, err := json.Marshal(map[string]string{"redirect_location": resp.Header.Get("Location")})
230 return json.Unmarshal(buf, dst)
233 return newTransactionError(req, resp, buf)
237 // Convert an arbitrary struct to url.Values. For example,
239 // Foo{Bar: []int{1,2,3}, Baz: "waz"}
243 // url.Values{`bar`:`{"a":[1,2,3]}`,`Baz`:`waz`}
245 // params itself is returned if it is already an url.Values.
246 func anythingToValues(params interface{}) (url.Values, error) {
247 if v, ok := params.(url.Values); ok {
250 // TODO: Do this more efficiently, possibly using
251 // json.Decode/Encode, so the whole thing doesn't have to get
252 // encoded, decoded, and re-encoded.
253 j, err := json.Marshal(params)
257 var generic map[string]interface{}
258 dec := json.NewDecoder(bytes.NewBuffer(j))
260 err = dec.Decode(&generic)
264 urlValues := url.Values{}
265 for k, v := range generic {
266 if v, ok := v.(string); ok {
270 if v, ok := v.(json.Number); ok {
271 urlValues.Set(k, v.String())
274 if v, ok := v.(bool); ok {
276 urlValues.Set(k, "true")
278 // "foo=false", "foo=0", and "foo="
279 // are all taken as true strings, so
280 // don't send false values at all --
281 // rely on the default being false.
285 j, err := json.Marshal(v)
289 if bytes.Equal(j, []byte("null")) {
290 // don't add it to urlValues at all
293 urlValues.Set(k, string(j))
295 return urlValues, nil
298 // RequestAndDecode performs an API request and unmarshals the
299 // response (which must be JSON) into dst. Method and body arguments
300 // are the same as for http.NewRequest(). The given path is added to
301 // the server's scheme/host/port to form the request URL. The given
302 // params are passed via POST form or query string.
304 // path must not contain a query string.
305 func (c *Client) RequestAndDecode(dst interface{}, method, path string, body io.Reader, params interface{}) error {
306 return c.RequestAndDecodeContext(context.Background(), dst, method, path, body, params)
309 func (c *Client) RequestAndDecodeContext(ctx context.Context, dst interface{}, method, path string, body io.Reader, params interface{}) error {
310 if body, ok := body.(io.Closer); ok {
311 // Ensure body is closed even if we error out early
314 urlString := c.apiURL(path)
315 urlValues, err := anythingToValues(params)
319 if urlValues == nil {
321 } else if body != nil || ((method == "GET" || method == "HEAD") && len(urlValues.Encode()) < 1000) {
322 // Send params in query part of URL
323 u, err := url.Parse(urlString)
327 u.RawQuery = urlValues.Encode()
328 urlString = u.String()
330 body = strings.NewReader(urlValues.Encode())
332 req, err := http.NewRequest(method, urlString, body)
336 if (method == "GET" || method == "HEAD") && body != nil {
337 req.Header.Set("X-Http-Method-Override", method)
340 req = req.WithContext(ctx)
341 req.Header.Set("Content-type", "application/x-www-form-urlencoded")
342 for k, v := range c.SendHeader {
345 return c.DoAndDecode(dst, req)
348 type resource interface {
349 resourceName() string
352 // UpdateBody returns an io.Reader suitable for use as an http.Request
353 // Body for a create or update API call.
354 func (c *Client) UpdateBody(rsc resource) io.Reader {
355 j, err := json.Marshal(rsc)
357 // Return a reader that returns errors.
359 w.CloseWithError(err)
362 v := url.Values{rsc.resourceName(): {string(j)}}
363 return bytes.NewBufferString(v.Encode())
366 // WithRequestID returns a new shallow copy of c that sends the given
367 // X-Request-Id value (instead of a new randomly generated one) with
368 // each subsequent request that doesn't provide its own via context or
370 func (c *Client) WithRequestID(reqid string) *Client {
372 cc.defaultRequestID = reqid
376 func (c *Client) httpClient() *http.Client {
378 case c.Client != nil:
381 return InsecureHTTPClient
383 return DefaultSecureClient
387 func (c *Client) apiURL(path string) string {
392 return scheme + "://" + c.APIHost + "/" + path
395 // DiscoveryDocument is the Arvados server's description of itself.
396 type DiscoveryDocument struct {
397 BasePath string `json:"basePath"`
398 DefaultCollectionReplication int `json:"defaultCollectionReplication"`
399 BlobSignatureTTL int64 `json:"blobSignatureTtl"`
400 GitURL string `json:"gitUrl"`
401 Schemas map[string]Schema `json:"schemas"`
402 Resources map[string]Resource `json:"resources"`
405 type Resource struct {
406 Methods map[string]ResourceMethod `json:"methods"`
409 type ResourceMethod struct {
410 HTTPMethod string `json:"httpMethod"`
411 Path string `json:"path"`
412 Response MethodResponse `json:"response"`
415 type MethodResponse struct {
416 Ref string `json:"$ref"`
420 UUIDPrefix string `json:"uuidPrefix"`
423 // DiscoveryDocument returns a *DiscoveryDocument. The returned object
424 // should not be modified: the same object may be returned by
426 func (c *Client) DiscoveryDocument() (*DiscoveryDocument, error) {
430 var dd DiscoveryDocument
431 err := c.RequestAndDecode(&dd, "GET", "discovery/v1/apis/arvados/v1/rest", nil, nil)
439 var pdhRegexp = regexp.MustCompile(`^[0-9a-f]{32}\+\d+$`)
441 func (c *Client) modelForUUID(dd *DiscoveryDocument, uuid string) (string, error) {
442 if pdhRegexp.MatchString(uuid) {
443 return "Collection", nil
446 return "", fmt.Errorf("invalid UUID: %q", uuid)
450 for m, s := range dd.Schemas {
451 if s.UUIDPrefix == infix {
457 return "", fmt.Errorf("unrecognized type portion %q in UUID %q", infix, uuid)
462 func (c *Client) KindForUUID(uuid string) (string, error) {
463 dd, err := c.DiscoveryDocument()
467 model, err := c.modelForUUID(dd, uuid)
471 return "arvados#" + strings.ToLower(model[:1]) + model[1:], nil
474 func (c *Client) PathForUUID(method, uuid string) (string, error) {
475 dd, err := c.DiscoveryDocument()
479 model, err := c.modelForUUID(dd, uuid)
484 for r, rsc := range dd.Resources {
485 if rsc.Methods["get"].Response.Ref == model {
491 return "", fmt.Errorf("no resource for model: %q", model)
493 m, ok := dd.Resources[resource].Methods[method]
495 return "", fmt.Errorf("no method %q for resource %q", method, resource)
497 path := dd.BasePath + strings.Replace(m.Path, "{uuid}", uuid, -1)