-
Notifications
You must be signed in to change notification settings - Fork 785
/
cluster.go
72 lines (64 loc) · 2.4 KB
/
cluster.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package cluster
import (
"strings"
"github.com/jenkins-x/jx/pkg/kube"
"github.com/pkg/errors"
"k8s.io/client-go/tools/clientcmd/api"
)
// Name gets the cluster name from the current context
// Note that this just reads the ClusterName from the local kube config, which can be renamed (but is unlikely to happen)
func Name(kuber kube.Kuber) (string, error) {
context, err := Context(kuber)
if err != nil {
return "", err
}
if context == nil {
return "", errors.New("kube context was nil")
}
// context.Cluster will likely be in the form gke_<accountName>_<region>_<clustername>
// Trim off the crud from the beginning context.Cluster
return SimplifiedClusterName(context.Cluster), nil
}
// Context returns the current kube context
func Context(kuber kube.Kuber) (*api.Context, error) {
config, _, err := kuber.LoadConfig()
if err != nil {
return nil, err
}
if config == nil {
return nil, nil
}
return kube.CurrentContext(config), nil
}
// ShortName returns a short clusters name. Eg, if ClusterName would return tweetypie-jenkinsx-dev, ShortClusterName
// would return tweetypie. This is needed because GCP has character limits on things like service accounts (6-30 chars)
// and combining a long cluster name and a long vault name exceeds this limit
func ShortName(kuber kube.Kuber) (string, error) {
clusterName, err := Name(kuber)
if err != nil {
return "", errors.Wrap(err, "retrieving the cluster name")
}
return ShortClusterName(clusterName), nil
}
// ShortClusterName shrinks the cluster name
func ShortClusterName(clusterName string) string {
return ShortNameN(clusterName, 16)
}
// ShortNameN shrinks the name to a max length
func ShortNameN(clusterName string, maxLen int) string {
shortClusterName := clusterName
if len(clusterName) > maxLen {
shortClusterName = clusterName[0:maxLen]
}
if strings.HasSuffix(shortClusterName, "_") || strings.HasSuffix(shortClusterName, "-") {
shortClusterName = shortClusterName[0 : len(shortClusterName)-1]
}
return shortClusterName
}
// SimplifiedClusterName get the simplified cluster name from the long-winded context cluster name that gets generated
// GKE cluster names as defined in the kube config are of the form gke_<projectname>_<region>_<clustername>
// This method will return <clustername> in the above
func SimplifiedClusterName(complexClusterName string) string {
split := strings.Split(complexClusterName, "_")
return split[len(split)-1]
}