1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: Apache-2.0
23 "git.curoverse.com/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
65 // The default http.Client used by a Client with Insecure==true and
67 var InsecureHTTPClient = &http.Client{
68 Transport: &http.Transport{
69 TLSClientConfig: &tls.Config{
70 InsecureSkipVerify: true}},
71 Timeout: 5 * time.Minute}
73 // The default http.Client used by a Client otherwise.
74 var DefaultSecureClient = &http.Client{
75 Timeout: 5 * time.Minute}
77 // NewClientFromConfig creates a new Client that uses the endpoints in
80 // AuthToken is left empty for the caller to populate.
81 func NewClientFromConfig(cluster *Cluster) (*Client, error) {
82 ctrlURL := cluster.Services.Controller.ExternalURL
83 if ctrlURL.Host == "" {
84 return nil, fmt.Errorf("no host in config Services.Controller.ExternalURL: %v", ctrlURL)
87 Scheme: ctrlURL.Scheme,
88 APIHost: ctrlURL.Host,
89 Insecure: cluster.TLS.Insecure,
93 // NewClientFromEnv creates a new Client that uses the default HTTP
94 // client with the API endpoint and credentials given by the
95 // ARVADOS_API_* environment variables.
96 func NewClientFromEnv() *Client {
98 for _, s := range strings.Split(os.Getenv("ARVADOS_KEEP_SERVICES"), " ") {
101 } else if u, err := url.Parse(s); err != nil {
102 log.Printf("ARVADOS_KEEP_SERVICES: %q: %s", s, err)
103 } else if !u.IsAbs() {
104 log.Printf("ARVADOS_KEEP_SERVICES: %q: not an absolute URI", s)
106 svcs = append(svcs, s)
110 if s := strings.ToLower(os.Getenv("ARVADOS_API_HOST_INSECURE")); s == "1" || s == "yes" || s == "true" {
115 APIHost: os.Getenv("ARVADOS_API_HOST"),
116 AuthToken: os.Getenv("ARVADOS_API_TOKEN"),
118 KeepServiceURIs: svcs,
122 var reqIDGen = httpserver.IDGenerator{Prefix: "req-"}
124 // Do adds Authorization and X-Request-Id headers and then calls
125 // (*http.Client)Do().
126 func (c *Client) Do(req *http.Request) (*http.Response, error) {
127 if auth, _ := req.Context().Value(contextKeyAuthorization{}).(string); auth != "" {
128 req.Header.Add("Authorization", auth)
129 } else if c.AuthToken != "" {
130 req.Header.Add("Authorization", "OAuth2 "+c.AuthToken)
133 if req.Header.Get("X-Request-Id") == "" {
134 reqid, _ := req.Context().Value(contextKeyRequestID{}).(string)
136 reqid, _ = c.context().Value(contextKeyRequestID{}).(string)
139 reqid = reqIDGen.Next()
141 if req.Header == nil {
142 req.Header = http.Header{"X-Request-Id": {reqid}}
144 req.Header.Set("X-Request-Id", reqid)
147 return c.httpClient().Do(req)
150 func isRedirectStatus(code int) bool {
152 case http.StatusMovedPermanently, http.StatusFound, http.StatusSeeOther, http.StatusTemporaryRedirect, http.StatusPermanentRedirect:
159 // DoAndDecode performs req and unmarshals the response (which must be
160 // JSON) into dst. Use this instead of RequestAndDecode if you need
161 // more control of the http.Request object.
163 // If the response status indicates an HTTP redirect, the Location
164 // header value is unmarshalled to dst as a RedirectLocation
166 func (c *Client) DoAndDecode(dst interface{}, req *http.Request) error {
167 resp, err := c.Do(req)
171 defer resp.Body.Close()
172 buf, err := ioutil.ReadAll(resp.Body)
177 case resp.StatusCode == http.StatusOK && dst == nil:
179 case resp.StatusCode == http.StatusOK:
180 return json.Unmarshal(buf, dst)
182 // If the caller uses a client with a custom CheckRedirect
183 // func, Do() might return the 3xx response instead of
185 case isRedirectStatus(resp.StatusCode) && dst == nil:
187 case isRedirectStatus(resp.StatusCode):
188 // Copy the redirect target URL to dst.RedirectLocation.
189 buf, err := json.Marshal(map[string]string{"RedirectLocation": resp.Header.Get("Location")})
193 return json.Unmarshal(buf, dst)
196 return newTransactionError(req, resp, buf)
200 // Convert an arbitrary struct to url.Values. For example,
202 // Foo{Bar: []int{1,2,3}, Baz: "waz"}
206 // url.Values{`bar`:`{"a":[1,2,3]}`,`Baz`:`waz`}
208 // params itself is returned if it is already an url.Values.
209 func anythingToValues(params interface{}) (url.Values, error) {
210 if v, ok := params.(url.Values); ok {
213 // TODO: Do this more efficiently, possibly using
214 // json.Decode/Encode, so the whole thing doesn't have to get
215 // encoded, decoded, and re-encoded.
216 j, err := json.Marshal(params)
220 var generic map[string]interface{}
221 dec := json.NewDecoder(bytes.NewBuffer(j))
223 err = dec.Decode(&generic)
227 urlValues := url.Values{}
228 for k, v := range generic {
229 if v, ok := v.(string); ok {
233 if v, ok := v.(json.Number); ok {
234 urlValues.Set(k, v.String())
237 if v, ok := v.(bool); ok {
239 urlValues.Set(k, "true")
241 // "foo=false", "foo=0", and "foo="
242 // are all taken as true strings, so
243 // don't send false values at all --
244 // rely on the default being false.
248 j, err := json.Marshal(v)
252 if bytes.Equal(j, []byte("null")) {
253 // don't add it to urlValues at all
256 urlValues.Set(k, string(j))
258 return urlValues, nil
261 // RequestAndDecode performs an API request and unmarshals the
262 // response (which must be JSON) into dst. Method and body arguments
263 // are the same as for http.NewRequest(). The given path is added to
264 // the server's scheme/host/port to form the request URL. The given
265 // params are passed via POST form or query string.
267 // path must not contain a query string.
268 func (c *Client) RequestAndDecode(dst interface{}, method, path string, body io.Reader, params interface{}) error {
269 return c.RequestAndDecodeContext(c.context(), dst, method, path, body, params)
272 func (c *Client) RequestAndDecodeContext(ctx context.Context, dst interface{}, method, path string, body io.Reader, params interface{}) error {
273 if body, ok := body.(io.Closer); ok {
274 // Ensure body is closed even if we error out early
277 urlString := c.apiURL(path)
278 urlValues, err := anythingToValues(params)
282 if urlValues == nil {
284 } else if body != nil || ((method == "GET" || method == "HEAD") && len(urlValues.Encode()) < 1000) {
285 // Send params in query part of URL
286 u, err := url.Parse(urlString)
290 u.RawQuery = urlValues.Encode()
291 urlString = u.String()
293 body = strings.NewReader(urlValues.Encode())
295 req, err := http.NewRequest(method, urlString, body)
299 if (method == "GET" || method == "HEAD") && body != nil {
300 req.Header.Set("X-Http-Method-Override", method)
303 req = req.WithContext(ctx)
304 req.Header.Set("Content-type", "application/x-www-form-urlencoded")
305 for k, v := range c.SendHeader {
308 return c.DoAndDecode(dst, req)
311 type resource interface {
312 resourceName() string
315 // UpdateBody returns an io.Reader suitable for use as an http.Request
316 // Body for a create or update API call.
317 func (c *Client) UpdateBody(rsc resource) io.Reader {
318 j, err := json.Marshal(rsc)
320 // Return a reader that returns errors.
322 w.CloseWithError(err)
325 v := url.Values{rsc.resourceName(): {string(j)}}
326 return bytes.NewBufferString(v.Encode())
329 // WithRequestID returns a new shallow copy of c that sends the given
330 // X-Request-Id value (instead of a new randomly generated one) with
331 // each subsequent request that doesn't provide its own via context or
333 func (c *Client) WithRequestID(reqid string) *Client {
335 cc.ctx = ContextWithRequestID(cc.context(), reqid)
339 func (c *Client) context() context.Context {
341 return context.Background()
346 func (c *Client) httpClient() *http.Client {
348 case c.Client != nil:
351 return InsecureHTTPClient
353 return DefaultSecureClient
357 func (c *Client) apiURL(path string) string {
362 return scheme + "://" + c.APIHost + "/" + path
365 // DiscoveryDocument is the Arvados server's description of itself.
366 type DiscoveryDocument struct {
367 BasePath string `json:"basePath"`
368 DefaultCollectionReplication int `json:"defaultCollectionReplication"`
369 BlobSignatureTTL int64 `json:"blobSignatureTtl"`
370 GitURL string `json:"gitUrl"`
371 Schemas map[string]Schema `json:"schemas"`
372 Resources map[string]Resource `json:"resources"`
375 type Resource struct {
376 Methods map[string]ResourceMethod `json:"methods"`
379 type ResourceMethod struct {
380 HTTPMethod string `json:"httpMethod"`
381 Path string `json:"path"`
382 Response MethodResponse `json:"response"`
385 type MethodResponse struct {
386 Ref string `json:"$ref"`
390 UUIDPrefix string `json:"uuidPrefix"`
393 // DiscoveryDocument returns a *DiscoveryDocument. The returned object
394 // should not be modified: the same object may be returned by
396 func (c *Client) DiscoveryDocument() (*DiscoveryDocument, error) {
400 var dd DiscoveryDocument
401 err := c.RequestAndDecode(&dd, "GET", "discovery/v1/apis/arvados/v1/rest", nil, nil)
409 var pdhRegexp = regexp.MustCompile(`^[0-9a-f]{32}\+\d+$`)
411 func (c *Client) modelForUUID(dd *DiscoveryDocument, uuid string) (string, error) {
412 if pdhRegexp.MatchString(uuid) {
413 return "Collection", nil
416 return "", fmt.Errorf("invalid UUID: %q", uuid)
420 for m, s := range dd.Schemas {
421 if s.UUIDPrefix == infix {
427 return "", fmt.Errorf("unrecognized type portion %q in UUID %q", infix, uuid)
432 func (c *Client) KindForUUID(uuid string) (string, error) {
433 dd, err := c.DiscoveryDocument()
437 model, err := c.modelForUUID(dd, uuid)
441 return "arvados#" + strings.ToLower(model[:1]) + model[1:], nil
444 func (c *Client) PathForUUID(method, uuid string) (string, error) {
445 dd, err := c.DiscoveryDocument()
449 model, err := c.modelForUUID(dd, uuid)
454 for r, rsc := range dd.Resources {
455 if rsc.Methods["get"].Response.Ref == model {
461 return "", fmt.Errorf("no resource for model: %q", model)
463 m, ok := dd.Resources[resource].Methods[method]
465 return "", fmt.Errorf("no method %q for resource %q", method, resource)
467 path := dd.BasePath + strings.Replace(m.Path, "{uuid}", uuid, -1)