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