1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: Apache-2.0
24 "git.curoverse.com/arvados.git/sdk/go/httpserver"
27 // A Client is an HTTP client with an API endpoint and a set of
28 // Arvados credentials.
30 // It offers methods for accessing individual Arvados APIs, and
31 // methods that implement common patterns like fetching multiple pages
32 // of results using List APIs.
34 // HTTP client used to make requests. If nil,
35 // DefaultSecureClient or InsecureHTTPClient will be used.
36 Client *http.Client `json:"-"`
38 // Hostname (or host:port) of Arvados API server.
41 // User authentication token.
44 // Accept unverified certificates. This works only if the
45 // Client field is nil: otherwise, it has no effect.
48 // Override keep service discovery with a list of base
49 // URIs. (Currently there are no Client methods for
50 // discovering keep services so this is just a convenience for
51 // callers who use a Client to initialize an
52 // arvadosclient.ArvadosClient.)
53 KeepServiceURIs []string `json:",omitempty"`
60 // The default http.Client used by a Client with Insecure==true and
62 var InsecureHTTPClient = &http.Client{
63 Transport: &http.Transport{
64 TLSClientConfig: &tls.Config{
65 InsecureSkipVerify: true}},
66 Timeout: 5 * time.Minute}
68 // The default http.Client used by a Client otherwise.
69 var DefaultSecureClient = &http.Client{
70 Timeout: 5 * time.Minute}
72 // NewClientFromEnv creates a new Client that uses the default HTTP
73 // client with the API endpoint and credentials given by the
74 // ARVADOS_API_* environment variables.
75 func NewClientFromEnv() *Client {
77 for _, s := range strings.Split(os.Getenv("ARVADOS_KEEP_SERVICES"), " ") {
80 } else if u, err := url.Parse(s); err != nil {
81 log.Printf("ARVADOS_KEEP_SERVICES: %q: %s", s, err)
82 } else if !u.IsAbs() {
83 log.Printf("ARVADOS_KEEP_SERVICES: %q: not an absolute URI", s)
85 svcs = append(svcs, s)
89 if s := strings.ToLower(os.Getenv("ARVADOS_API_HOST_INSECURE")); s == "1" || s == "yes" || s == "true" {
93 APIHost: os.Getenv("ARVADOS_API_HOST"),
94 AuthToken: os.Getenv("ARVADOS_API_TOKEN"),
96 KeepServiceURIs: svcs,
100 var reqIDGen = httpserver.IDGenerator{Prefix: "req-"}
102 // Do adds Authorization and X-Request-Id headers and then calls
103 // (*http.Client)Do().
104 func (c *Client) Do(req *http.Request) (*http.Response, error) {
105 if c.AuthToken != "" {
106 req.Header.Add("Authorization", "OAuth2 "+c.AuthToken)
109 if req.Header.Get("X-Request-Id") == "" {
110 reqid, _ := c.context().Value(contextKeyRequestID).(string)
112 reqid = reqIDGen.Next()
114 if req.Header == nil {
115 req.Header = http.Header{"X-Request-Id": {reqid}}
117 req.Header.Set("X-Request-Id", reqid)
120 return c.httpClient().Do(req)
123 // DoAndDecode performs req and unmarshals the response (which must be
124 // JSON) into dst. Use this instead of RequestAndDecode if you need
125 // more control of the http.Request object.
126 func (c *Client) DoAndDecode(dst interface{}, req *http.Request) error {
127 resp, err := c.Do(req)
131 defer resp.Body.Close()
132 buf, err := ioutil.ReadAll(resp.Body)
136 if resp.StatusCode != 200 {
137 return newTransactionError(req, resp, buf)
142 return json.Unmarshal(buf, dst)
145 // Convert an arbitrary struct to url.Values. For example,
147 // Foo{Bar: []int{1,2,3}, Baz: "waz"}
151 // url.Values{`bar`:`{"a":[1,2,3]}`,`Baz`:`waz`}
153 // params itself is returned if it is already an url.Values.
154 func anythingToValues(params interface{}) (url.Values, error) {
155 if v, ok := params.(url.Values); ok {
158 // TODO: Do this more efficiently, possibly using
159 // json.Decode/Encode, so the whole thing doesn't have to get
160 // encoded, decoded, and re-encoded.
161 j, err := json.Marshal(params)
165 var generic map[string]interface{}
166 err = json.Unmarshal(j, &generic)
170 urlValues := url.Values{}
171 for k, v := range generic {
172 if v, ok := v.(string); ok {
176 if v, ok := v.(float64); ok {
177 // Unmarshal decodes all numbers as float64,
178 // which can be written as 1.2345e4 in JSON,
179 // but this form is not accepted for ints in
180 // url params. If a number fits in an int64,
181 // encode it as int64 rather than float64.
182 if v, frac := math.Modf(v); frac == 0 && v <= math.MaxInt64 && v >= math.MinInt64 {
183 urlValues.Set(k, fmt.Sprintf("%d", int64(v)))
187 j, err := json.Marshal(v)
191 urlValues.Set(k, string(j))
193 return urlValues, nil
196 // RequestAndDecode performs an API request and unmarshals the
197 // response (which must be JSON) into dst. Method and body arguments
198 // are the same as for http.NewRequest(). The given path is added to
199 // the server's scheme/host/port to form the request URL. The given
200 // params are passed via POST form or query string.
202 // path must not contain a query string.
203 func (c *Client) RequestAndDecode(dst interface{}, method, path string, body io.Reader, params interface{}) error {
204 if body, ok := body.(io.Closer); ok {
205 // Ensure body is closed even if we error out early
208 urlString := c.apiURL(path)
209 urlValues, err := anythingToValues(params)
213 if urlValues == nil {
215 } else if method == "GET" || method == "HEAD" || body != nil {
216 // Must send params in query part of URL (FIXME: what
217 // if resulting URL is too long?)
218 u, err := url.Parse(urlString)
222 u.RawQuery = urlValues.Encode()
223 urlString = u.String()
225 body = strings.NewReader(urlValues.Encode())
227 req, err := http.NewRequest(method, urlString, body)
231 req.Header.Set("Content-type", "application/x-www-form-urlencoded")
232 return c.DoAndDecode(dst, req)
235 type resource interface {
236 resourceName() string
239 // UpdateBody returns an io.Reader suitable for use as an http.Request
240 // Body for a create or update API call.
241 func (c *Client) UpdateBody(rsc resource) io.Reader {
242 j, err := json.Marshal(rsc)
244 // Return a reader that returns errors.
246 w.CloseWithError(err)
249 v := url.Values{rsc.resourceName(): {string(j)}}
250 return bytes.NewBufferString(v.Encode())
253 type contextKey string
255 var contextKeyRequestID contextKey = "X-Request-Id"
257 func (c *Client) WithRequestID(reqid string) *Client {
259 cc.ctx = context.WithValue(cc.context(), contextKeyRequestID, reqid)
263 func (c *Client) context() context.Context {
265 return context.Background()
270 func (c *Client) httpClient() *http.Client {
272 case c.Client != nil:
275 return InsecureHTTPClient
277 return DefaultSecureClient
281 func (c *Client) apiURL(path string) string {
282 return "https://" + c.APIHost + "/" + path
285 // DiscoveryDocument is the Arvados server's description of itself.
286 type DiscoveryDocument struct {
287 BasePath string `json:"basePath"`
288 DefaultCollectionReplication int `json:"defaultCollectionReplication"`
289 BlobSignatureTTL int64 `json:"blobSignatureTtl"`
290 GitURL string `json:"gitUrl"`
291 Schemas map[string]Schema `json:"schemas"`
292 Resources map[string]Resource `json:"resources"`
295 type Resource struct {
296 Methods map[string]ResourceMethod `json:"methods"`
299 type ResourceMethod struct {
300 HTTPMethod string `json:"httpMethod"`
301 Path string `json:"path"`
302 Response MethodResponse `json:"response"`
305 type MethodResponse struct {
306 Ref string `json:"$ref"`
310 UUIDPrefix string `json:"uuidPrefix"`
313 // DiscoveryDocument returns a *DiscoveryDocument. The returned object
314 // should not be modified: the same object may be returned by
316 func (c *Client) DiscoveryDocument() (*DiscoveryDocument, error) {
320 var dd DiscoveryDocument
321 err := c.RequestAndDecode(&dd, "GET", "discovery/v1/apis/arvados/v1/rest", nil, nil)
329 var pdhRegexp = regexp.MustCompile(`^[0-9a-f]{32}\+\d+$`)
331 func (c *Client) modelForUUID(dd *DiscoveryDocument, uuid string) (string, error) {
332 if pdhRegexp.MatchString(uuid) {
333 return "Collection", nil
336 return "", fmt.Errorf("invalid UUID: %q", uuid)
340 for m, s := range dd.Schemas {
341 if s.UUIDPrefix == infix {
347 return "", fmt.Errorf("unrecognized type portion %q in UUID %q", infix, uuid)
352 func (c *Client) KindForUUID(uuid string) (string, error) {
353 dd, err := c.DiscoveryDocument()
357 model, err := c.modelForUUID(dd, uuid)
361 return "arvados#" + strings.ToLower(model[:1]) + model[1:], nil
364 func (c *Client) PathForUUID(method, uuid string) (string, error) {
365 dd, err := c.DiscoveryDocument()
369 model, err := c.modelForUUID(dd, uuid)
374 for r, rsc := range dd.Resources {
375 if rsc.Methods["get"].Response.Ref == model {
381 return "", fmt.Errorf("no resource for model: %q", model)
383 m, ok := dd.Resources[resource].Methods[method]
385 return "", fmt.Errorf("no method %q for resource %q", method, resource)
387 path := dd.BasePath + strings.Replace(m.Path, "{uuid}", uuid, -1)