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