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