Merge branch '21217-invalid-auth-header'
[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/rand"
11         "crypto/tls"
12         "encoding/json"
13         "errors"
14         "fmt"
15         "io"
16         "io/fs"
17         "io/ioutil"
18         "log"
19         "math"
20         "math/big"
21         mathrand "math/rand"
22         "net"
23         "net/http"
24         "net/url"
25         "os"
26         "regexp"
27         "strconv"
28         "strings"
29         "sync/atomic"
30         "time"
31
32         "git.arvados.org/arvados.git/sdk/go/httpserver"
33         "github.com/hashicorp/go-retryablehttp"
34 )
35
36 // A Client is an HTTP client with an API endpoint and a set of
37 // Arvados credentials.
38 //
39 // It offers methods for accessing individual Arvados APIs, and
40 // methods that implement common patterns like fetching multiple pages
41 // of results using List APIs.
42 type Client struct {
43         // HTTP client used to make requests. If nil,
44         // DefaultSecureClient or InsecureHTTPClient will be used.
45         Client *http.Client `json:"-"`
46
47         // Protocol scheme: "http", "https", or "" (https)
48         Scheme string
49
50         // Hostname (or host:port) of Arvados API server.
51         APIHost string
52
53         // User authentication token.
54         AuthToken string
55
56         // Accept unverified certificates. This works only if the
57         // Client field is nil: otherwise, it has no effect.
58         Insecure bool
59
60         // Override keep service discovery with a list of base
61         // URIs. (Currently there are no Client methods for
62         // discovering keep services so this is just a convenience for
63         // callers who use a Client to initialize an
64         // arvadosclient.ArvadosClient.)
65         KeepServiceURIs []string `json:",omitempty"`
66
67         // HTTP headers to add/override in outgoing requests.
68         SendHeader http.Header
69
70         // Timeout for requests. NewClientFromConfig and
71         // NewClientFromEnv return a Client with a default 5 minute
72         // timeout. Within this time, retryable errors are
73         // automatically retried with exponential backoff.
74         //
75         // To disable automatic retries, set Timeout to zero and use a
76         // context deadline to establish a maximum request time.
77         Timeout time.Duration
78
79         dd *DiscoveryDocument
80
81         defaultRequestID string
82
83         // APIHost and AuthToken were loaded from ARVADOS_* env vars
84         // (used to customize "no host/token" error messages)
85         loadedFromEnv bool
86
87         // Track/limit concurrent outgoing API calls. Note this
88         // differs from an outgoing connection limit (a feature
89         // provided by http.Transport) when concurrent calls are
90         // multiplexed on a single http2 connection.
91         requestLimiter requestLimiter
92
93         last503 atomic.Value
94 }
95
96 // InsecureHTTPClient is the default http.Client used by a Client with
97 // Insecure==true and Client==nil.
98 var InsecureHTTPClient = &http.Client{
99         Transport: &http.Transport{
100                 TLSClientConfig: &tls.Config{
101                         InsecureSkipVerify: true}}}
102
103 // DefaultSecureClient is the default http.Client used by a Client otherwise.
104 var DefaultSecureClient = &http.Client{}
105
106 // NewClientFromConfig creates a new Client that uses the endpoints in
107 // the given cluster.
108 //
109 // AuthToken is left empty for the caller to populate.
110 func NewClientFromConfig(cluster *Cluster) (*Client, error) {
111         ctrlURL := cluster.Services.Controller.ExternalURL
112         if ctrlURL.Host == "" {
113                 return nil, fmt.Errorf("no host in config Services.Controller.ExternalURL: %v", ctrlURL)
114         }
115         var hc *http.Client
116         if srvaddr := os.Getenv("ARVADOS_SERVER_ADDRESS"); srvaddr != "" {
117                 // When this client is used to make a request to
118                 // https://{ctrlhost}:port/ (any port), it dials the
119                 // indicated port on ARVADOS_SERVER_ADDRESS instead.
120                 //
121                 // This is invoked by arvados-server boot to ensure
122                 // that server->server traffic (e.g.,
123                 // keepproxy->controller) only hits local interfaces,
124                 // even if the Controller.ExternalURL host is a load
125                 // balancer / gateway and not a local interface
126                 // address (e.g., when running on a cloud VM).
127                 //
128                 // This avoids unnecessary delay/cost of routing
129                 // external traffic, and also allows controller to
130                 // recognize other services as internal clients based
131                 // on the connection source address.
132                 divertedHost := (*url.URL)(&cluster.Services.Controller.ExternalURL).Hostname()
133                 var dialer net.Dialer
134                 hc = &http.Client{
135                         Transport: &http.Transport{
136                                 TLSClientConfig: &tls.Config{InsecureSkipVerify: cluster.TLS.Insecure},
137                                 DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
138                                         host, port, err := net.SplitHostPort(addr)
139                                         if err == nil && network == "tcp" && host == divertedHost {
140                                                 addr = net.JoinHostPort(srvaddr, port)
141                                         }
142                                         return dialer.DialContext(ctx, network, addr)
143                                 },
144                         },
145                 }
146         }
147         return &Client{
148                 Client:         hc,
149                 Scheme:         ctrlURL.Scheme,
150                 APIHost:        ctrlURL.Host,
151                 Insecure:       cluster.TLS.Insecure,
152                 Timeout:        5 * time.Minute,
153                 requestLimiter: requestLimiter{maxlimit: int64(cluster.API.MaxConcurrentRequests / 4)},
154         }, nil
155 }
156
157 // NewClientFromEnv creates a new Client that uses the default HTTP
158 // client, and loads API endpoint and credentials from ARVADOS_*
159 // environment variables (if set) and
160 // $HOME/.config/arvados/settings.conf (if readable).
161 //
162 // If a config exists in both locations, the environment variable is
163 // used.
164 //
165 // If there is an error (other than ENOENT) reading settings.conf,
166 // NewClientFromEnv logs the error to log.Default(), then proceeds as
167 // if settings.conf did not exist.
168 //
169 // Space characters are trimmed when reading the settings file, so
170 // these are equivalent:
171 //
172 //      ARVADOS_API_HOST=localhost\n
173 //      ARVADOS_API_HOST=localhost\r\n
174 //      ARVADOS_API_HOST = localhost \n
175 //      \tARVADOS_API_HOST = localhost\n
176 func NewClientFromEnv() *Client {
177         vars := map[string]string{}
178         home := os.Getenv("HOME")
179         conffile := home + "/.config/arvados/settings.conf"
180         if home == "" {
181                 // no $HOME => just use env vars
182         } else if settings, err := os.ReadFile(conffile); errors.Is(err, fs.ErrNotExist) {
183                 // no config file => just use env vars
184         } else if err != nil {
185                 // config file unreadable => log message, then use env vars
186                 log.Printf("continuing without loading %s: %s", conffile, err)
187         } else {
188                 for _, line := range bytes.Split(settings, []byte{'\n'}) {
189                         kv := bytes.SplitN(line, []byte{'='}, 2)
190                         k := string(bytes.TrimSpace(kv[0]))
191                         if len(kv) != 2 || !strings.HasPrefix(k, "ARVADOS_") {
192                                 // Same behavior as python sdk:
193                                 // silently skip leading # (comments),
194                                 // blank lines, typos, and non-Arvados
195                                 // vars.
196                                 continue
197                         }
198                         vars[k] = string(bytes.TrimSpace(kv[1]))
199                 }
200         }
201         for _, env := range os.Environ() {
202                 if !strings.HasPrefix(env, "ARVADOS_") {
203                         continue
204                 }
205                 kv := strings.SplitN(env, "=", 2)
206                 if len(kv) == 2 {
207                         vars[kv[0]] = kv[1]
208                 }
209         }
210         var svcs []string
211         for _, s := range strings.Split(vars["ARVADOS_KEEP_SERVICES"], " ") {
212                 if s == "" {
213                         continue
214                 } else if u, err := url.Parse(s); err != nil {
215                         log.Printf("ARVADOS_KEEP_SERVICES: %q: %s", s, err)
216                 } else if !u.IsAbs() {
217                         log.Printf("ARVADOS_KEEP_SERVICES: %q: not an absolute URI", s)
218                 } else {
219                         svcs = append(svcs, s)
220                 }
221         }
222         var insecure bool
223         if s := strings.ToLower(vars["ARVADOS_API_HOST_INSECURE"]); s == "1" || s == "yes" || s == "true" {
224                 insecure = true
225         }
226         return &Client{
227                 Scheme:          "https",
228                 APIHost:         vars["ARVADOS_API_HOST"],
229                 AuthToken:       vars["ARVADOS_API_TOKEN"],
230                 Insecure:        insecure,
231                 KeepServiceURIs: svcs,
232                 Timeout:         5 * time.Minute,
233                 loadedFromEnv:   true,
234         }
235 }
236
237 var reqIDGen = httpserver.IDGenerator{Prefix: "req-"}
238
239 var nopCancelFunc context.CancelFunc = func() {}
240
241 var reqErrorRe = regexp.MustCompile(`net/http: invalid header `)
242
243 // Do augments (*http.Client)Do(): adds Authorization and X-Request-Id
244 // headers, delays in order to comply with rate-limiting restrictions,
245 // and retries failed requests when appropriate.
246 func (c *Client) Do(req *http.Request) (*http.Response, error) {
247         ctx := req.Context()
248         if auth, _ := ctx.Value(contextKeyAuthorization{}).(string); auth != "" {
249                 req.Header.Add("Authorization", auth)
250         } else if c.AuthToken != "" {
251                 req.Header.Add("Authorization", "OAuth2 "+c.AuthToken)
252         }
253
254         if req.Header.Get("X-Request-Id") == "" {
255                 var reqid string
256                 if ctxreqid, _ := ctx.Value(contextKeyRequestID{}).(string); ctxreqid != "" {
257                         reqid = ctxreqid
258                 } else if c.defaultRequestID != "" {
259                         reqid = c.defaultRequestID
260                 } else {
261                         reqid = reqIDGen.Next()
262                 }
263                 if req.Header == nil {
264                         req.Header = http.Header{"X-Request-Id": {reqid}}
265                 } else {
266                         req.Header.Set("X-Request-Id", reqid)
267                 }
268         }
269
270         rreq, err := retryablehttp.FromRequest(req)
271         if err != nil {
272                 return nil, err
273         }
274
275         cancel := nopCancelFunc
276         var lastResp *http.Response
277         var lastRespBody io.ReadCloser
278         var lastErr error
279         var checkRetryCalled int
280
281         rclient := retryablehttp.NewClient()
282         rclient.HTTPClient = c.httpClient()
283         rclient.Backoff = exponentialBackoff
284         if c.Timeout > 0 {
285                 rclient.RetryWaitMax = c.Timeout / 10
286                 rclient.RetryMax = 32
287                 ctx, cancel = context.WithDeadline(ctx, time.Now().Add(c.Timeout))
288                 rreq = rreq.WithContext(ctx)
289         } else {
290                 rclient.RetryMax = 0
291         }
292         rclient.CheckRetry = func(ctx context.Context, resp *http.Response, respErr error) (bool, error) {
293                 checkRetryCalled++
294                 if c.requestLimiter.Report(resp, respErr) {
295                         c.last503.Store(time.Now())
296                 }
297                 if c.Timeout == 0 {
298                         return false, nil
299                 }
300                 if respErr != nil && reqErrorRe.MatchString(respErr.Error()) {
301                         return false, nil
302                 }
303                 retrying, err := retryablehttp.DefaultRetryPolicy(ctx, resp, respErr)
304                 if retrying {
305                         lastResp, lastRespBody, lastErr = resp, nil, respErr
306                         if respErr == nil {
307                                 // Save the response and body so we
308                                 // can return it instead of "deadline
309                                 // exceeded". retryablehttp.Client
310                                 // will drain and discard resp.body,
311                                 // so we need to stash it separately.
312                                 buf, err := ioutil.ReadAll(resp.Body)
313                                 if err == nil {
314                                         lastRespBody = io.NopCloser(bytes.NewReader(buf))
315                                 } else {
316                                         lastResp, lastErr = nil, err
317                                 }
318                         }
319                 }
320                 return retrying, err
321         }
322         rclient.Logger = nil
323
324         c.requestLimiter.Acquire(ctx)
325         if ctx.Err() != nil {
326                 c.requestLimiter.Release()
327                 cancel()
328                 return nil, ctx.Err()
329         }
330         resp, err := rclient.Do(rreq)
331         if (errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled)) && (lastResp != nil || lastErr != nil) {
332                 resp = lastResp
333                 err = lastErr
334                 if checkRetryCalled > 0 && err != nil {
335                         // Mimic retryablehttp's "giving up after X
336                         // attempts" message, even if we gave up
337                         // because of time rather than maxretries.
338                         err = fmt.Errorf("%s %s giving up after %d attempt(s): %w", req.Method, req.URL.String(), checkRetryCalled, err)
339                 }
340                 if resp != nil {
341                         resp.Body = lastRespBody
342                 }
343         }
344         if err != nil {
345                 c.requestLimiter.Release()
346                 cancel()
347                 return nil, err
348         }
349         // We need to call cancel() eventually, but we can't use
350         // "defer cancel()" because the context has to stay alive
351         // until the caller has finished reading the response body.
352         resp.Body = cancelOnClose{
353                 ReadCloser: resp.Body,
354                 cancel: func() {
355                         c.requestLimiter.Release()
356                         cancel()
357                 },
358         }
359         return resp, err
360 }
361
362 // Last503 returns the time of the most recent HTTP 503 (Service
363 // Unavailable) response. Zero time indicates never.
364 func (c *Client) Last503() time.Time {
365         t, _ := c.last503.Load().(time.Time)
366         return t
367 }
368
369 // cancelOnClose calls a provided CancelFunc when its wrapped
370 // ReadCloser's Close() method is called.
371 type cancelOnClose struct {
372         io.ReadCloser
373         cancel context.CancelFunc
374 }
375
376 func (coc cancelOnClose) Close() error {
377         err := coc.ReadCloser.Close()
378         coc.cancel()
379         return err
380 }
381
382 func isRedirectStatus(code int) bool {
383         switch code {
384         case http.StatusMovedPermanently, http.StatusFound, http.StatusSeeOther, http.StatusTemporaryRedirect, http.StatusPermanentRedirect:
385                 return true
386         default:
387                 return false
388         }
389 }
390
391 const minExponentialBackoffBase = time.Second
392
393 // Implements retryablehttp.Backoff using the server-provided
394 // Retry-After header if available, otherwise nearly-full jitter
395 // exponential backoff (similar to
396 // https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/),
397 // in all cases respecting the provided min and max.
398 func exponentialBackoff(min, max time.Duration, attemptNum int, resp *http.Response) time.Duration {
399         if attemptNum > 0 && min < minExponentialBackoffBase {
400                 min = minExponentialBackoffBase
401         }
402         var t time.Duration
403         if resp != nil && (resp.StatusCode == http.StatusTooManyRequests || resp.StatusCode == http.StatusServiceUnavailable) {
404                 if s := resp.Header.Get("Retry-After"); s != "" {
405                         if sleep, err := strconv.ParseInt(s, 10, 64); err == nil {
406                                 t = time.Second * time.Duration(sleep)
407                         } else if stamp, err := time.Parse(time.RFC1123, s); err == nil {
408                                 t = stamp.Sub(time.Now())
409                         }
410                 }
411         }
412         if t == 0 {
413                 jitter := mathrand.New(mathrand.NewSource(int64(time.Now().Nanosecond()))).Float64()
414                 t = min + time.Duration((math.Pow(2, float64(attemptNum))*float64(min)-float64(min))*jitter)
415         }
416         if t < min {
417                 return min
418         } else if t > max {
419                 return max
420         } else {
421                 return t
422         }
423 }
424
425 // DoAndDecode performs req and unmarshals the response (which must be
426 // JSON) into dst. Use this instead of RequestAndDecode if you need
427 // more control of the http.Request object.
428 //
429 // If the response status indicates an HTTP redirect, the Location
430 // header value is unmarshalled to dst as a RedirectLocation
431 // key/field.
432 func (c *Client) DoAndDecode(dst interface{}, req *http.Request) error {
433         resp, err := c.Do(req)
434         if err != nil {
435                 return err
436         }
437         defer resp.Body.Close()
438         buf, err := ioutil.ReadAll(resp.Body)
439         if err != nil {
440                 return err
441         }
442         switch {
443         case resp.StatusCode == http.StatusNoContent:
444                 return nil
445         case resp.StatusCode == http.StatusOK && dst == nil:
446                 return nil
447         case resp.StatusCode == http.StatusOK:
448                 return json.Unmarshal(buf, dst)
449
450         // If the caller uses a client with a custom CheckRedirect
451         // func, Do() might return the 3xx response instead of
452         // following it.
453         case isRedirectStatus(resp.StatusCode) && dst == nil:
454                 return nil
455         case isRedirectStatus(resp.StatusCode):
456                 // Copy the redirect target URL to dst.RedirectLocation.
457                 buf, err := json.Marshal(map[string]string{"redirect_location": resp.Header.Get("Location")})
458                 if err != nil {
459                         return err
460                 }
461                 return json.Unmarshal(buf, dst)
462
463         default:
464                 return newTransactionError(req, resp, buf)
465         }
466 }
467
468 // Convert an arbitrary struct to url.Values. For example,
469 //
470 //      Foo{Bar: []int{1,2,3}, Baz: "waz"}
471 //
472 // becomes
473 //
474 //      url.Values{`bar`:`{"a":[1,2,3]}`,`Baz`:`waz`}
475 //
476 // params itself is returned if it is already an url.Values.
477 func anythingToValues(params interface{}) (url.Values, error) {
478         if v, ok := params.(url.Values); ok {
479                 return v, nil
480         }
481         // TODO: Do this more efficiently, possibly using
482         // json.Decode/Encode, so the whole thing doesn't have to get
483         // encoded, decoded, and re-encoded.
484         j, err := json.Marshal(params)
485         if err != nil {
486                 return nil, err
487         }
488         var generic map[string]interface{}
489         dec := json.NewDecoder(bytes.NewBuffer(j))
490         dec.UseNumber()
491         err = dec.Decode(&generic)
492         if err != nil {
493                 return nil, err
494         }
495         urlValues := url.Values{}
496         for k, v := range generic {
497                 if v, ok := v.(string); ok {
498                         urlValues.Set(k, v)
499                         continue
500                 }
501                 if v, ok := v.(json.Number); ok {
502                         urlValues.Set(k, v.String())
503                         continue
504                 }
505                 if v, ok := v.(bool); ok {
506                         if v {
507                                 urlValues.Set(k, "true")
508                         } else {
509                                 // "foo=false", "foo=0", and "foo="
510                                 // are all taken as true strings, so
511                                 // don't send false values at all --
512                                 // rely on the default being false.
513                         }
514                         continue
515                 }
516                 j, err := json.Marshal(v)
517                 if err != nil {
518                         return nil, err
519                 }
520                 if bytes.Equal(j, []byte("null")) {
521                         // don't add it to urlValues at all
522                         continue
523                 }
524                 urlValues.Set(k, string(j))
525         }
526         return urlValues, nil
527 }
528
529 // RequestAndDecode performs an API request and unmarshals the
530 // response (which must be JSON) into dst. Method and body arguments
531 // are the same as for http.NewRequest(). The given path is added to
532 // the server's scheme/host/port to form the request URL. The given
533 // params are passed via POST form or query string.
534 //
535 // path must not contain a query string.
536 func (c *Client) RequestAndDecode(dst interface{}, method, path string, body io.Reader, params interface{}) error {
537         return c.RequestAndDecodeContext(context.Background(), dst, method, path, body, params)
538 }
539
540 // RequestAndDecodeContext does the same as RequestAndDecode, but with a context
541 func (c *Client) RequestAndDecodeContext(ctx context.Context, dst interface{}, method, path string, body io.Reader, params interface{}) error {
542         if body, ok := body.(io.Closer); ok {
543                 // Ensure body is closed even if we error out early
544                 defer body.Close()
545         }
546         if c.APIHost == "" {
547                 if c.loadedFromEnv {
548                         return errors.New("ARVADOS_API_HOST and/or ARVADOS_API_TOKEN environment variables are not set")
549                 }
550                 return errors.New("arvados.Client cannot perform request: APIHost is not set")
551         }
552         urlString := c.apiURL(path)
553         urlValues, err := anythingToValues(params)
554         if err != nil {
555                 return err
556         }
557         if dst == nil {
558                 if urlValues == nil {
559                         urlValues = url.Values{}
560                 }
561                 urlValues["select"] = []string{`["uuid"]`}
562         }
563         if urlValues == nil {
564                 // Nothing to send
565         } else if body != nil || ((method == "GET" || method == "HEAD") && len(urlValues.Encode()) < 1000) {
566                 // Send params in query part of URL
567                 u, err := url.Parse(urlString)
568                 if err != nil {
569                         return err
570                 }
571                 u.RawQuery = urlValues.Encode()
572                 urlString = u.String()
573         } else {
574                 body = strings.NewReader(urlValues.Encode())
575         }
576         req, err := http.NewRequest(method, urlString, body)
577         if err != nil {
578                 return err
579         }
580         if (method == "GET" || method == "HEAD") && body != nil {
581                 req.Header.Set("X-Http-Method-Override", method)
582                 req.Method = "POST"
583         }
584         req = req.WithContext(ctx)
585         req.Header.Set("Content-type", "application/x-www-form-urlencoded")
586         for k, v := range c.SendHeader {
587                 req.Header[k] = v
588         }
589         return c.DoAndDecode(dst, req)
590 }
591
592 type resource interface {
593         resourceName() string
594 }
595
596 // UpdateBody returns an io.Reader suitable for use as an http.Request
597 // Body for a create or update API call.
598 func (c *Client) UpdateBody(rsc resource) io.Reader {
599         j, err := json.Marshal(rsc)
600         if err != nil {
601                 // Return a reader that returns errors.
602                 r, w := io.Pipe()
603                 w.CloseWithError(err)
604                 return r
605         }
606         v := url.Values{rsc.resourceName(): {string(j)}}
607         return bytes.NewBufferString(v.Encode())
608 }
609
610 // WithRequestID returns a new shallow copy of c that sends the given
611 // X-Request-Id value (instead of a new randomly generated one) with
612 // each subsequent request that doesn't provide its own via context or
613 // header.
614 func (c *Client) WithRequestID(reqid string) *Client {
615         cc := *c
616         cc.defaultRequestID = reqid
617         return &cc
618 }
619
620 func (c *Client) httpClient() *http.Client {
621         switch {
622         case c.Client != nil:
623                 return c.Client
624         case c.Insecure:
625                 return InsecureHTTPClient
626         default:
627                 return DefaultSecureClient
628         }
629 }
630
631 func (c *Client) apiURL(path string) string {
632         scheme := c.Scheme
633         if scheme == "" {
634                 scheme = "https"
635         }
636         // Double-slash in URLs tend to cause subtle hidden problems
637         // (e.g., they can behave differently when a load balancer is
638         // in the picture). Here we ensure exactly one "/" regardless
639         // of whether the given APIHost or path has a superfluous one.
640         return scheme + "://" + strings.TrimSuffix(c.APIHost, "/") + "/" + strings.TrimPrefix(path, "/")
641 }
642
643 // DiscoveryDocument is the Arvados server's description of itself.
644 type DiscoveryDocument struct {
645         BasePath                     string              `json:"basePath"`
646         DefaultCollectionReplication int                 `json:"defaultCollectionReplication"`
647         BlobSignatureTTL             int64               `json:"blobSignatureTtl"`
648         GitURL                       string              `json:"gitUrl"`
649         Schemas                      map[string]Schema   `json:"schemas"`
650         Resources                    map[string]Resource `json:"resources"`
651         Revision                     string              `json:"revision"`
652 }
653
654 type Resource struct {
655         Methods map[string]ResourceMethod `json:"methods"`
656 }
657
658 type ResourceMethod struct {
659         HTTPMethod string         `json:"httpMethod"`
660         Path       string         `json:"path"`
661         Response   MethodResponse `json:"response"`
662 }
663
664 type MethodResponse struct {
665         Ref string `json:"$ref"`
666 }
667
668 type Schema struct {
669         UUIDPrefix string `json:"uuidPrefix"`
670 }
671
672 // DiscoveryDocument returns a *DiscoveryDocument. The returned object
673 // should not be modified: the same object may be returned by
674 // subsequent calls.
675 func (c *Client) DiscoveryDocument() (*DiscoveryDocument, error) {
676         if c.dd != nil {
677                 return c.dd, nil
678         }
679         var dd DiscoveryDocument
680         err := c.RequestAndDecode(&dd, "GET", "discovery/v1/apis/arvados/v1/rest", nil, nil)
681         if err != nil {
682                 return nil, err
683         }
684         c.dd = &dd
685         return c.dd, nil
686 }
687
688 var pdhRegexp = regexp.MustCompile(`^[0-9a-f]{32}\+\d+$`)
689
690 func (c *Client) modelForUUID(dd *DiscoveryDocument, uuid string) (string, error) {
691         if pdhRegexp.MatchString(uuid) {
692                 return "Collection", nil
693         }
694         if len(uuid) != 27 {
695                 return "", fmt.Errorf("invalid UUID: %q", uuid)
696         }
697         infix := uuid[6:11]
698         var model string
699         for m, s := range dd.Schemas {
700                 if s.UUIDPrefix == infix {
701                         model = m
702                         break
703                 }
704         }
705         if model == "" {
706                 return "", fmt.Errorf("unrecognized type portion %q in UUID %q", infix, uuid)
707         }
708         return model, nil
709 }
710
711 func (c *Client) KindForUUID(uuid string) (string, error) {
712         dd, err := c.DiscoveryDocument()
713         if err != nil {
714                 return "", err
715         }
716         model, err := c.modelForUUID(dd, uuid)
717         if err != nil {
718                 return "", err
719         }
720         return "arvados#" + strings.ToLower(model[:1]) + model[1:], nil
721 }
722
723 func (c *Client) PathForUUID(method, uuid string) (string, error) {
724         dd, err := c.DiscoveryDocument()
725         if err != nil {
726                 return "", err
727         }
728         model, err := c.modelForUUID(dd, uuid)
729         if err != nil {
730                 return "", err
731         }
732         var resource string
733         for r, rsc := range dd.Resources {
734                 if rsc.Methods["get"].Response.Ref == model {
735                         resource = r
736                         break
737                 }
738         }
739         if resource == "" {
740                 return "", fmt.Errorf("no resource for model: %q", model)
741         }
742         m, ok := dd.Resources[resource].Methods[method]
743         if !ok {
744                 return "", fmt.Errorf("no method %q for resource %q", method, resource)
745         }
746         path := dd.BasePath + strings.Replace(m.Path, "{uuid}", uuid, -1)
747         if path[0] == '/' {
748                 path = path[1:]
749         }
750         return path, nil
751 }
752
753 var maxUUIDInt = (&big.Int{}).Exp(big.NewInt(36), big.NewInt(15), nil)
754
755 func RandomUUID(clusterID, infix string) string {
756         n, err := rand.Int(rand.Reader, maxUUIDInt)
757         if err != nil {
758                 panic(err)
759         }
760         nstr := n.Text(36)
761         for len(nstr) < 15 {
762                 nstr = "0" + nstr
763         }
764         return clusterID + "-" + infix + "-" + nstr
765 }