-
Notifications
You must be signed in to change notification settings - Fork 1
/
gkediscovery.go
103 lines (88 loc) · 2.63 KB
/
gkediscovery.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
95
96
97
98
99
100
101
102
103
package main
import (
"context"
"encoding/base64"
"io/ioutil"
"path/filepath"
"sort"
gke "cloud.google.com/go/container/apiv1"
"github.com/golang/glog"
"github.com/pkg/errors"
gkepb "google.golang.org/genproto/googleapis/container/v1"
)
type cluster struct {
Project string
CertFile string
KeyFile string
CAFile string
BearerTokenFile string
gkepb.Cluster
}
type byEndpoint []*cluster
func (a byEndpoint) Len() int { return len(a) }
func (a byEndpoint) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a byEndpoint) Less(i, j int) bool {
if a[i].Endpoint < a[j].Endpoint {
return true
}
return false
}
type clusterLister func(ctx context.Context) ([]*cluster, error)
func listGKEClusters(c *gke.ClusterManagerClient, project string, tlsDir string, tokenFile string) clusterLister {
return func(ctx context.Context) ([]*cluster, error) {
req := &gkepb.ListClustersRequest{
Parent: "projects/" + project + "/locations/-",
}
resp, err := c.ListClusters(ctx, req)
if err != nil {
return nil, errors.Wrap(err, "could not list cluster")
}
var cls []*cluster
for _, c := range resp.Clusters {
newcluster := &cluster{
Project: project,
Cluster: *c,
BearerTokenFile: tokenFile,
}
if len(c.MasterAuth.ClientCertificate) != 0 {
crtFile := filepath.Join(tlsDir, c.Name+".crt")
bs, err := base64.StdEncoding.DecodeString(c.MasterAuth.ClientCertificate)
if err != nil {
glog.Errorf("failed decoding %s cert, %v", c.Name, err)
}
err = ioutil.WriteFile(crtFile, bs, 0600)
if err != nil {
glog.Errorf("failed writing %s, %v", crtFile, err)
}
newcluster.CertFile = crtFile
}
if len(c.MasterAuth.ClientKey) != 0 {
keyFile := filepath.Join(tlsDir, c.Name+".key")
bs, err := base64.StdEncoding.DecodeString(c.MasterAuth.ClientKey)
if err != nil {
glog.Errorf("failed decoding %s key, %v", c.Name, err)
}
err = ioutil.WriteFile(keyFile, bs, 0600)
if err != nil {
glog.Errorf("failed writing %s, %v", keyFile, err)
}
newcluster.KeyFile = keyFile
}
if len(c.MasterAuth.ClusterCaCertificate) != 0 {
cacrtFile := filepath.Join(tlsDir, c.Name+".cacrt")
bs, err := base64.StdEncoding.DecodeString(c.MasterAuth.ClusterCaCertificate)
if err != nil {
glog.Errorf("failed decoding %s ca cert, %v", c.Name, err)
}
err = ioutil.WriteFile(cacrtFile, bs, 0600)
if err != nil {
glog.Errorf("failed writing %s, %v", cacrtFile, err)
}
newcluster.CAFile = cacrtFile
}
cls = append(cls, newcluster)
}
sort.Sort(byEndpoint(cls))
return cls, nil
}
}