forked from rancher/rancher
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cluster.go
86 lines (73 loc) · 1.72 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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package cluster
import (
"encoding/base64"
"fmt"
"io/ioutil"
"os"
"path"
"k8s.io/client-go/rest"
)
const (
rancherCredentialsFolder = "/cattle-credentials"
urlFilename = "url"
tokenFilename = "token"
kubernetesServiceHostKey = "KUBERNETES_SERVICE_HOST"
kubernetesServicePortKey = "KUBERNETES_SERVICE_PORT"
)
func TokenAndURL() (string, string, error) {
return getRancherClient()
}
func Params() (map[string]interface{}, error) {
cfg, err := rest.InClusterConfig()
if err != nil {
return nil, err
}
if err := populateCAData(cfg); err != nil {
return nil, err
}
kubernetesServiceHost, err := getenv(kubernetesServiceHostKey)
if err != nil {
return nil, err
}
kubernetesServicePort, err := getenv(kubernetesServicePortKey)
if err != nil {
return nil, err
}
return map[string]interface{}{
"cluster": map[string]interface{}{
"address": fmt.Sprintf("%s:%s", kubernetesServiceHost, kubernetesServicePort),
"token": cfg.BearerToken,
"caCert": base64.StdEncoding.EncodeToString(cfg.CAData),
},
}, nil
}
func getenv(env string) (string, error) {
value := os.Getenv(env)
if value == "" {
return "", fmt.Errorf("%s is empty", env)
}
return value, nil
}
func populateCAData(cfg *rest.Config) error {
bytes, err := ioutil.ReadFile(cfg.CAFile)
if err != nil {
return err
}
cfg.CAData = bytes
return nil
}
func getRancherClient() (string, string, error) {
url, err := readKey(urlFilename)
if err != nil {
return "", "", err
}
token, err := readKey(tokenFilename)
return token, url, err
}
func readKey(key string) (string, error) {
bytes, err := ioutil.ReadFile(path.Join(rancherCredentialsFolder, key))
if err != nil {
return "", err
}
return string(bytes), nil
}