-
Notifications
You must be signed in to change notification settings - Fork 74
/
kubeconfig_store_eks.go
351 lines (300 loc) · 9.62 KB
/
kubeconfig_store_eks.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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
// Copyright 2021 The Kubeswitch authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package store
import (
"context"
"fmt"
"os"
"strings"
"time"
awsconfig "github.com/aws/aws-sdk-go-v2/config"
awseks "github.com/aws/aws-sdk-go-v2/service/eks"
awsekstypes "github.com/aws/aws-sdk-go-v2/service/eks/types"
"github.com/aws/smithy-go/logging"
"github.com/danielfoehrkn/kubeswitch/types"
"github.com/disiqueira/gotree"
"github.com/sirupsen/logrus"
"gopkg.in/yaml.v3"
)
func NewEKSStore(store types.KubeconfigStore, stateDir string) (*EKSStore, error) {
eksStoreConfig := &types.StoreConfigEKS{}
if store.Config != nil {
buf, err := yaml.Marshal(store.Config)
if err != nil {
return nil, err
}
err = yaml.Unmarshal(buf, eksStoreConfig)
if err != nil {
return nil, fmt.Errorf("failed to unmarshal eks config: %w", err)
}
if eksStoreConfig.Region == nil {
defaultregion, ok := os.LookupEnv("AWS_DEFAULT_REGION")
if !ok {
return nil, fmt.Errorf("failed to set aws region from config or environment")
}
eksStoreConfig.Region = &defaultregion
}
} else {
profile, ok := os.LookupEnv("AWS_PROFILE")
if !ok {
return nil, fmt.Errorf("failed to set aws profile from config or environment")
}
region, ok := os.LookupEnv("AWS_REGION")
defaultregion, ok2 := os.LookupEnv("AWS_DEFAULT_REGION")
if !ok && !ok2 {
return nil, fmt.Errorf("failed to set aws region from config or environment")
}
if ok2 {
region = defaultregion
}
eksStoreConfig.Profile = profile
eksStoreConfig.Region = ®ion
}
if len(eksStoreConfig.Profile) == 0 {
return nil, fmt.Errorf("profile is required")
}
if eksStoreConfig.Region == nil || len(*eksStoreConfig.Region) == 0 {
return nil, fmt.Errorf("region is required")
}
return &EKSStore{
KubeconfigStore: store,
Config: eksStoreConfig,
StateDirectory: stateDir,
DiscoveredClusters: make(map[string]*awsekstypes.Cluster),
}, nil
}
func (s *EKSStore) InitializeEKSStore() error {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
optFns := []func(*awsconfig.LoadOptions) error{
awsconfig.WithLogger(AWSLogrusBridgeLogger{Logger: s.GetLogger()}),
}
optFns = append(optFns, awsconfig.WithRegion(*s.Config.Region))
optFns = append(optFns, awsconfig.WithSharedConfigProfile(s.Config.Profile))
cfg, err := awsconfig.LoadDefaultConfig(ctx, optFns...)
if err != nil {
return err
}
s.Client = awseks.NewFromConfig(cfg)
return nil
}
func (s *EKSStore) IsInitialized() bool {
return s.Client != nil && s.Config != nil
}
func (s *EKSStore) GetID() string {
id := "default"
if s.KubeconfigStore.ID != nil {
id = *s.KubeconfigStore.ID
}
return fmt.Sprintf("%s.%s", types.StoreKindEKS, id)
}
func (s *EKSStore) GetKind() types.StoreKind {
return types.StoreKindEKS
}
func (s *EKSStore) GetStoreConfig() types.KubeconfigStore {
return s.KubeconfigStore
}
func (s *EKSStore) GetLogger() *logrus.Entry {
if s.Logger == nil {
s.Logger = logrus.WithField("store", s.GetID())
}
return s.Logger
}
func (s *EKSStore) GetContextPrefix(path string) string {
if s.GetStoreConfig().ShowPrefix != nil && !*s.GetStoreConfig().ShowPrefix {
return ""
}
return strings.ReplaceAll(path, "--", "-")
}
func (s *EKSStore) VerifyKubeconfigPaths() error {
// NOOP
return nil
}
func (s *EKSStore) StartSearch(channel chan SearchResult) {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
if err := s.InitializeEKSStore(); err != nil {
err := fmt.Errorf("failed to initialize store. This is most likely a problem with your provided aws credentials: %v", err)
channel <- SearchResult{
Error: err,
}
return
}
opts := &awseks.ListClustersInput{}
pager := awseks.NewListClustersPaginator(s.Client, opts)
for pager.HasMorePages() {
s.GetLogger().Debugf("next page found")
resp, err := pager.NextPage(ctx)
if err != nil {
channel <- SearchResult{
Error: err,
}
return
}
for _, clusterName := range resp.Clusters {
// kubeconfig path used to uniquely identify this cluster
// eks_<profile>--<region>--<eks-cluster-name>
kubeconfigPath := fmt.Sprintf("eks_%s--%s--%s", s.Config.Profile, *s.Config.Region, clusterName)
channel <- SearchResult{
KubeconfigPath: kubeconfigPath,
Error: nil,
}
}
}
s.GetLogger().Debugf("Search done for EKS")
}
// ParseIdentifier takes a kubeconfig identifier and
// returns the
// 1) the EKS resource group
// 2) the name of the EKS cluster
func parseEksIdentifier(path string) (string, string, string, error) {
split := strings.Split(path, "--")
switch len(split) {
case 3:
return strings.TrimPrefix(split[0], "eks_"), split[1], split[2], nil
default:
return "", "", "", fmt.Errorf("unable to parse kubeconfig path: %q", path)
}
}
func (s *EKSStore) GetKubeconfigForPath(path string, _ map[string]string) ([]byte, error) {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
if !s.IsInitialized() {
if err := s.InitializeEKSStore(); err != nil {
return nil, fmt.Errorf("failed to initialize EKS store: %w", err)
}
}
_, _, clusterName, err := parseEksIdentifier(path)
if err != nil {
return nil, err
}
cluster := s.DiscoveredClusters[path]
if cluster == nil {
resp, err := s.Client.DescribeCluster(ctx, &awseks.DescribeClusterInput{Name: &clusterName})
if err != nil {
return nil, err
}
s.DiscoveredClusters[path] = resp.Cluster
cluster = resp.Cluster
}
// context name does not include the location or the account as this information is already included in the path (different to gcloud)
contextName := fmt.Sprintf("eks_%s", *cluster.Name)
// need to provide a CA certificate in the kubeconfig (if not using insecure configuration)
if cluster.CertificateAuthority == nil || cluster.CertificateAuthority.Data == nil {
return nil, fmt.Errorf("cluster CA certificate not found for cluster=%s", *cluster.Arn)
}
kubeconfig := &types.KubeConfig{
TypeMeta: types.TypeMeta{
APIVersion: "v1",
Kind: "Config",
},
Clusters: []types.KubeCluster{{
Name: contextName,
Cluster: types.Cluster{
CertificateAuthorityData: *cluster.CertificateAuthority.Data,
Server: *cluster.Endpoint,
},
}},
CurrentContext: contextName,
Contexts: []types.KubeContext{
{
Name: contextName,
Context: types.Context{
Cluster: contextName,
User: contextName,
},
},
},
Users: []types.KubeUser{
{
Name: contextName,
User: types.User{
ExecProvider: &types.ExecProvider{
APIVersion: "client.authentication.k8s.io/v1beta1",
Command: "aws",
Args: []string{
"--region",
*s.Config.Region,
"eks",
"get-token",
"--cluster-name",
*cluster.Name,
},
Env: []types.EnvMap{
{Name: "AWS_PROFILE", Value: s.Config.Profile},
},
},
},
},
},
}
bytes, err := yaml.Marshal(kubeconfig)
return bytes, err
}
func (s *EKSStore) GetSearchPreview(path string, optionalTags map[string]string) (string, error) {
if !s.IsInitialized() {
// this takes too long, initialize concurrently
go func() {
if err := s.InitializeEKSStore(); err != nil {
s.Logger.Debugf("failed to initialize store: %v", err)
}
}()
return "", fmt.Errorf("eks store is not initalized yet")
}
// low timeout to not pile up many requests, but timeout fast
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
profile, region, clusterName, err := parseEksIdentifier(path)
if err != nil {
return "", err
}
// the cluster should be in the cache, but do not fail if it is not
cluster := s.DiscoveredClusters[path]
// cluster has not been discovered from the EKS API yet
// this is the case when a search index is used
if cluster == nil {
// The name of the cluster to retrieve.
// we can safely use the client, as we know the store has been previously initialized
resp, err := s.Client.DescribeCluster(ctx, &awseks.DescribeClusterInput{Name: &clusterName})
if err != nil {
return "", fmt.Errorf("failed to get Eks cluster with name %q : %w", clusterName, err)
}
cluster = resp.Cluster
s.DiscoveredClusters[path] = cluster
}
asciTree := gotree.New(clusterName)
if cluster.Version != nil {
asciTree.Add(fmt.Sprintf("Kubernetes Version: %s", *cluster.Version))
}
if cluster.PlatformVersion != nil {
asciTree.Add(fmt.Sprintf("Platform Version: %s", *cluster.PlatformVersion))
}
asciTree.Add(fmt.Sprintf("Status: %s", cluster.Status))
asciTree.Add(fmt.Sprintf("AWS Profile: %s", profile))
asciTree.Add(fmt.Sprintf("Region: %s", region))
return asciTree.Print(), nil
}
// AWSLogrusBridgeLogger is a Logger implementation that wraps the standard library logger, and delegates logging to it's
// Printf method.
type AWSLogrusBridgeLogger struct {
Logger *logrus.Entry
}
// Logf logs the given classification and message to the underlying logger.
func (s AWSLogrusBridgeLogger) Logf(classification logging.Classification, format string, v ...interface{}) {
level, err := logrus.ParseLevel(string(classification))
if err != nil {
level = logrus.DebugLevel
}
s.Logger.Logf(level, format, v...)
}