20540: Implement nearly-full jitter for exponential backoff.
[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 // Do augments (*http.Client)Do(): adds Authorization and X-Request-Id
242 // headers, delays in order to comply with rate-limiting restrictions,
243 // and retries failed requests when appropriate.
244 func (c *Client) Do(req *http.Request) (*http.Response, error) {
245         ctx := req.Context()
246         if auth, _ := ctx.Value(contextKeyAuthorization{}).(string); auth != "" {
247                 req.Header.Add("Authorization", auth)
248         } else if c.AuthToken != "" {
249                 req.Header.Add("Authorization", "OAuth2 "+c.AuthToken)
250         }
251
252         if req.Header.Get("X-Request-Id") == "" {
253                 var reqid string
254                 if ctxreqid, _ := ctx.Value(contextKeyRequestID{}).(string); ctxreqid != "" {
255                         reqid = ctxreqid
256                 } else if c.defaultRequestID != "" {
257                         reqid = c.defaultRequestID
258                 } else {
259                         reqid = reqIDGen.Next()
260                 }
261                 if req.Header == nil {
262                         req.Header = http.Header{"X-Request-Id": {reqid}}
263                 } else {
264                         req.Header.Set("X-Request-Id", reqid)
265                 }
266         }
267
268         rreq, err := retryablehttp.FromRequest(req)
269         if err != nil {
270                 return nil, err
271         }
272
273         cancel := nopCancelFunc
274         var lastResp *http.Response
275         var lastRespBody io.ReadCloser
276         var lastErr error
277
278         rclient := retryablehttp.NewClient()
279         rclient.HTTPClient = c.httpClient()
280         rclient.Backoff = exponentialBackoff
281         if c.Timeout > 0 {
282                 rclient.RetryWaitMax = c.Timeout / 10
283                 rclient.RetryMax = 32
284                 ctx, cancel = context.WithDeadline(ctx, time.Now().Add(c.Timeout))
285                 rreq = rreq.WithContext(ctx)
286         } else {
287                 rclient.RetryMax = 0
288         }
289         rclient.CheckRetry = func(ctx context.Context, resp *http.Response, respErr error) (bool, error) {
290                 if c.requestLimiter.Report(resp, respErr) {
291                         c.last503.Store(time.Now())
292                 }
293                 if c.Timeout == 0 {
294                         return false, err
295                 }
296                 retrying, err := retryablehttp.DefaultRetryPolicy(ctx, resp, respErr)
297                 if retrying {
298                         lastResp, lastRespBody, lastErr = resp, nil, respErr
299                         if respErr == nil {
300                                 // Save the response and body so we
301                                 // can return it instead of "deadline
302                                 // exceeded". retryablehttp.Client
303                                 // will drain and discard resp.body,
304                                 // so we need to stash it separately.
305                                 buf, err := ioutil.ReadAll(resp.Body)
306                                 if err == nil {
307                                         lastRespBody = io.NopCloser(bytes.NewReader(buf))
308                                 } else {
309                                         lastResp, lastErr = nil, err
310                                 }
311                         }
312                 }
313                 return retrying, err
314         }
315         rclient.Logger = nil
316
317         c.requestLimiter.Acquire(ctx)
318         if ctx.Err() != nil {
319                 c.requestLimiter.Release()
320                 cancel()
321                 return nil, ctx.Err()
322         }
323         resp, err := rclient.Do(rreq)
324         if (errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled)) && (lastResp != nil || lastErr != nil) {
325                 resp, err = lastResp, lastErr
326                 if resp != nil {
327                         resp.Body = lastRespBody
328                 }
329         }
330         if err != nil {
331                 c.requestLimiter.Release()
332                 cancel()
333                 return nil, err
334         }
335         // We need to call cancel() eventually, but we can't use
336         // "defer cancel()" because the context has to stay alive
337         // until the caller has finished reading the response body.
338         resp.Body = cancelOnClose{
339                 ReadCloser: resp.Body,
340                 cancel: func() {
341                         c.requestLimiter.Release()
342                         cancel()
343                 },
344         }
345         return resp, err
346 }
347
348 // Last503 returns the time of the most recent HTTP 503 (Service
349 // Unavailable) response. Zero time indicates never.
350 func (c *Client) Last503() time.Time {
351         t, _ := c.last503.Load().(time.Time)
352         return t
353 }
354
355 // cancelOnClose calls a provided CancelFunc when its wrapped
356 // ReadCloser's Close() method is called.
357 type cancelOnClose struct {
358         io.ReadCloser
359         cancel context.CancelFunc
360 }
361
362 func (coc cancelOnClose) Close() error {
363         err := coc.ReadCloser.Close()
364         coc.cancel()
365         return err
366 }
367
368 func isRedirectStatus(code int) bool {
369         switch code {
370         case http.StatusMovedPermanently, http.StatusFound, http.StatusSeeOther, http.StatusTemporaryRedirect, http.StatusPermanentRedirect:
371                 return true
372         default:
373                 return false
374         }
375 }
376
377 // Implements retryablehttp.Backoff using the server-provided
378 // Retry-After header if available, otherwise nearly-full jitter
379 // exponential backoff (similar to
380 // https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/),
381 // in all cases respecting the provided min and max.
382 func exponentialBackoff(min, max time.Duration, attemptNum int, resp *http.Response) time.Duration {
383         var t time.Duration
384         if resp != nil && (resp.StatusCode == http.StatusTooManyRequests || resp.StatusCode == http.StatusServiceUnavailable) {
385                 if s := resp.Header.Get("Retry-After"); s != "" {
386                         if sleep, err := strconv.ParseInt(s, 10, 64); err == nil {
387                                 t = time.Second * time.Duration(sleep)
388                         } else if stamp, err := time.Parse(time.RFC1123, s); err == nil {
389                                 t = stamp.Sub(time.Now())
390                         }
391                 }
392         }
393         if t == 0 {
394                 jitter := mathrand.New(mathrand.NewSource(int64(time.Now().Nanosecond()))).Float64()
395                 t = min + time.Duration((math.Pow(2, float64(attemptNum))*float64(min)-float64(min))*jitter)
396         }
397         if t < min {
398                 return min
399         } else if t > max {
400                 return max
401         } else {
402                 return t
403         }
404 }
405
406 // DoAndDecode performs req and unmarshals the response (which must be
407 // JSON) into dst. Use this instead of RequestAndDecode if you need
408 // more control of the http.Request object.
409 //
410 // If the response status indicates an HTTP redirect, the Location
411 // header value is unmarshalled to dst as a RedirectLocation
412 // key/field.
413 func (c *Client) DoAndDecode(dst interface{}, req *http.Request) error {
414         resp, err := c.Do(req)
415         if err != nil {
416                 return err
417         }
418         defer resp.Body.Close()
419         buf, err := ioutil.ReadAll(resp.Body)
420         if err != nil {
421                 return err
422         }
423         switch {
424         case resp.StatusCode == http.StatusNoContent:
425                 return nil
426         case resp.StatusCode == http.StatusOK && dst == nil:
427                 return nil
428         case resp.StatusCode == http.StatusOK:
429                 return json.Unmarshal(buf, dst)
430
431         // If the caller uses a client with a custom CheckRedirect
432         // func, Do() might return the 3xx response instead of
433         // following it.
434         case isRedirectStatus(resp.StatusCode) && dst == nil:
435                 return nil
436         case isRedirectStatus(resp.StatusCode):
437                 // Copy the redirect target URL to dst.RedirectLocation.
438                 buf, err := json.Marshal(map[string]string{"redirect_location": resp.Header.Get("Location")})
439                 if err != nil {
440                         return err
441                 }
442                 return json.Unmarshal(buf, dst)
443
444         default:
445                 return newTransactionError(req, resp, buf)
446         }
447 }
448
449 // Convert an arbitrary struct to url.Values. For example,
450 //
451 //      Foo{Bar: []int{1,2,3}, Baz: "waz"}
452 //
453 // becomes
454 //
455 //      url.Values{`bar`:`{"a":[1,2,3]}`,`Baz`:`waz`}
456 //
457 // params itself is returned if it is already an url.Values.
458 func anythingToValues(params interface{}) (url.Values, error) {
459         if v, ok := params.(url.Values); ok {
460                 return v, nil
461         }
462         // TODO: Do this more efficiently, possibly using
463         // json.Decode/Encode, so the whole thing doesn't have to get
464         // encoded, decoded, and re-encoded.
465         j, err := json.Marshal(params)
466         if err != nil {
467                 return nil, err
468         }
469         var generic map[string]interface{}
470         dec := json.NewDecoder(bytes.NewBuffer(j))
471         dec.UseNumber()
472         err = dec.Decode(&generic)
473         if err != nil {
474                 return nil, err
475         }
476         urlValues := url.Values{}
477         for k, v := range generic {
478                 if v, ok := v.(string); ok {
479                         urlValues.Set(k, v)
480                         continue
481                 }
482                 if v, ok := v.(json.Number); ok {
483                         urlValues.Set(k, v.String())
484                         continue
485                 }
486                 if v, ok := v.(bool); ok {
487                         if v {
488                                 urlValues.Set(k, "true")
489                         } else {
490                                 // "foo=false", "foo=0", and "foo="
491                                 // are all taken as true strings, so
492                                 // don't send false values at all --
493                                 // rely on the default being false.
494                         }
495                         continue
496                 }
497                 j, err := json.Marshal(v)
498                 if err != nil {
499                         return nil, err
500                 }
501                 if bytes.Equal(j, []byte("null")) {
502                         // don't add it to urlValues at all
503                         continue
504                 }
505                 urlValues.Set(k, string(j))
506         }
507         return urlValues, nil
508 }
509
510 // RequestAndDecode performs an API request and unmarshals the
511 // response (which must be JSON) into dst. Method and body arguments
512 // are the same as for http.NewRequest(). The given path is added to
513 // the server's scheme/host/port to form the request URL. The given
514 // params are passed via POST form or query string.
515 //
516 // path must not contain a query string.
517 func (c *Client) RequestAndDecode(dst interface{}, method, path string, body io.Reader, params interface{}) error {
518         return c.RequestAndDecodeContext(context.Background(), dst, method, path, body, params)
519 }
520
521 // RequestAndDecodeContext does the same as RequestAndDecode, but with a context
522 func (c *Client) RequestAndDecodeContext(ctx context.Context, dst interface{}, method, path string, body io.Reader, params interface{}) error {
523         if body, ok := body.(io.Closer); ok {
524                 // Ensure body is closed even if we error out early
525                 defer body.Close()
526         }
527         if c.APIHost == "" {
528                 if c.loadedFromEnv {
529                         return errors.New("ARVADOS_API_HOST and/or ARVADOS_API_TOKEN environment variables are not set")
530                 }
531                 return errors.New("arvados.Client cannot perform request: APIHost is not set")
532         }
533         urlString := c.apiURL(path)
534         urlValues, err := anythingToValues(params)
535         if err != nil {
536                 return err
537         }
538         if urlValues == nil {
539                 // Nothing to send
540         } else if body != nil || ((method == "GET" || method == "HEAD") && len(urlValues.Encode()) < 1000) {
541                 // Send params in query part of URL
542                 u, err := url.Parse(urlString)
543                 if err != nil {
544                         return err
545                 }
546                 u.RawQuery = urlValues.Encode()
547                 urlString = u.String()
548         } else {
549                 body = strings.NewReader(urlValues.Encode())
550         }
551         req, err := http.NewRequest(method, urlString, body)
552         if err != nil {
553                 return err
554         }
555         if (method == "GET" || method == "HEAD") && body != nil {
556                 req.Header.Set("X-Http-Method-Override", method)
557                 req.Method = "POST"
558         }
559         req = req.WithContext(ctx)
560         req.Header.Set("Content-type", "application/x-www-form-urlencoded")
561         for k, v := range c.SendHeader {
562                 req.Header[k] = v
563         }
564         return c.DoAndDecode(dst, req)
565 }
566
567 type resource interface {
568         resourceName() string
569 }
570
571 // UpdateBody returns an io.Reader suitable for use as an http.Request
572 // Body for a create or update API call.
573 func (c *Client) UpdateBody(rsc resource) io.Reader {
574         j, err := json.Marshal(rsc)
575         if err != nil {
576                 // Return a reader that returns errors.
577                 r, w := io.Pipe()
578                 w.CloseWithError(err)
579                 return r
580         }
581         v := url.Values{rsc.resourceName(): {string(j)}}
582         return bytes.NewBufferString(v.Encode())
583 }
584
585 // WithRequestID returns a new shallow copy of c that sends the given
586 // X-Request-Id value (instead of a new randomly generated one) with
587 // each subsequent request that doesn't provide its own via context or
588 // header.
589 func (c *Client) WithRequestID(reqid string) *Client {
590         cc := *c
591         cc.defaultRequestID = reqid
592         return &cc
593 }
594
595 func (c *Client) httpClient() *http.Client {
596         switch {
597         case c.Client != nil:
598                 return c.Client
599         case c.Insecure:
600                 return InsecureHTTPClient
601         default:
602                 return DefaultSecureClient
603         }
604 }
605
606 func (c *Client) apiURL(path string) string {
607         scheme := c.Scheme
608         if scheme == "" {
609                 scheme = "https"
610         }
611         return scheme + "://" + c.APIHost + "/" + path
612 }
613
614 // DiscoveryDocument is the Arvados server's description of itself.
615 type DiscoveryDocument struct {
616         BasePath                     string              `json:"basePath"`
617         DefaultCollectionReplication int                 `json:"defaultCollectionReplication"`
618         BlobSignatureTTL             int64               `json:"blobSignatureTtl"`
619         GitURL                       string              `json:"gitUrl"`
620         Schemas                      map[string]Schema   `json:"schemas"`
621         Resources                    map[string]Resource `json:"resources"`
622 }
623
624 type Resource struct {
625         Methods map[string]ResourceMethod `json:"methods"`
626 }
627
628 type ResourceMethod struct {
629         HTTPMethod string         `json:"httpMethod"`
630         Path       string         `json:"path"`
631         Response   MethodResponse `json:"response"`
632 }
633
634 type MethodResponse struct {
635         Ref string `json:"$ref"`
636 }
637
638 type Schema struct {
639         UUIDPrefix string `json:"uuidPrefix"`
640 }
641
642 // DiscoveryDocument returns a *DiscoveryDocument. The returned object
643 // should not be modified: the same object may be returned by
644 // subsequent calls.
645 func (c *Client) DiscoveryDocument() (*DiscoveryDocument, error) {
646         if c.dd != nil {
647                 return c.dd, nil
648         }
649         var dd DiscoveryDocument
650         err := c.RequestAndDecode(&dd, "GET", "discovery/v1/apis/arvados/v1/rest", nil, nil)
651         if err != nil {
652                 return nil, err
653         }
654         c.dd = &dd
655         return c.dd, nil
656 }
657
658 var pdhRegexp = regexp.MustCompile(`^[0-9a-f]{32}\+\d+$`)
659
660 func (c *Client) modelForUUID(dd *DiscoveryDocument, uuid string) (string, error) {
661         if pdhRegexp.MatchString(uuid) {
662                 return "Collection", nil
663         }
664         if len(uuid) != 27 {
665                 return "", fmt.Errorf("invalid UUID: %q", uuid)
666         }
667         infix := uuid[6:11]
668         var model string
669         for m, s := range dd.Schemas {
670                 if s.UUIDPrefix == infix {
671                         model = m
672                         break
673                 }
674         }
675         if model == "" {
676                 return "", fmt.Errorf("unrecognized type portion %q in UUID %q", infix, uuid)
677         }
678         return model, nil
679 }
680
681 func (c *Client) KindForUUID(uuid string) (string, error) {
682         dd, err := c.DiscoveryDocument()
683         if err != nil {
684                 return "", err
685         }
686         model, err := c.modelForUUID(dd, uuid)
687         if err != nil {
688                 return "", err
689         }
690         return "arvados#" + strings.ToLower(model[:1]) + model[1:], nil
691 }
692
693 func (c *Client) PathForUUID(method, uuid string) (string, error) {
694         dd, err := c.DiscoveryDocument()
695         if err != nil {
696                 return "", err
697         }
698         model, err := c.modelForUUID(dd, uuid)
699         if err != nil {
700                 return "", err
701         }
702         var resource string
703         for r, rsc := range dd.Resources {
704                 if rsc.Methods["get"].Response.Ref == model {
705                         resource = r
706                         break
707                 }
708         }
709         if resource == "" {
710                 return "", fmt.Errorf("no resource for model: %q", model)
711         }
712         m, ok := dd.Resources[resource].Methods[method]
713         if !ok {
714                 return "", fmt.Errorf("no method %q for resource %q", method, resource)
715         }
716         path := dd.BasePath + strings.Replace(m.Path, "{uuid}", uuid, -1)
717         if path[0] == '/' {
718                 path = path[1:]
719         }
720         return path, nil
721 }
722
723 var maxUUIDInt = (&big.Int{}).Exp(big.NewInt(36), big.NewInt(15), nil)
724
725 func RandomUUID(clusterID, infix string) string {
726         n, err := rand.Int(rand.Reader, maxUUIDInt)
727         if err != nil {
728                 panic(err)
729         }
730         nstr := n.Text(36)
731         for len(nstr) < 15 {
732                 nstr = "0" + nstr
733         }
734         return clusterID + "-" + infix + "-" + nstr
735 }