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