Merge branch '20522-load-dispatch-priv-key'
[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 const minExponentialBackoffBase = time.Second
378
379 // Implements retryablehttp.Backoff using the server-provided
380 // Retry-After header if available, otherwise nearly-full jitter
381 // exponential backoff (similar to
382 // https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/),
383 // in all cases respecting the provided min and max.
384 func exponentialBackoff(min, max time.Duration, attemptNum int, resp *http.Response) time.Duration {
385         if attemptNum > 0 && min < minExponentialBackoffBase {
386                 min = minExponentialBackoffBase
387         }
388         var t time.Duration
389         if resp != nil && (resp.StatusCode == http.StatusTooManyRequests || resp.StatusCode == http.StatusServiceUnavailable) {
390                 if s := resp.Header.Get("Retry-After"); s != "" {
391                         if sleep, err := strconv.ParseInt(s, 10, 64); err == nil {
392                                 t = time.Second * time.Duration(sleep)
393                         } else if stamp, err := time.Parse(time.RFC1123, s); err == nil {
394                                 t = stamp.Sub(time.Now())
395                         }
396                 }
397         }
398         if t == 0 {
399                 jitter := mathrand.New(mathrand.NewSource(int64(time.Now().Nanosecond()))).Float64()
400                 t = min + time.Duration((math.Pow(2, float64(attemptNum))*float64(min)-float64(min))*jitter)
401         }
402         if t < min {
403                 return min
404         } else if t > max {
405                 return max
406         } else {
407                 return t
408         }
409 }
410
411 // DoAndDecode performs req and unmarshals the response (which must be
412 // JSON) into dst. Use this instead of RequestAndDecode if you need
413 // more control of the http.Request object.
414 //
415 // If the response status indicates an HTTP redirect, the Location
416 // header value is unmarshalled to dst as a RedirectLocation
417 // key/field.
418 func (c *Client) DoAndDecode(dst interface{}, req *http.Request) error {
419         resp, err := c.Do(req)
420         if err != nil {
421                 return err
422         }
423         defer resp.Body.Close()
424         buf, err := ioutil.ReadAll(resp.Body)
425         if err != nil {
426                 return err
427         }
428         switch {
429         case resp.StatusCode == http.StatusNoContent:
430                 return nil
431         case resp.StatusCode == http.StatusOK && dst == nil:
432                 return nil
433         case resp.StatusCode == http.StatusOK:
434                 return json.Unmarshal(buf, dst)
435
436         // If the caller uses a client with a custom CheckRedirect
437         // func, Do() might return the 3xx response instead of
438         // following it.
439         case isRedirectStatus(resp.StatusCode) && dst == nil:
440                 return nil
441         case isRedirectStatus(resp.StatusCode):
442                 // Copy the redirect target URL to dst.RedirectLocation.
443                 buf, err := json.Marshal(map[string]string{"redirect_location": resp.Header.Get("Location")})
444                 if err != nil {
445                         return err
446                 }
447                 return json.Unmarshal(buf, dst)
448
449         default:
450                 return newTransactionError(req, resp, buf)
451         }
452 }
453
454 // Convert an arbitrary struct to url.Values. For example,
455 //
456 //      Foo{Bar: []int{1,2,3}, Baz: "waz"}
457 //
458 // becomes
459 //
460 //      url.Values{`bar`:`{"a":[1,2,3]}`,`Baz`:`waz`}
461 //
462 // params itself is returned if it is already an url.Values.
463 func anythingToValues(params interface{}) (url.Values, error) {
464         if v, ok := params.(url.Values); ok {
465                 return v, nil
466         }
467         // TODO: Do this more efficiently, possibly using
468         // json.Decode/Encode, so the whole thing doesn't have to get
469         // encoded, decoded, and re-encoded.
470         j, err := json.Marshal(params)
471         if err != nil {
472                 return nil, err
473         }
474         var generic map[string]interface{}
475         dec := json.NewDecoder(bytes.NewBuffer(j))
476         dec.UseNumber()
477         err = dec.Decode(&generic)
478         if err != nil {
479                 return nil, err
480         }
481         urlValues := url.Values{}
482         for k, v := range generic {
483                 if v, ok := v.(string); ok {
484                         urlValues.Set(k, v)
485                         continue
486                 }
487                 if v, ok := v.(json.Number); ok {
488                         urlValues.Set(k, v.String())
489                         continue
490                 }
491                 if v, ok := v.(bool); ok {
492                         if v {
493                                 urlValues.Set(k, "true")
494                         } else {
495                                 // "foo=false", "foo=0", and "foo="
496                                 // are all taken as true strings, so
497                                 // don't send false values at all --
498                                 // rely on the default being false.
499                         }
500                         continue
501                 }
502                 j, err := json.Marshal(v)
503                 if err != nil {
504                         return nil, err
505                 }
506                 if bytes.Equal(j, []byte("null")) {
507                         // don't add it to urlValues at all
508                         continue
509                 }
510                 urlValues.Set(k, string(j))
511         }
512         return urlValues, nil
513 }
514
515 // RequestAndDecode performs an API request and unmarshals the
516 // response (which must be JSON) into dst. Method and body arguments
517 // are the same as for http.NewRequest(). The given path is added to
518 // the server's scheme/host/port to form the request URL. The given
519 // params are passed via POST form or query string.
520 //
521 // path must not contain a query string.
522 func (c *Client) RequestAndDecode(dst interface{}, method, path string, body io.Reader, params interface{}) error {
523         return c.RequestAndDecodeContext(context.Background(), dst, method, path, body, params)
524 }
525
526 // RequestAndDecodeContext does the same as RequestAndDecode, but with a context
527 func (c *Client) RequestAndDecodeContext(ctx context.Context, dst interface{}, method, path string, body io.Reader, params interface{}) error {
528         if body, ok := body.(io.Closer); ok {
529                 // Ensure body is closed even if we error out early
530                 defer body.Close()
531         }
532         if c.APIHost == "" {
533                 if c.loadedFromEnv {
534                         return errors.New("ARVADOS_API_HOST and/or ARVADOS_API_TOKEN environment variables are not set")
535                 }
536                 return errors.New("arvados.Client cannot perform request: APIHost is not set")
537         }
538         urlString := c.apiURL(path)
539         urlValues, err := anythingToValues(params)
540         if err != nil {
541                 return err
542         }
543         if dst == nil {
544                 if urlValues == nil {
545                         urlValues = url.Values{}
546                 }
547                 urlValues["select"] = []string{`["uuid"]`}
548         }
549         if urlValues == nil {
550                 // Nothing to send
551         } else if body != nil || ((method == "GET" || method == "HEAD") && len(urlValues.Encode()) < 1000) {
552                 // Send params in query part of URL
553                 u, err := url.Parse(urlString)
554                 if err != nil {
555                         return err
556                 }
557                 u.RawQuery = urlValues.Encode()
558                 urlString = u.String()
559         } else {
560                 body = strings.NewReader(urlValues.Encode())
561         }
562         req, err := http.NewRequest(method, urlString, body)
563         if err != nil {
564                 return err
565         }
566         if (method == "GET" || method == "HEAD") && body != nil {
567                 req.Header.Set("X-Http-Method-Override", method)
568                 req.Method = "POST"
569         }
570         req = req.WithContext(ctx)
571         req.Header.Set("Content-type", "application/x-www-form-urlencoded")
572         for k, v := range c.SendHeader {
573                 req.Header[k] = v
574         }
575         return c.DoAndDecode(dst, req)
576 }
577
578 type resource interface {
579         resourceName() string
580 }
581
582 // UpdateBody returns an io.Reader suitable for use as an http.Request
583 // Body for a create or update API call.
584 func (c *Client) UpdateBody(rsc resource) io.Reader {
585         j, err := json.Marshal(rsc)
586         if err != nil {
587                 // Return a reader that returns errors.
588                 r, w := io.Pipe()
589                 w.CloseWithError(err)
590                 return r
591         }
592         v := url.Values{rsc.resourceName(): {string(j)}}
593         return bytes.NewBufferString(v.Encode())
594 }
595
596 // WithRequestID returns a new shallow copy of c that sends the given
597 // X-Request-Id value (instead of a new randomly generated one) with
598 // each subsequent request that doesn't provide its own via context or
599 // header.
600 func (c *Client) WithRequestID(reqid string) *Client {
601         cc := *c
602         cc.defaultRequestID = reqid
603         return &cc
604 }
605
606 func (c *Client) httpClient() *http.Client {
607         switch {
608         case c.Client != nil:
609                 return c.Client
610         case c.Insecure:
611                 return InsecureHTTPClient
612         default:
613                 return DefaultSecureClient
614         }
615 }
616
617 func (c *Client) apiURL(path string) string {
618         scheme := c.Scheme
619         if scheme == "" {
620                 scheme = "https"
621         }
622         return scheme + "://" + c.APIHost + "/" + path
623 }
624
625 // DiscoveryDocument is the Arvados server's description of itself.
626 type DiscoveryDocument struct {
627         BasePath                     string              `json:"basePath"`
628         DefaultCollectionReplication int                 `json:"defaultCollectionReplication"`
629         BlobSignatureTTL             int64               `json:"blobSignatureTtl"`
630         GitURL                       string              `json:"gitUrl"`
631         Schemas                      map[string]Schema   `json:"schemas"`
632         Resources                    map[string]Resource `json:"resources"`
633 }
634
635 type Resource struct {
636         Methods map[string]ResourceMethod `json:"methods"`
637 }
638
639 type ResourceMethod struct {
640         HTTPMethod string         `json:"httpMethod"`
641         Path       string         `json:"path"`
642         Response   MethodResponse `json:"response"`
643 }
644
645 type MethodResponse struct {
646         Ref string `json:"$ref"`
647 }
648
649 type Schema struct {
650         UUIDPrefix string `json:"uuidPrefix"`
651 }
652
653 // DiscoveryDocument returns a *DiscoveryDocument. The returned object
654 // should not be modified: the same object may be returned by
655 // subsequent calls.
656 func (c *Client) DiscoveryDocument() (*DiscoveryDocument, error) {
657         if c.dd != nil {
658                 return c.dd, nil
659         }
660         var dd DiscoveryDocument
661         err := c.RequestAndDecode(&dd, "GET", "discovery/v1/apis/arvados/v1/rest", nil, nil)
662         if err != nil {
663                 return nil, err
664         }
665         c.dd = &dd
666         return c.dd, nil
667 }
668
669 var pdhRegexp = regexp.MustCompile(`^[0-9a-f]{32}\+\d+$`)
670
671 func (c *Client) modelForUUID(dd *DiscoveryDocument, uuid string) (string, error) {
672         if pdhRegexp.MatchString(uuid) {
673                 return "Collection", nil
674         }
675         if len(uuid) != 27 {
676                 return "", fmt.Errorf("invalid UUID: %q", uuid)
677         }
678         infix := uuid[6:11]
679         var model string
680         for m, s := range dd.Schemas {
681                 if s.UUIDPrefix == infix {
682                         model = m
683                         break
684                 }
685         }
686         if model == "" {
687                 return "", fmt.Errorf("unrecognized type portion %q in UUID %q", infix, uuid)
688         }
689         return model, nil
690 }
691
692 func (c *Client) KindForUUID(uuid string) (string, error) {
693         dd, err := c.DiscoveryDocument()
694         if err != nil {
695                 return "", err
696         }
697         model, err := c.modelForUUID(dd, uuid)
698         if err != nil {
699                 return "", err
700         }
701         return "arvados#" + strings.ToLower(model[:1]) + model[1:], nil
702 }
703
704 func (c *Client) PathForUUID(method, uuid string) (string, error) {
705         dd, err := c.DiscoveryDocument()
706         if err != nil {
707                 return "", err
708         }
709         model, err := c.modelForUUID(dd, uuid)
710         if err != nil {
711                 return "", err
712         }
713         var resource string
714         for r, rsc := range dd.Resources {
715                 if rsc.Methods["get"].Response.Ref == model {
716                         resource = r
717                         break
718                 }
719         }
720         if resource == "" {
721                 return "", fmt.Errorf("no resource for model: %q", model)
722         }
723         m, ok := dd.Resources[resource].Methods[method]
724         if !ok {
725                 return "", fmt.Errorf("no method %q for resource %q", method, resource)
726         }
727         path := dd.BasePath + strings.Replace(m.Path, "{uuid}", uuid, -1)
728         if path[0] == '/' {
729                 path = path[1:]
730         }
731         return path, nil
732 }
733
734 var maxUUIDInt = (&big.Int{}).Exp(big.NewInt(36), big.NewInt(15), nil)
735
736 func RandomUUID(clusterID, infix string) string {
737         n, err := rand.Int(rand.Reader, maxUUIDInt)
738         if err != nil {
739                 panic(err)
740         }
741         nstr := n.Text(36)
742         for len(nstr) < 15 {
743                 nstr = "0" + nstr
744         }
745         return clusterID + "-" + infix + "-" + nstr
746 }