18631: fix path in shell login-sync cron
[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.StatusNoContent:
221                 return nil
222         case resp.StatusCode == http.StatusOK && dst == nil:
223                 return nil
224         case resp.StatusCode == http.StatusOK:
225                 return json.Unmarshal(buf, dst)
226
227         // If the caller uses a client with a custom CheckRedirect
228         // func, Do() might return the 3xx response instead of
229         // following it.
230         case isRedirectStatus(resp.StatusCode) && dst == nil:
231                 return nil
232         case isRedirectStatus(resp.StatusCode):
233                 // Copy the redirect target URL to dst.RedirectLocation.
234                 buf, err := json.Marshal(map[string]string{"redirect_location": resp.Header.Get("Location")})
235                 if err != nil {
236                         return err
237                 }
238                 return json.Unmarshal(buf, dst)
239
240         default:
241                 return newTransactionError(req, resp, buf)
242         }
243 }
244
245 // Convert an arbitrary struct to url.Values. For example,
246 //
247 //     Foo{Bar: []int{1,2,3}, Baz: "waz"}
248 //
249 // becomes
250 //
251 //     url.Values{`bar`:`{"a":[1,2,3]}`,`Baz`:`waz`}
252 //
253 // params itself is returned if it is already an url.Values.
254 func anythingToValues(params interface{}) (url.Values, error) {
255         if v, ok := params.(url.Values); ok {
256                 return v, nil
257         }
258         // TODO: Do this more efficiently, possibly using
259         // json.Decode/Encode, so the whole thing doesn't have to get
260         // encoded, decoded, and re-encoded.
261         j, err := json.Marshal(params)
262         if err != nil {
263                 return nil, err
264         }
265         var generic map[string]interface{}
266         dec := json.NewDecoder(bytes.NewBuffer(j))
267         dec.UseNumber()
268         err = dec.Decode(&generic)
269         if err != nil {
270                 return nil, err
271         }
272         urlValues := url.Values{}
273         for k, v := range generic {
274                 if v, ok := v.(string); ok {
275                         urlValues.Set(k, v)
276                         continue
277                 }
278                 if v, ok := v.(json.Number); ok {
279                         urlValues.Set(k, v.String())
280                         continue
281                 }
282                 if v, ok := v.(bool); ok {
283                         if v {
284                                 urlValues.Set(k, "true")
285                         } else {
286                                 // "foo=false", "foo=0", and "foo="
287                                 // are all taken as true strings, so
288                                 // don't send false values at all --
289                                 // rely on the default being false.
290                         }
291                         continue
292                 }
293                 j, err := json.Marshal(v)
294                 if err != nil {
295                         return nil, err
296                 }
297                 if bytes.Equal(j, []byte("null")) {
298                         // don't add it to urlValues at all
299                         continue
300                 }
301                 urlValues.Set(k, string(j))
302         }
303         return urlValues, nil
304 }
305
306 // RequestAndDecode performs an API request and unmarshals the
307 // response (which must be JSON) into dst. Method and body arguments
308 // are the same as for http.NewRequest(). The given path is added to
309 // the server's scheme/host/port to form the request URL. The given
310 // params are passed via POST form or query string.
311 //
312 // path must not contain a query string.
313 func (c *Client) RequestAndDecode(dst interface{}, method, path string, body io.Reader, params interface{}) error {
314         return c.RequestAndDecodeContext(context.Background(), dst, method, path, body, params)
315 }
316
317 // RequestAndDecodeContext does the same as RequestAndDecode, but with a context
318 func (c *Client) RequestAndDecodeContext(ctx context.Context, dst interface{}, method, path string, body io.Reader, params interface{}) error {
319         if body, ok := body.(io.Closer); ok {
320                 // Ensure body is closed even if we error out early
321                 defer body.Close()
322         }
323         if c.APIHost == "" {
324                 if c.loadedFromEnv {
325                         return errors.New("ARVADOS_API_HOST and/or ARVADOS_API_TOKEN environment variables are not set")
326                 }
327                 return errors.New("arvados.Client cannot perform request: APIHost is not set")
328         }
329         urlString := c.apiURL(path)
330         urlValues, err := anythingToValues(params)
331         if err != nil {
332                 return err
333         }
334         if urlValues == nil {
335                 // Nothing to send
336         } else if body != nil || ((method == "GET" || method == "HEAD") && len(urlValues.Encode()) < 1000) {
337                 // Send params in query part of URL
338                 u, err := url.Parse(urlString)
339                 if err != nil {
340                         return err
341                 }
342                 u.RawQuery = urlValues.Encode()
343                 urlString = u.String()
344         } else {
345                 body = strings.NewReader(urlValues.Encode())
346         }
347         req, err := http.NewRequest(method, urlString, body)
348         if err != nil {
349                 return err
350         }
351         if (method == "GET" || method == "HEAD") && body != nil {
352                 req.Header.Set("X-Http-Method-Override", method)
353                 req.Method = "POST"
354         }
355         req = req.WithContext(ctx)
356         req.Header.Set("Content-type", "application/x-www-form-urlencoded")
357         for k, v := range c.SendHeader {
358                 req.Header[k] = v
359         }
360         return c.DoAndDecode(dst, req)
361 }
362
363 type resource interface {
364         resourceName() string
365 }
366
367 // UpdateBody returns an io.Reader suitable for use as an http.Request
368 // Body for a create or update API call.
369 func (c *Client) UpdateBody(rsc resource) io.Reader {
370         j, err := json.Marshal(rsc)
371         if err != nil {
372                 // Return a reader that returns errors.
373                 r, w := io.Pipe()
374                 w.CloseWithError(err)
375                 return r
376         }
377         v := url.Values{rsc.resourceName(): {string(j)}}
378         return bytes.NewBufferString(v.Encode())
379 }
380
381 // WithRequestID returns a new shallow copy of c that sends the given
382 // X-Request-Id value (instead of a new randomly generated one) with
383 // each subsequent request that doesn't provide its own via context or
384 // header.
385 func (c *Client) WithRequestID(reqid string) *Client {
386         cc := *c
387         cc.defaultRequestID = reqid
388         return &cc
389 }
390
391 func (c *Client) httpClient() *http.Client {
392         switch {
393         case c.Client != nil:
394                 return c.Client
395         case c.Insecure:
396                 return InsecureHTTPClient
397         default:
398                 return DefaultSecureClient
399         }
400 }
401
402 func (c *Client) apiURL(path string) string {
403         scheme := c.Scheme
404         if scheme == "" {
405                 scheme = "https"
406         }
407         return scheme + "://" + c.APIHost + "/" + path
408 }
409
410 // DiscoveryDocument is the Arvados server's description of itself.
411 type DiscoveryDocument struct {
412         BasePath                     string              `json:"basePath"`
413         DefaultCollectionReplication int                 `json:"defaultCollectionReplication"`
414         BlobSignatureTTL             int64               `json:"blobSignatureTtl"`
415         GitURL                       string              `json:"gitUrl"`
416         Schemas                      map[string]Schema   `json:"schemas"`
417         Resources                    map[string]Resource `json:"resources"`
418 }
419
420 type Resource struct {
421         Methods map[string]ResourceMethod `json:"methods"`
422 }
423
424 type ResourceMethod struct {
425         HTTPMethod string         `json:"httpMethod"`
426         Path       string         `json:"path"`
427         Response   MethodResponse `json:"response"`
428 }
429
430 type MethodResponse struct {
431         Ref string `json:"$ref"`
432 }
433
434 type Schema struct {
435         UUIDPrefix string `json:"uuidPrefix"`
436 }
437
438 // DiscoveryDocument returns a *DiscoveryDocument. The returned object
439 // should not be modified: the same object may be returned by
440 // subsequent calls.
441 func (c *Client) DiscoveryDocument() (*DiscoveryDocument, error) {
442         if c.dd != nil {
443                 return c.dd, nil
444         }
445         var dd DiscoveryDocument
446         err := c.RequestAndDecode(&dd, "GET", "discovery/v1/apis/arvados/v1/rest", nil, nil)
447         if err != nil {
448                 return nil, err
449         }
450         c.dd = &dd
451         return c.dd, nil
452 }
453
454 var pdhRegexp = regexp.MustCompile(`^[0-9a-f]{32}\+\d+$`)
455
456 func (c *Client) modelForUUID(dd *DiscoveryDocument, uuid string) (string, error) {
457         if pdhRegexp.MatchString(uuid) {
458                 return "Collection", nil
459         }
460         if len(uuid) != 27 {
461                 return "", fmt.Errorf("invalid UUID: %q", uuid)
462         }
463         infix := uuid[6:11]
464         var model string
465         for m, s := range dd.Schemas {
466                 if s.UUIDPrefix == infix {
467                         model = m
468                         break
469                 }
470         }
471         if model == "" {
472                 return "", fmt.Errorf("unrecognized type portion %q in UUID %q", infix, uuid)
473         }
474         return model, nil
475 }
476
477 func (c *Client) KindForUUID(uuid string) (string, error) {
478         dd, err := c.DiscoveryDocument()
479         if err != nil {
480                 return "", err
481         }
482         model, err := c.modelForUUID(dd, uuid)
483         if err != nil {
484                 return "", err
485         }
486         return "arvados#" + strings.ToLower(model[:1]) + model[1:], nil
487 }
488
489 func (c *Client) PathForUUID(method, uuid string) (string, error) {
490         dd, err := c.DiscoveryDocument()
491         if err != nil {
492                 return "", err
493         }
494         model, err := c.modelForUUID(dd, uuid)
495         if err != nil {
496                 return "", err
497         }
498         var resource string
499         for r, rsc := range dd.Resources {
500                 if rsc.Methods["get"].Response.Ref == model {
501                         resource = r
502                         break
503                 }
504         }
505         if resource == "" {
506                 return "", fmt.Errorf("no resource for model: %q", model)
507         }
508         m, ok := dd.Resources[resource].Methods[method]
509         if !ok {
510                 return "", fmt.Errorf("no method %q for resource %q", method, resource)
511         }
512         path := dd.BasePath + strings.Replace(m.Path, "{uuid}", uuid, -1)
513         if path[0] == '/' {
514                 path = path[1:]
515         }
516         return path, nil
517 }