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 // InsecureHTTPClient is the default http.Client used by a Client with
73 // Insecure==true and Client==nil.
74 var InsecureHTTPClient = &http.Client{
75 Transport: &http.Transport{
76 TLSClientConfig: &tls.Config{
77 InsecureSkipVerify: true}}}
79 // DefaultSecureClient is 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 // RequestAndDecodeContext does the same as RequestAndDecode, but with a context
310 func (c *Client) RequestAndDecodeContext(ctx context.Context, dst interface{}, method, path string, body io.Reader, params interface{}) error {
311 if body, ok := body.(io.Closer); ok {
312 // Ensure body is closed even if we error out early
315 urlString := c.apiURL(path)
316 urlValues, err := anythingToValues(params)
320 if urlValues == nil {
322 } else if body != nil || ((method == "GET" || method == "HEAD") && len(urlValues.Encode()) < 1000) {
323 // Send params in query part of URL
324 u, err := url.Parse(urlString)
328 u.RawQuery = urlValues.Encode()
329 urlString = u.String()
331 body = strings.NewReader(urlValues.Encode())
333 req, err := http.NewRequest(method, urlString, body)
337 if (method == "GET" || method == "HEAD") && body != nil {
338 req.Header.Set("X-Http-Method-Override", method)
341 req = req.WithContext(ctx)
342 req.Header.Set("Content-type", "application/x-www-form-urlencoded")
343 for k, v := range c.SendHeader {
346 return c.DoAndDecode(dst, req)
349 type resource interface {
350 resourceName() string
353 // UpdateBody returns an io.Reader suitable for use as an http.Request
354 // Body for a create or update API call.
355 func (c *Client) UpdateBody(rsc resource) io.Reader {
356 j, err := json.Marshal(rsc)
358 // Return a reader that returns errors.
360 w.CloseWithError(err)
363 v := url.Values{rsc.resourceName(): {string(j)}}
364 return bytes.NewBufferString(v.Encode())
367 // WithRequestID returns a new shallow copy of c that sends the given
368 // X-Request-Id value (instead of a new randomly generated one) with
369 // each subsequent request that doesn't provide its own via context or
371 func (c *Client) WithRequestID(reqid string) *Client {
373 cc.defaultRequestID = reqid
377 func (c *Client) httpClient() *http.Client {
379 case c.Client != nil:
382 return InsecureHTTPClient
384 return DefaultSecureClient
388 func (c *Client) apiURL(path string) string {
393 return scheme + "://" + c.APIHost + "/" + path
396 // DiscoveryDocument is the Arvados server's description of itself.
397 type DiscoveryDocument struct {
398 BasePath string `json:"basePath"`
399 DefaultCollectionReplication int `json:"defaultCollectionReplication"`
400 BlobSignatureTTL int64 `json:"blobSignatureTtl"`
401 GitURL string `json:"gitUrl"`
402 Schemas map[string]Schema `json:"schemas"`
403 Resources map[string]Resource `json:"resources"`
406 type Resource struct {
407 Methods map[string]ResourceMethod `json:"methods"`
410 type ResourceMethod struct {
411 HTTPMethod string `json:"httpMethod"`
412 Path string `json:"path"`
413 Response MethodResponse `json:"response"`
416 type MethodResponse struct {
417 Ref string `json:"$ref"`
421 UUIDPrefix string `json:"uuidPrefix"`
424 // DiscoveryDocument returns a *DiscoveryDocument. The returned object
425 // should not be modified: the same object may be returned by
427 func (c *Client) DiscoveryDocument() (*DiscoveryDocument, error) {
431 var dd DiscoveryDocument
432 err := c.RequestAndDecode(&dd, "GET", "discovery/v1/apis/arvados/v1/rest", nil, nil)
440 var pdhRegexp = regexp.MustCompile(`^[0-9a-f]{32}\+\d+$`)
442 func (c *Client) modelForUUID(dd *DiscoveryDocument, uuid string) (string, error) {
443 if pdhRegexp.MatchString(uuid) {
444 return "Collection", nil
447 return "", fmt.Errorf("invalid UUID: %q", uuid)
451 for m, s := range dd.Schemas {
452 if s.UUIDPrefix == infix {
458 return "", fmt.Errorf("unrecognized type portion %q in UUID %q", infix, uuid)
463 func (c *Client) KindForUUID(uuid string) (string, error) {
464 dd, err := c.DiscoveryDocument()
468 model, err := c.modelForUUID(dd, uuid)
472 return "arvados#" + strings.ToLower(model[:1]) + model[1:], nil
475 func (c *Client) PathForUUID(method, uuid string) (string, error) {
476 dd, err := c.DiscoveryDocument()
480 model, err := c.modelForUUID(dd, uuid)
485 for r, rsc := range dd.Resources {
486 if rsc.Methods["get"].Response.Ref == model {
492 return "", fmt.Errorf("no resource for model: %q", model)
494 m, ok := dd.Resources[resource].Methods[method]
496 return "", fmt.Errorf("no method %q for resource %q", method, resource)
498 path := dd.BasePath + strings.Replace(m.Path, "{uuid}", uuid, -1)