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