1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: Apache-2.0
24 // A Client is an HTTP client with an API endpoint and a set of
25 // Arvados credentials.
27 // It offers methods for accessing individual Arvados APIs, and
28 // methods that implement common patterns like fetching multiple pages
29 // of results using List APIs.
31 // HTTP client used to make requests. If nil,
32 // DefaultSecureClient or InsecureHTTPClient will be used.
33 Client *http.Client `json:"-"`
35 // Hostname (or host:port) of Arvados API server.
38 // User authentication token.
41 // Accept unverified certificates. This works only if the
42 // Client field is nil: otherwise, it has no effect.
45 // Override keep service discovery with a list of base
46 // URIs. (Currently there are no Client methods for
47 // discovering keep services so this is just a convenience for
48 // callers who use a Client to initialize an
49 // arvadosclient.ArvadosClient.)
50 KeepServiceURIs []string `json:",omitempty"`
55 // The default http.Client used by a Client with Insecure==true and
57 var InsecureHTTPClient = &http.Client{
58 Transport: &http.Transport{
59 TLSClientConfig: &tls.Config{
60 InsecureSkipVerify: true}},
61 Timeout: 5 * time.Minute}
63 // The default http.Client used by a Client otherwise.
64 var DefaultSecureClient = &http.Client{
65 Timeout: 5 * time.Minute}
67 // NewClientFromEnv creates a new Client that uses the default HTTP
68 // client with the API endpoint and credentials given by the
69 // ARVADOS_API_* environment variables.
70 func NewClientFromEnv() *Client {
72 for _, s := range strings.Split(os.Getenv("ARVADOS_KEEP_SERVICES"), " ") {
75 } else if u, err := url.Parse(s); err != nil {
76 log.Printf("ARVADOS_KEEP_SERVICES: %q: %s", s, err)
77 } else if !u.IsAbs() {
78 log.Printf("ARVADOS_KEEP_SERVICES: %q: not an absolute URI", s)
80 svcs = append(svcs, s)
84 if s := strings.ToLower(os.Getenv("ARVADOS_API_HOST_INSECURE")); s == "1" || s == "yes" || s == "true" {
88 APIHost: os.Getenv("ARVADOS_API_HOST"),
89 AuthToken: os.Getenv("ARVADOS_API_TOKEN"),
91 KeepServiceURIs: svcs,
95 // Do adds authentication headers and then calls (*http.Client)Do().
96 func (c *Client) Do(req *http.Request) (*http.Response, error) {
97 if c.AuthToken != "" {
98 req.Header.Add("Authorization", "OAuth2 "+c.AuthToken)
100 return c.httpClient().Do(req)
103 // DoAndDecode performs req and unmarshals the response (which must be
104 // JSON) into dst. Use this instead of RequestAndDecode if you need
105 // more control of the http.Request object.
106 func (c *Client) DoAndDecode(dst interface{}, req *http.Request) error {
107 resp, err := c.Do(req)
111 defer resp.Body.Close()
112 buf, err := ioutil.ReadAll(resp.Body)
116 if resp.StatusCode != 200 {
117 return newTransactionError(req, resp, buf)
122 return json.Unmarshal(buf, dst)
125 // Convert an arbitrary struct to url.Values. For example,
127 // Foo{Bar: []int{1,2,3}, Baz: "waz"}
131 // url.Values{`bar`:`{"a":[1,2,3]}`,`Baz`:`waz`}
133 // params itself is returned if it is already an url.Values.
134 func anythingToValues(params interface{}) (url.Values, error) {
135 if v, ok := params.(url.Values); ok {
138 // TODO: Do this more efficiently, possibly using
139 // json.Decode/Encode, so the whole thing doesn't have to get
140 // encoded, decoded, and re-encoded.
141 j, err := json.Marshal(params)
145 var generic map[string]interface{}
146 err = json.Unmarshal(j, &generic)
150 urlValues := url.Values{}
151 for k, v := range generic {
152 if v, ok := v.(string); ok {
156 if v, ok := v.(float64); ok {
157 // Unmarshal decodes all numbers as float64,
158 // which can be written as 1.2345e4 in JSON,
159 // but this form is not accepted for ints in
160 // url params. If a number fits in an int64,
161 // encode it as int64 rather than float64.
162 if v, frac := math.Modf(v); frac == 0 && v <= math.MaxInt64 && v >= math.MinInt64 {
163 urlValues.Set(k, fmt.Sprintf("%d", int64(v)))
167 j, err := json.Marshal(v)
171 urlValues.Set(k, string(j))
173 return urlValues, nil
176 // RequestAndDecode performs an API request and unmarshals the
177 // response (which must be JSON) into dst. Method and body arguments
178 // are the same as for http.NewRequest(). The given path is added to
179 // the server's scheme/host/port to form the request URL. The given
180 // params are passed via POST form or query string.
182 // path must not contain a query string.
183 func (c *Client) RequestAndDecode(dst interface{}, method, path string, body io.Reader, params interface{}) error {
184 if body, ok := body.(io.Closer); ok {
185 // Ensure body is closed even if we error out early
188 urlString := c.apiURL(path)
189 urlValues, err := anythingToValues(params)
193 if (method == "GET" || body != nil) && urlValues != nil {
194 // FIXME: what if params don't fit in URL
195 u, err := url.Parse(urlString)
199 u.RawQuery = urlValues.Encode()
200 urlString = u.String()
202 req, err := http.NewRequest(method, urlString, body)
206 req.Header.Set("Content-type", "application/x-www-form-urlencoded")
207 return c.DoAndDecode(dst, req)
210 type resource interface {
211 resourceName() string
214 // UpdateBody returns an io.Reader suitable for use as an http.Request
215 // Body for a create or update API call.
216 func (c *Client) UpdateBody(rsc resource) io.Reader {
217 j, err := json.Marshal(rsc)
219 // Return a reader that returns errors.
221 w.CloseWithError(err)
224 v := url.Values{rsc.resourceName(): {string(j)}}
225 return bytes.NewBufferString(v.Encode())
228 func (c *Client) httpClient() *http.Client {
230 case c.Client != nil:
233 return InsecureHTTPClient
235 return DefaultSecureClient
239 func (c *Client) apiURL(path string) string {
240 return "https://" + c.APIHost + "/" + path
243 // DiscoveryDocument is the Arvados server's description of itself.
244 type DiscoveryDocument struct {
245 BasePath string `json:"basePath"`
246 DefaultCollectionReplication int `json:"defaultCollectionReplication"`
247 BlobSignatureTTL int64 `json:"blobSignatureTtl"`
248 GitURL string `json:"gitUrl"`
249 Schemas map[string]Schema `json:"schemas"`
250 Resources map[string]Resource `json:"resources"`
253 type Resource struct {
254 Methods map[string]ResourceMethod `json:"methods"`
257 type ResourceMethod struct {
258 HTTPMethod string `json:"httpMethod"`
259 Path string `json:"path"`
260 Response MethodResponse `json:"response"`
263 type MethodResponse struct {
264 Ref string `json:"$ref"`
268 UUIDPrefix string `json:"uuidPrefix"`
271 // DiscoveryDocument returns a *DiscoveryDocument. The returned object
272 // should not be modified: the same object may be returned by
274 func (c *Client) DiscoveryDocument() (*DiscoveryDocument, error) {
278 var dd DiscoveryDocument
279 err := c.RequestAndDecode(&dd, "GET", "discovery/v1/apis/arvados/v1/rest", nil, nil)
287 var pdhRegexp = regexp.MustCompile(`^[0-9a-f]{32}\+\d+$`)
289 func (c *Client) modelForUUID(dd *DiscoveryDocument, uuid string) (string, error) {
290 if pdhRegexp.MatchString(uuid) {
291 return "Collection", nil
294 return "", fmt.Errorf("invalid UUID: %q", uuid)
298 for m, s := range dd.Schemas {
299 if s.UUIDPrefix == infix {
305 return "", fmt.Errorf("unrecognized type portion %q in UUID %q", infix, uuid)
310 func (c *Client) KindForUUID(uuid string) (string, error) {
311 dd, err := c.DiscoveryDocument()
315 model, err := c.modelForUUID(dd, uuid)
319 return "arvados#" + strings.ToLower(model[:1]) + model[1:], nil
322 func (c *Client) PathForUUID(method, uuid string) (string, error) {
323 dd, err := c.DiscoveryDocument()
327 model, err := c.modelForUUID(dd, uuid)
332 for r, rsc := range dd.Resources {
333 if rsc.Methods["get"].Response.Ref == model {
339 return "", fmt.Errorf("no resource for model: %q", model)
341 m, ok := dd.Resources[resource].Methods[method]
343 return "", fmt.Errorf("no method %q for resource %q", method, resource)
345 path := dd.BasePath + strings.Replace(m.Path, "{uuid}", uuid, -1)