github.com/openshift/installer@v1.4.17/pkg/asset/installconfig/clusterid.go (about)

     1  package installconfig
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"regexp"
     7  	"strings"
     8  
     9  	"github.com/pborman/uuid"
    10  	"github.com/sirupsen/logrus"
    11  	utilrand "k8s.io/apimachinery/pkg/util/rand"
    12  
    13  	"github.com/openshift/installer/pkg/asset"
    14  )
    15  
    16  const (
    17  	randomLen = 5
    18  )
    19  
    20  // ClusterID is the unique ID of the cluster, immutable during the cluster's life
    21  type ClusterID struct {
    22  	// UUID is a globally unique identifier.
    23  	UUID string
    24  
    25  	// InfraID is an identifier for the cluster that is more human friendly.
    26  	// This does not have
    27  	InfraID string
    28  }
    29  
    30  var _ asset.Asset = (*ClusterID)(nil)
    31  
    32  // Dependencies returns install-config.
    33  func (a *ClusterID) Dependencies() []asset.Asset {
    34  	return []asset.Asset{
    35  		&InstallConfig{},
    36  	}
    37  }
    38  
    39  // Generate generates a new ClusterID
    40  func (a *ClusterID) Generate(_ context.Context, dep asset.Parents) error {
    41  	ica := &InstallConfig{}
    42  	dep.Get(ica)
    43  
    44  	// resource using InfraID usually have suffixes like `[-/_][a-z]{3,4}` eg. `_int`, `-ext` or `-ctlp`
    45  	// and the maximum length for most resources is approx 32.
    46  	maxLen := 27
    47  
    48  	// add random chars to the end to randomize
    49  	a.InfraID = generateInfraID(ica.Config.ObjectMeta.Name, maxLen)
    50  	a.UUID = uuid.New()
    51  	return nil
    52  }
    53  
    54  // Name returns the human-friendly name of the asset.
    55  func (a *ClusterID) Name() string {
    56  	return "Cluster ID"
    57  }
    58  
    59  // generateInfraID take base and returns a ID that
    60  // - is of length maxLen
    61  // - only contains `alphanum` or `-`
    62  func generateInfraID(base string, maxLen int) string {
    63  	maxBaseLen := maxLen - (randomLen + 1)
    64  
    65  	// replace all characters that are not `alphanum` or `-` with `-`
    66  	re := regexp.MustCompile("[^A-Za-z0-9-]")
    67  	base = re.ReplaceAllString(base, "-")
    68  
    69  	// replace all multiple dashes in a sequence with single one.
    70  	re = regexp.MustCompile(`-{2,}`)
    71  	base = re.ReplaceAllString(base, "-")
    72  
    73  	// truncate to maxBaseLen
    74  	if len(base) > maxBaseLen {
    75  		logrus.Warnf("Length of cluster name %q is %d which is greater than the max %d allowed. The name will be truncated to %q", base, len(base), maxBaseLen, strings.TrimRight(base[:maxBaseLen], "-"))
    76  		base = base[:maxBaseLen]
    77  	}
    78  	base = strings.TrimRight(base, "-")
    79  
    80  	// add random chars to the end to randomize
    81  	return fmt.Sprintf("%s-%s", base, utilrand.String(randomLen))
    82  }