Fix a few more golint warnings.
[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                 }
325                 return errors.New("arvados.Client cannot perform request: APIHost is not set")
326         }
327         urlString := c.apiURL(path)
328         urlValues, err := anythingToValues(params)
329         if err != nil {
330                 return err
331         }
332         if urlValues == nil {
333                 // Nothing to send
334         } else if body != nil || ((method == "GET" || method == "HEAD") && len(urlValues.Encode()) < 1000) {
335                 // Send params in query part of URL
336                 u, err := url.Parse(urlString)
337                 if err != nil {
338                         return err
339                 }
340                 u.RawQuery = urlValues.Encode()
341                 urlString = u.String()
342         } else {
343                 body = strings.NewReader(urlValues.Encode())
344         }
345         req, err := http.NewRequest(method, urlString, body)
346         if err != nil {
347                 return err
348         }
349         if (method == "GET" || method == "HEAD") && body != nil {
350                 req.Header.Set("X-Http-Method-Override", method)
351                 req.Method = "POST"
352         }
353         req = req.WithContext(ctx)
354         req.Header.Set("Content-type", "application/x-www-form-urlencoded")
355         for k, v := range c.SendHeader {
356                 req.Header[k] = v
357         }
358         return c.DoAndDecode(dst, req)
359 }
360
361 type resource interface {
362         resourceName() string
363 }
364
365 // UpdateBody returns an io.Reader suitable for use as an http.Request
366 // Body for a create or update API call.
367 func (c *Client) UpdateBody(rsc resource) io.Reader {
368         j, err := json.Marshal(rsc)
369         if err != nil {
370                 // Return a reader that returns errors.
371                 r, w := io.Pipe()
372                 w.CloseWithError(err)
373                 return r
374         }
375         v := url.Values{rsc.resourceName(): {string(j)}}
376         return bytes.NewBufferString(v.Encode())
377 }
378
379 // WithRequestID returns a new shallow copy of c that sends the given
380 // X-Request-Id value (instead of a new randomly generated one) with
381 // each subsequent request that doesn't provide its own via context or
382 // header.
383 func (c *Client) WithRequestID(reqid string) *Client {
384         cc := *c
385         cc.defaultRequestID = reqid
386         return &cc
387 }
388
389 func (c *Client) httpClient() *http.Client {
390         switch {
391         case c.Client != nil:
392                 return c.Client
393         case c.Insecure:
394                 return InsecureHTTPClient
395         default:
396                 return DefaultSecureClient
397         }
398 }
399
400 func (c *Client) apiURL(path string) string {
401         scheme := c.Scheme
402         if scheme == "" {
403                 scheme = "https"
404         }
405         return scheme + "://" + c.APIHost + "/" + path
406 }
407
408 // DiscoveryDocument is the Arvados server's description of itself.
409 type DiscoveryDocument struct {
410         BasePath                     string              `json:"basePath"`
411         DefaultCollectionReplication int                 `json:"defaultCollectionReplication"`
412         BlobSignatureTTL             int64               `json:"blobSignatureTtl"`
413         GitURL                       string              `json:"gitUrl"`
414         Schemas                      map[string]Schema   `json:"schemas"`
415         Resources                    map[string]Resource `json:"resources"`
416 }
417
418 type Resource struct {
419         Methods map[string]ResourceMethod `json:"methods"`
420 }
421
422 type ResourceMethod struct {
423         HTTPMethod string         `json:"httpMethod"`
424         Path       string         `json:"path"`
425         Response   MethodResponse `json:"response"`
426 }
427
428 type MethodResponse struct {
429         Ref string `json:"$ref"`
430 }
431
432 type Schema struct {
433         UUIDPrefix string `json:"uuidPrefix"`
434 }
435
436 // DiscoveryDocument returns a *DiscoveryDocument. The returned object
437 // should not be modified: the same object may be returned by
438 // subsequent calls.
439 func (c *Client) DiscoveryDocument() (*DiscoveryDocument, error) {
440         if c.dd != nil {
441                 return c.dd, nil
442         }
443         var dd DiscoveryDocument
444         err := c.RequestAndDecode(&dd, "GET", "discovery/v1/apis/arvados/v1/rest", nil, nil)
445         if err != nil {
446                 return nil, err
447         }
448         c.dd = &dd
449         return c.dd, nil
450 }
451
452 var pdhRegexp = regexp.MustCompile(`^[0-9a-f]{32}\+\d+$`)
453
454 func (c *Client) modelForUUID(dd *DiscoveryDocument, uuid string) (string, error) {
455         if pdhRegexp.MatchString(uuid) {
456                 return "Collection", nil
457         }
458         if len(uuid) != 27 {
459                 return "", fmt.Errorf("invalid UUID: %q", uuid)
460         }
461         infix := uuid[6:11]
462         var model string
463         for m, s := range dd.Schemas {
464                 if s.UUIDPrefix == infix {
465                         model = m
466                         break
467                 }
468         }
469         if model == "" {
470                 return "", fmt.Errorf("unrecognized type portion %q in UUID %q", infix, uuid)
471         }
472         return model, nil
473 }
474
475 func (c *Client) KindForUUID(uuid string) (string, error) {
476         dd, err := c.DiscoveryDocument()
477         if err != nil {
478                 return "", err
479         }
480         model, err := c.modelForUUID(dd, uuid)
481         if err != nil {
482                 return "", err
483         }
484         return "arvados#" + strings.ToLower(model[:1]) + model[1:], nil
485 }
486
487 func (c *Client) PathForUUID(method, uuid string) (string, error) {
488         dd, err := c.DiscoveryDocument()
489         if err != nil {
490                 return "", err
491         }
492         model, err := c.modelForUUID(dd, uuid)
493         if err != nil {
494                 return "", err
495         }
496         var resource string
497         for r, rsc := range dd.Resources {
498                 if rsc.Methods["get"].Response.Ref == model {
499                         resource = r
500                         break
501                 }
502         }
503         if resource == "" {
504                 return "", fmt.Errorf("no resource for model: %q", model)
505         }
506         m, ok := dd.Resources[resource].Methods[method]
507         if !ok {
508                 return "", fmt.Errorf("no method %q for resource %q", method, resource)
509         }
510         path := dd.BasePath + strings.Replace(m.Path, "{uuid}", uuid, -1)
511         if path[0] == '/' {
512                 path = path[1:]
513         }
514         return path, nil
515 }