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