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