1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: Apache-2.0
23 // A Client is an HTTP client with an API endpoint and a set of
24 // Arvados credentials.
26 // It offers methods for accessing individual Arvados APIs, and
27 // methods that implement common patterns like fetching multiple pages
28 // of results using List APIs.
30 // HTTP client used to make requests. If nil,
31 // DefaultSecureClient or InsecureHTTPClient will be used.
32 Client *http.Client `json:"-"`
34 // Hostname (or host:port) of Arvados API server.
37 // User authentication token.
40 // Accept unverified certificates. This works only if the
41 // Client field is nil: otherwise, it has no effect.
44 // Override keep service discovery with a list of base
45 // URIs. (Currently there are no Client methods for
46 // discovering keep services so this is just a convenience for
47 // callers who use a Client to initialize an
48 // arvadosclient.ArvadosClient.)
49 KeepServiceURIs []string `json:",omitempty"`
54 // The default http.Client used by a Client with Insecure==true and
56 var InsecureHTTPClient = &http.Client{
57 Transport: &http.Transport{
58 TLSClientConfig: &tls.Config{
59 InsecureSkipVerify: true}},
60 Timeout: 5 * time.Minute}
62 // The default http.Client used by a Client otherwise.
63 var DefaultSecureClient = &http.Client{
64 Timeout: 5 * time.Minute}
66 // NewClientFromEnv creates a new Client that uses the default HTTP
67 // client with the API endpoint and credentials given by the
68 // ARVADOS_API_* environment variables.
69 func NewClientFromEnv() *Client {
71 for _, s := range strings.Split(os.Getenv("ARVADOS_KEEP_SERVICES"), " ") {
74 } else if u, err := url.Parse(s); err != nil {
75 log.Printf("ARVADOS_KEEP_SERVICES: %q: %s", s, err)
76 } else if !u.IsAbs() {
77 log.Printf("ARVADOS_KEEP_SERVICES: %q: not an absolute URI", s)
79 svcs = append(svcs, s)
83 if s := strings.ToLower(os.Getenv("ARVADOS_API_HOST_INSECURE")); s == "1" || s == "yes" || s == "true" {
87 APIHost: os.Getenv("ARVADOS_API_HOST"),
88 AuthToken: os.Getenv("ARVADOS_API_TOKEN"),
90 KeepServiceURIs: svcs,
94 // Do adds authentication headers and then calls (*http.Client)Do().
95 func (c *Client) Do(req *http.Request) (*http.Response, error) {
96 if c.AuthToken != "" {
97 req.Header.Add("Authorization", "OAuth2 "+c.AuthToken)
99 return c.httpClient().Do(req)
102 // DoAndDecode performs req and unmarshals the response (which must be
103 // JSON) into dst. Use this instead of RequestAndDecode if you need
104 // more control of the http.Request object.
105 func (c *Client) DoAndDecode(dst interface{}, req *http.Request) error {
106 resp, err := c.Do(req)
110 defer resp.Body.Close()
111 buf, err := ioutil.ReadAll(resp.Body)
115 if resp.StatusCode != 200 {
116 return newTransactionError(req, resp, buf)
121 return json.Unmarshal(buf, dst)
124 // Convert an arbitrary struct to url.Values. For example,
126 // Foo{Bar: []int{1,2,3}, Baz: "waz"}
130 // url.Values{`bar`:`{"a":[1,2,3]}`,`Baz`:`waz`}
132 // params itself is returned if it is already an url.Values.
133 func anythingToValues(params interface{}) (url.Values, error) {
134 if v, ok := params.(url.Values); ok {
137 // TODO: Do this more efficiently, possibly using
138 // json.Decode/Encode, so the whole thing doesn't have to get
139 // encoded, decoded, and re-encoded.
140 j, err := json.Marshal(params)
144 var generic map[string]interface{}
145 err = json.Unmarshal(j, &generic)
149 urlValues := url.Values{}
150 for k, v := range generic {
151 if v, ok := v.(string); ok {
155 if v, ok := v.(float64); ok {
156 // Unmarshal decodes all numbers as float64,
157 // which can be written as 1.2345e4 in JSON,
158 // but this form is not accepted for ints in
159 // url params. If a number fits in an int64,
160 // encode it as int64 rather than float64.
161 if v, frac := math.Modf(v); frac == 0 && v <= math.MaxInt64 && v >= math.MinInt64 {
162 urlValues.Set(k, fmt.Sprintf("%d", int64(v)))
166 j, err := json.Marshal(v)
170 urlValues.Set(k, string(j))
172 return urlValues, nil
175 // RequestAndDecode performs an API request and unmarshals the
176 // response (which must be JSON) into dst. Method and body arguments
177 // are the same as for http.NewRequest(). The given path is added to
178 // the server's scheme/host/port to form the request URL. The given
179 // params are passed via POST form or query string.
181 // path must not contain a query string.
182 func (c *Client) RequestAndDecode(dst interface{}, method, path string, body io.Reader, params interface{}) error {
183 urlString := c.apiURL(path)
184 urlValues, err := anythingToValues(params)
188 if (method == "GET" || body != nil) && urlValues != nil {
189 // FIXME: what if params don't fit in URL
190 u, err := url.Parse(urlString)
194 u.RawQuery = urlValues.Encode()
195 urlString = u.String()
197 req, err := http.NewRequest(method, urlString, body)
201 req.Header.Set("Content-type", "application/x-www-form-urlencoded")
202 return c.DoAndDecode(dst, req)
205 func (c *Client) httpClient() *http.Client {
207 case c.Client != nil:
210 return InsecureHTTPClient
212 return DefaultSecureClient
216 func (c *Client) apiURL(path string) string {
217 return "https://" + c.APIHost + "/" + path
220 // DiscoveryDocument is the Arvados server's description of itself.
221 type DiscoveryDocument struct {
222 BasePath string `json:"basePath"`
223 DefaultCollectionReplication int `json:"defaultCollectionReplication"`
224 BlobSignatureTTL int64 `json:"blobSignatureTtl"`
225 Schemas map[string]Schema `json:"schemas"`
226 Resources map[string]Resource `json:"resources"`
229 type Resource struct {
230 Methods map[string]ResourceMethod `json:"methods"`
233 type ResourceMethod struct {
234 HTTPMethod string `json:"httpMethod"`
235 Path string `json:"path"`
236 Response MethodResponse `json:"response"`
239 type MethodResponse struct {
240 Ref string `json:"$ref"`
244 UUIDPrefix string `json:"uuidPrefix"`
247 // DiscoveryDocument returns a *DiscoveryDocument. The returned object
248 // should not be modified: the same object may be returned by
250 func (c *Client) DiscoveryDocument() (*DiscoveryDocument, error) {
254 var dd DiscoveryDocument
255 err := c.RequestAndDecode(&dd, "GET", "discovery/v1/apis/arvados/v1/rest", nil, nil)
263 var pdhRegexp = regexp.MustCompile(`^[0-9a-f]{32}\+\d+$`)
265 func (c *Client) modelForUUID(dd *DiscoveryDocument, uuid string) (string, error) {
266 if pdhRegexp.MatchString(uuid) {
267 return "Collection", nil
270 return "", fmt.Errorf("invalid UUID: %q", uuid)
274 for m, s := range dd.Schemas {
275 if s.UUIDPrefix == infix {
281 return "", fmt.Errorf("unrecognized type portion %q in UUID %q", infix, uuid)
286 func (c *Client) KindForUUID(uuid string) (string, error) {
287 dd, err := c.DiscoveryDocument()
291 model, err := c.modelForUUID(dd, uuid)
295 return "arvados#" + strings.ToLower(model[:1]) + model[1:], nil
298 func (c *Client) PathForUUID(method, uuid string) (string, error) {
299 dd, err := c.DiscoveryDocument()
303 model, err := c.modelForUUID(dd, uuid)
308 for r, rsc := range dd.Resources {
309 if rsc.Methods["get"].Response.Ref == model {
315 return "", fmt.Errorf("no resource for model: %q", model)
317 m, ok := dd.Resources[resource].Methods[method]
319 return "", fmt.Errorf("no method %q for resource %q", method, resource)
321 path := dd.BasePath + strings.Replace(m.Path, "{uuid}", uuid, -1)