github.com/telepresenceio/telepresence/v2@v2.20.0-pro.6.0.20240517030216-236ea954e789/pkg/client/cli/daemon/identifier.go (about)

     1  package daemon
     2  
     3  import (
     4  	"context"
     5  	"errors"
     6  
     7  	"github.com/telepresenceio/telepresence/v2/pkg/client"
     8  	"github.com/telepresenceio/telepresence/v2/pkg/ioutil"
     9  )
    10  
    11  type Identifier struct {
    12  	Name          string
    13  	KubeContext   string
    14  	Namespace     string
    15  	Containerized bool
    16  }
    17  
    18  func NewIdentifier(name, contextName, namespace string, containerized bool) (*Identifier, error) {
    19  	if namespace == "" {
    20  		return nil, errors.New("daemon identifier must have a namespace")
    21  	}
    22  	if name == "" {
    23  		if contextName == "" {
    24  			// Must be an in-cluster config
    25  			name = "in-cluster-" + namespace
    26  		} else {
    27  			name = contextName + "-" + namespace
    28  		}
    29  		if containerized {
    30  			name += "-cn"
    31  		}
    32  	}
    33  	return &Identifier{
    34  		KubeContext:   contextName,
    35  		Namespace:     namespace,
    36  		Name:          ioutil.SafeName(name),
    37  		Containerized: containerized,
    38  	}, nil
    39  }
    40  
    41  func (id *Identifier) String() string {
    42  	return id.Name
    43  }
    44  
    45  func (id *Identifier) InfoFileName() string {
    46  	return id.String() + ".json"
    47  }
    48  
    49  func (id *Identifier) ContainerName() string {
    50  	return "tp-" + id.String()
    51  }
    52  
    53  // IdentifierFromFlags returns a unique name created from the name of the current context
    54  // and the active namespace denoted by the given flagMap.
    55  func IdentifierFromFlags(ctx context.Context, name string, flagMap map[string]string, kubeConfigData []byte, containerized bool) (*Identifier, error) {
    56  	cc := flagMap["context"]
    57  	ns := flagMap["namespace"]
    58  	if cc == "" || ns == "" {
    59  		cld, err := client.ConfigLoader(ctx, flagMap, kubeConfigData)
    60  		if err != nil {
    61  			return nil, err
    62  		}
    63  		if ns == "" {
    64  			ns, _, err = cld.Namespace()
    65  			if err != nil {
    66  				return nil, err
    67  			}
    68  		}
    69  		if cc == "" {
    70  			config, err := cld.RawConfig()
    71  			if err != nil {
    72  				return nil, err
    73  			}
    74  			cc = config.CurrentContext
    75  		}
    76  	}
    77  	return NewIdentifier(name, cc, ns, containerized)
    78  }