-
Notifications
You must be signed in to change notification settings - Fork 4
/
kubeconfig.go
94 lines (76 loc) · 1.98 KB
/
kubeconfig.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
87
88
89
90
91
92
93
94
package aws
import (
"fmt"
"os"
"os/exec"
"path/filepath"
"sync"
log "github.com/Sirupsen/logrus"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
)
var kubeClient *kubernetes.Clientset
var cacheClientsetOnce sync.Once
var cacheConfigPathOnce sync.Once
var (
rootPath = "/opt/datacol"
kcpath = filepath.Join(rootPath, "kubeconfig")
pemPathRE = filepath.Join(rootPath, "%s.pem")
privateIpAttr = "MasterPrivateIp"
scpCmd = "scp -i %s -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null ubuntu@%s:~/kubeconfig %s"
)
func (p *AwsCloud) kubeClient() *kubernetes.Clientset {
cacheConfigPathOnce.Do(func() {
p.K8sConfigPath()
})
cacheClientsetOnce.Do(func() {
kube, err := getkubeclientset(p.DeploymentName)
if err != nil {
log.Fatal(err)
}
kubeClient = kube
})
return kubeClient
}
func (p *AwsCloud) K8sConfigPath() (string, error) {
if _, err := os.Stat(kcpath); err != nil {
if os.IsNotExist(err) {
ipAddr, err := p.masterPrivateIp()
if err != nil {
return ipAddr, err
}
keyname := fmt.Sprintf(pemPathRE, os.Getenv("DATACOL_KEY_NAME"))
cmd := fmt.Sprintf(scpCmd, keyname, ipAddr, kcpath)
log.Debugf("Executing %s", cmd)
if _, err := exec.Command("/bin/sh", "-c", cmd).Output(); err != nil {
return "", err
}
} else {
return kcpath, err
}
}
return kcpath, nil
}
func (p *AwsCloud) masterPrivateIp() (string, error) {
s, err := p.describeStack("")
if err != nil {
return "", err
}
for _, o := range s.Outputs {
if o.OutputKey != nil && privateIpAttr == *o.OutputKey {
return *o.OutputValue, nil
}
}
return "", fmt.Errorf("unable to find MasterPrivateIp from stack output")
}
func getkubeclientset(name string) (*kubernetes.Clientset, error) {
config, err := clientcmd.BuildConfigFromFlags("", kcpath)
if err != nil {
return nil, err
}
c, err := kubernetes.NewForConfig(config)
if err != nil {
return nil, fmt.Errorf("cluster connection %v", err)
}
return c, nil
}