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