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

     1  package configimage
     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  	"github.com/openshift/installer/pkg/asset/installconfig"
    15  )
    16  
    17  const (
    18  	randomLen = 5
    19  )
    20  
    21  // ClusterID is the unique ID of the cluster, immutable during the cluster's life.
    22  type ClusterID struct {
    23  	installconfig.ClusterID
    24  }
    25  
    26  var _ asset.Asset = (*ClusterID)(nil)
    27  
    28  // Dependencies returns install-config.
    29  func (i *ClusterID) Dependencies() []asset.Asset {
    30  	return []asset.Asset{
    31  		&InstallConfig{},
    32  	}
    33  }
    34  
    35  // Generate generates a new ClusterID.
    36  func (i *ClusterID) Generate(_ context.Context, dep asset.Parents) error {
    37  	ica := &InstallConfig{}
    38  	dep.Get(ica)
    39  
    40  	if ica.Config == nil {
    41  		return fmt.Errorf("missing install-config.yaml")
    42  	}
    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  	i.InfraID = generateInfraID(ica.Config.ObjectMeta.Name, maxLen)
    50  	i.UUID = uuid.New()
    51  	return nil
    52  }
    53  
    54  // Name returns the human-friendly name of the asset.
    55  func (i *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  }