vitess.io/vitess@v0.16.2/go/vt/vtadmin/cluster/dynamic/cluster.go (about)

     1  package dynamic
     2  
     3  import (
     4  	"context"
     5  	"encoding/base64"
     6  	"strings"
     7  
     8  	"vitess.io/vitess/go/vt/vtadmin/cluster"
     9  )
    10  
    11  // ClusterFromString returns a cluster ID and possibly fully-usable Cluster
    12  // from a base64-encoded JSON spec.
    13  //
    14  // If an error occurs decoding or unmarshalling the string, this function
    15  // returns, respectively, the empty string, a nil Cluster, and a non-nil error.
    16  //
    17  // If the string can be decoded and unmarshalled, then the id will be non-empty,
    18  // but errors may still be returned from instantiating the cluster, for example
    19  // if the configuration in the JSON spec is invalid.
    20  //
    21  // Therefore, callers should handle the return values as follows:
    22  //
    23  //	c, id, err := dynamic.ClusterFromString(ctx, s)
    24  //	if id == "" {
    25  //		// handle err, do not use `c`.
    26  //	}
    27  //	if err != nil {
    28  //		// log error. if desired, lookup the existing cluster with ID: `id`
    29  //	}
    30  //	// Use `c` (or existing cluster with ID == `id`) based on the dynamic cluster
    31  //	api.WithCluster(c, id).DoAThing()
    32  func ClusterFromString(ctx context.Context, s string) (c *cluster.Cluster, id string, err error) {
    33  	cfg, id, err := cluster.LoadConfig(base64.NewDecoder(base64.StdEncoding, strings.NewReader(s)), "json")
    34  	if err != nil {
    35  		return nil, id, err
    36  	}
    37  
    38  	c, err = cfg.Cluster(ctx)
    39  	return c, id, err
    40  }