ea3cb6899e7bd5ac9f92cc0d3127e6aa3a485f13
[arvados.git] / sdk / go / arvados / client.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: Apache-2.0
4
5 package arvados
6
7 import (
8         "bytes"
9         "context"
10         "crypto/tls"
11         "encoding/json"
12         "errors"
13         "fmt"
14         "io"
15         "io/ioutil"
16         "log"
17         "net/http"
18         "net/url"
19         "os"
20         "regexp"
21         "strings"
22         "time"
23
24         "git.arvados.org/arvados.git/sdk/go/httpserver"
25 )
26
27 // A Client is an HTTP client with an API endpoint and a set of
28 // Arvados credentials.
29 //
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.
33 type Client struct {
34         // HTTP client used to make requests. If nil,
35         // DefaultSecureClient or InsecureHTTPClient will be used.
36         Client *http.Client `json:"-"`
37
38         // Protocol scheme: "http", "https", or "" (https)
39         Scheme string
40
41         // Hostname (or host:port) of Arvados API server.
42         APIHost string
43
44         // User authentication token.
45         AuthToken string
46
47         // Accept unverified certificates. This works only if the
48         // Client field is nil: otherwise, it has no effect.
49         Insecure bool
50
51         // Override keep service discovery with a list of base
52         // URIs. (Currently there are no Client methods for
53         // discovering keep services so this is just a convenience for
54         // callers who use a Client to initialize an
55         // arvadosclient.ArvadosClient.)
56         KeepServiceURIs []string `json:",omitempty"`
57
58         // HTTP headers to add/override in outgoing requests.
59         SendHeader http.Header
60
61         // Timeout for requests. NewClientFromConfig and
62         // NewClientFromEnv return a Client with a default 5 minute
63         // timeout.  To disable this timeout and rely on each
64         // http.Request's context deadline instead, set Timeout to
65         // zero.
66         Timeout time.Duration
67
68         dd *DiscoveryDocument
69
70         defaultRequestID string
71
72         // APIHost and AuthToken were loaded from ARVADOS_* env vars
73         // (used to customize "no host/token" error messages)
74         loadedFromEnv bool
75 }
76
77 // InsecureHTTPClient is the default http.Client used by a Client with
78 // Insecure==true and Client==nil.
79 var InsecureHTTPClient = &http.Client{
80         Transport: &http.Transport{
81                 TLSClientConfig: &tls.Config{
82                         InsecureSkipVerify: true}}}
83
84 // DefaultSecureClient is the default http.Client used by a Client otherwise.
85 var DefaultSecureClient = &http.Client{}
86
87 // NewClientFromConfig creates a new Client that uses the endpoints in
88 // the given cluster.
89 //
90 // AuthToken is left empty for the caller to populate.
91 func NewClientFromConfig(cluster *Cluster) (*Client, error) {
92         ctrlURL := cluster.Services.Controller.ExternalURL
93         if ctrlURL.Host == "" {
94                 return nil, fmt.Errorf("no host in config Services.Controller.ExternalURL: %v", ctrlURL)
95         }
96         return &Client{
97                 Scheme:   ctrlURL.Scheme,
98                 APIHost:  ctrlURL.Host,
99                 Insecure: cluster.TLS.Insecure,
100                 Timeout:  5 * time.Minute,
101         }, nil
102 }
103
104 // NewClientFromEnv creates a new Client that uses the default HTTP
105 // client with the API endpoint and credentials given by the
106 // ARVADOS_API_* environment variables.
107 func NewClientFromEnv() *Client {
108         var svcs []string
109         for _, s := range strings.Split(os.Getenv("ARVADOS_KEEP_SERVICES"), " ") {
110                 if s == "" {
111                         continue
112                 } else if u, err := url.Parse(s); err != nil {
113                         log.Printf("ARVADOS_KEEP_SERVICES: %q: %s", s, err)
114                 } else if !u.IsAbs() {
115                         log.Printf("ARVADOS_KEEP_SERVICES: %q: not an absolute URI", s)
116                 } else {
117                         svcs = append(svcs, s)
118                 }
119         }
120         var insecure bool
121         if s := strings.ToLower(os.Getenv("ARVADOS_API_HOST_INSECURE")); s == "1" || s == "yes" || s == "true" {
122                 insecure = true
123         }
124         return &Client{
125                 Scheme:          "https",
126                 APIHost:         os.Getenv("ARVADOS_API_HOST"),
127                 AuthToken:       os.Getenv("ARVADOS_API_TOKEN"),
128                 Insecure:        insecure,
129                 KeepServiceURIs: svcs,
130                 Timeout:         5 * time.Minute,
131                 loadedFromEnv:   true,
132         }
133 }
134
135 var reqIDGen = httpserver.IDGenerator{Prefix: "req-"}
136
137 // Do adds Authorization and X-Request-Id headers and then calls
138 // (*http.Client)Do().
139 func (c *Client) Do(req *http.Request) (*http.Response, error) {
140         if auth, _ := req.Context().Value(contextKeyAuthorization{}).(string); auth != "" {
141                 req.Header.Add("Authorization", auth)
142         } else if c.AuthToken != "" {
143                 req.Header.Add("Authorization", "OAuth2 "+c.AuthToken)
144         }
145
146         if req.Header.Get("X-Request-Id") == "" {
147                 var reqid string
148                 if ctxreqid, _ := req.Context().Value(contextKeyRequestID{}).(string); ctxreqid != "" {
149                         reqid = ctxreqid
150                 } else if c.defaultRequestID != "" {
151                         reqid = c.defaultRequestID
152                 } else {
153                         reqid = reqIDGen.Next()
154                 }
155                 if req.Header == nil {
156                         req.Header = http.Header{"X-Request-Id": {reqid}}
157                 } else {
158                         req.Header.Set("X-Request-Id", reqid)
159                 }
160         }
161         var cancel context.CancelFunc
162         if c.Timeout > 0 {
163                 ctx := req.Context()
164                 ctx, cancel = context.WithDeadline(ctx, time.Now().Add(c.Timeout))
165                 req = req.WithContext(ctx)
166         }
167         resp, err := c.httpClient().Do(req)
168         if err == nil && cancel != nil {
169                 // We need to call cancel() eventually, but we can't
170                 // use "defer cancel()" because the context has to
171                 // stay alive until the caller has finished reading
172                 // the response body.
173                 resp.Body = cancelOnClose{ReadCloser: resp.Body, cancel: cancel}
174         } else if cancel != nil {
175                 cancel()
176         }
177         return resp, err
178 }
179
180 // cancelOnClose calls a provided CancelFunc when its wrapped
181 // ReadCloser's Close() method is called.
182 type cancelOnClose struct {
183         io.ReadCloser
184         cancel context.CancelFunc
185 }
186
187 func (coc cancelOnClose) Close() error {
188         err := coc.ReadCloser.Close()
189         coc.cancel()
190         return err
191 }
192
193 func isRedirectStatus(code int) bool {
194         switch code {
195         case http.StatusMovedPermanently, http.StatusFound, http.StatusSeeOther, http.StatusTemporaryRedirect, http.StatusPermanentRedirect:
196                 return true
197         default:
198                 return false
199         }
200 }
201
202 // DoAndDecode performs req and unmarshals the response (which must be
203 // JSON) into dst. Use this instead of RequestAndDecode if you need
204 // more control of the http.Request object.
205 //
206 // If the response status indicates an HTTP redirect, the Location
207 // header value is unmarshalled to dst as a RedirectLocation
208 // key/field.
209 func (c *Client) DoAndDecode(dst interface{}, req *http.Request) error {
210         resp, err := c.Do(req)
211         if err != nil {
212                 return err
213         }
214         defer resp.Body.Close()
215         buf, err := ioutil.ReadAll(resp.Body)
216         if err != nil {
217                 return err
218         }
219         switch {
220         case resp.StatusCode == http.StatusOK && dst == nil:
221                 return nil
222         case resp.StatusCode == http.StatusOK:
223                 return json.Unmarshal(buf, dst)
224
225         // If the caller uses a client with a custom CheckRedirect
226         // func, Do() might return the 3xx response instead of
227         // following it.
228         case isRedirectStatus(resp.StatusCode) && dst == nil:
229                 return nil
230         case isRedirectStatus(resp.StatusCode):
231                 // Copy the redirect target URL to dst.RedirectLocation.
232                 buf, err := json.Marshal(map[string]string{"redirect_location": resp.Header.Get("Location")})
233                 if err != nil {
234                         return err
235                 }
236                 return json.Unmarshal(buf, dst)
237
238         default:
239                 return newTransactionError(req, resp, buf)
240         }
241 }
242
243 // Convert an arbitrary struct to url.Values. For example,
244 //
245 //     Foo{Bar: []int{1,2,3}, Baz: "waz"}
246 //
247 // becomes
248 //
249 //     url.Values{`bar`:`{"a":[1,2,3]}`,`Baz`:`waz`}
250 //
251 // params itself is returned if it is already an url.Values.
252 func anythingToValues(params interface{}) (url.Values, error) {
253         if v, ok := params.(url.Values); ok {
254                 return v, nil
255         }
256         // TODO: Do this more efficiently, possibly using
257         // json.Decode/Encode, so the whole thing doesn't have to get
258         // encoded, decoded, and re-encoded.
259         j, err := json.Marshal(params)
260         if err != nil {
261                 return nil, err
262         }
263         var generic map[string]interface{}
264         dec := json.NewDecoder(bytes.NewBuffer(j))
265         dec.UseNumber()
266         err = dec.Decode(&generic)
267         if err != nil {
268                 return nil, err
269         }
270         urlValues := url.Values{}
271         for k, v := range generic {
272                 if v, ok := v.(string); ok {
273                         urlValues.Set(k, v)
274                         continue
275                 }
276                 if v, ok := v.(json.Number); ok {
277                         urlValues.Set(k, v.String())
278                         continue
279                 }
280                 if v, ok := v.(bool); ok {
281                         if v {
282                                 urlValues.Set(k, "true")
283                         } else {
284                                 // "foo=false", "foo=0", and "foo="
285                                 // are all taken as true strings, so
286                                 // don't send false values at all --
287                                 // rely on the default being false.
288                         }
289                         continue
290                 }
291                 j, err := json.Marshal(v)
292                 if err != nil {
293                         return nil, err
294                 }
295                 if bytes.Equal(j, []byte("null")) {
296                         // don't add it to urlValues at all
297                         continue
298                 }
299                 urlValues.Set(k, string(j))
300         }
301         return urlValues, nil
302 }
303
304 // RequestAndDecode performs an API request and unmarshals the
305 // response (which must be JSON) into dst. Method and body arguments
306 // are the same as for http.NewRequest(). The given path is added to
307 // the server's scheme/host/port to form the request URL. The given
308 // params are passed via POST form or query string.
309 //
310 // path must not contain a query string.
311 func (c *Client) RequestAndDecode(dst interface{}, method, path string, body io.Reader, params interface{}) error {
312         return c.RequestAndDecodeContext(context.Background(), dst, method, path, body, params)
313 }
314
315 // RequestAndDecodeContext does the same as RequestAndDecode, but with a context
316 func (c *Client) RequestAndDecodeContext(ctx context.Context, dst interface{}, method, path string, body io.Reader, params interface{}) error {
317         if body, ok := body.(io.Closer); ok {
318                 // Ensure body is closed even if we error out early
319                 defer body.Close()
320         }
321         if c.APIHost == "" {
322                 if c.loadedFromEnv {
323                         return errors.New("ARVADOS_API_HOST and/or ARVADOS_API_TOKEN environment variables are not set")
324                 } else {
325                         return errors.New("arvados.Client cannot perform request: APIHost is not set")
326                 }
327         }
328         urlString := c.apiURL(path)
329         urlValues, err := anythingToValues(params)
330         if err != nil {
331                 return err
332         }
333         if urlValues == nil {
334                 // Nothing to send
335         } else if body != nil || ((method == "GET" || method == "HEAD") && len(urlValues.Encode()) < 1000) {
336                 // Send params in query part of URL
337                 u, err := url.Parse(urlString)
338                 if err != nil {
339                         return err
340                 }
341                 u.RawQuery = urlValues.Encode()
342                 urlString = u.String()
343         } else {
344                 body = strings.NewReader(urlValues.Encode())
345         }
346         req, err := http.NewRequest(method, urlString, body)
347         if err != nil {
348                 return err
349         }
350         if (method == "GET" || method == "HEAD") && body != nil {
351                 req.Header.Set("X-Http-Method-Override", method)
352                 req.Method = "POST"
353         }
354         req = req.WithContext(ctx)
355         req.Header.Set("Content-type", "application/x-www-form-urlencoded")
356         for k, v := range c.SendHeader {
357                 req.Header[k] = v
358         }
359         return c.DoAndDecode(dst, req)
360 }
361
362 type resource interface {
363         resourceName() string
364 }
365
366 // UpdateBody returns an io.Reader suitable for use as an http.Request
367 // Body for a create or update API call.
368 func (c *Client) UpdateBody(rsc resource) io.Reader {
369         j, err := json.Marshal(rsc)
370         if err != nil {
371                 // Return a reader that returns errors.
372                 r, w := io.Pipe()
373                 w.CloseWithError(err)
374                 return r
375         }
376         v := url.Values{rsc.resourceName(): {string(j)}}
377         return bytes.NewBufferString(v.Encode())
378 }
379
380 // WithRequestID returns a new shallow copy of c that sends the given
381 // X-Request-Id value (instead of a new randomly generated one) with
382 // each subsequent request that doesn't provide its own via context or
383 // header.
384 func (c *Client) WithRequestID(reqid string) *Client {
385         cc := *c
386         cc.defaultRequestID = reqid
387         return &cc
388 }
389
390 func (c *Client) httpClient() *http.Client {
391         switch {
392         case c.Client != nil:
393                 return c.Client
394         case c.Insecure:
395                 return InsecureHTTPClient
396         default:
397                 return DefaultSecureClient
398         }
399 }
400
401 func (c *Client) apiURL(path string) string {
402         scheme := c.Scheme
403         if scheme == "" {
404                 scheme = "https"
405         }
406         return scheme + "://" + c.APIHost + "/" + path
407 }
408
409 // DiscoveryDocument is the Arvados server's description of itself.
410 type DiscoveryDocument struct {
411         BasePath                     string              `json:"basePath"`
412         DefaultCollectionReplication int                 `json:"defaultCollectionReplication"`
413         BlobSignatureTTL             int64               `json:"blobSignatureTtl"`
414         GitURL                       string              `json:"gitUrl"`
415         Schemas                      map[string]Schema   `json:"schemas"`
416         Resources                    map[string]Resource `json:"resources"`
417 }
418
419 type Resource struct {
420         Methods map[string]ResourceMethod `json:"methods"`
421 }
422
423 type ResourceMethod struct {
424         HTTPMethod string         `json:"httpMethod"`
425         Path       string         `json:"path"`
426         Response   MethodResponse `json:"response"`
427 }
428
429 type MethodResponse struct {
430         Ref string `json:"$ref"`
431 }
432
433 type Schema struct {
434         UUIDPrefix string `json:"uuidPrefix"`
435 }
436
437 // DiscoveryDocument returns a *DiscoveryDocument. The returned object
438 // should not be modified: the same object may be returned by
439 // subsequent calls.
440 func (c *Client) DiscoveryDocument() (*DiscoveryDocument, error) {
441         if c.dd != nil {
442                 return c.dd, nil
443         }
444         var dd DiscoveryDocument
445         err := c.RequestAndDecode(&dd, "GET", "discovery/v1/apis/arvados/v1/rest", nil, nil)
446         if err != nil {
447                 return nil, err
448         }
449         c.dd = &dd
450         return c.dd, nil
451 }
452
453 var pdhRegexp = regexp.MustCompile(`^[0-9a-f]{32}\+\d+$`)
454
455 func (c *Client) modelForUUID(dd *DiscoveryDocument, uuid string) (string, error) {
456         if pdhRegexp.MatchString(uuid) {
457                 return "Collection", nil
458         }
459         if len(uuid) != 27 {
460                 return "", fmt.Errorf("invalid UUID: %q", uuid)
461         }
462         infix := uuid[6:11]
463         var model string
464         for m, s := range dd.Schemas {
465                 if s.UUIDPrefix == infix {
466                         model = m
467                         break
468                 }
469         }
470         if model == "" {
471                 return "", fmt.Errorf("unrecognized type portion %q in UUID %q", infix, uuid)
472         }
473         return model, nil
474 }
475
476 func (c *Client) KindForUUID(uuid string) (string, error) {
477         dd, err := c.DiscoveryDocument()
478         if err != nil {
479                 return "", err
480         }
481         model, err := c.modelForUUID(dd, uuid)
482         if err != nil {
483                 return "", err
484         }
485         return "arvados#" + strings.ToLower(model[:1]) + model[1:], nil
486 }
487
488 func (c *Client) PathForUUID(method, uuid string) (string, error) {
489         dd, err := c.DiscoveryDocument()
490         if err != nil {
491                 return "", err
492         }
493         model, err := c.modelForUUID(dd, uuid)
494         if err != nil {
495                 return "", err
496         }
497         var resource string
498         for r, rsc := range dd.Resources {
499                 if rsc.Methods["get"].Response.Ref == model {
500                         resource = r
501                         break
502                 }
503         }
504         if resource == "" {
505                 return "", fmt.Errorf("no resource for model: %q", model)
506         }
507         m, ok := dd.Resources[resource].Methods[method]
508         if !ok {
509                 return "", fmt.Errorf("no method %q for resource %q", method, resource)
510         }
511         path := dd.BasePath + strings.Replace(m.Path, "{uuid}", uuid, -1)
512         if path[0] == '/' {
513                 path = path[1:]
514         }
515         return path, nil
516 }