-
Notifications
You must be signed in to change notification settings - Fork 18
/
config.go
377 lines (304 loc) · 10.1 KB
/
config.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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
/*
SPDX-FileCopyrightText: 2021 SAP SE or an SAP affiliate company and Gardener contributors
SPDX-License-Identifier: Apache-2.0
*/
package config
import (
"errors"
"fmt"
"os"
"path/filepath"
"regexp"
"strconv"
"github.com/mitchellh/go-homedir"
"k8s.io/client-go/tools/clientcmd"
clientcmdapi "k8s.io/client-go/tools/clientcmd/api"
"k8s.io/klog/v2"
"sigs.k8s.io/yaml"
"github.com/gardener/gardenctl-v2/pkg/ac"
)
// Config holds the gardenctl configuration.
type Config struct {
// Filename is the name of the gardenctl configuration file
Filename string `json:"-"`
// LinkKubeconfig defines if kubeconfig is symlinked with the target
LinkKubeconfig *bool `json:"linkKubeconfig,omitempty"`
// Gardens is a list of known Garden clusters
Gardens []Garden `json:"gardens"`
}
// Garden represents one garden cluster.
type Garden struct {
// Name is a unique identifier of this Garden that can be used to target this Garden
Name string `json:"identity"`
// Alias is a unique identifier of this Garden that can be used as an alternate name to target this Garden
// +optional
Alias string `json:"name,omitempty"`
// Kubeconfig holds the path for the kubeconfig of the garden cluster
Kubeconfig string `json:"kubeconfig"`
// Context overrides the current-context of the garden cluster kubeconfig
// +optional
Context string `json:"context,omitempty"`
// Patterns is a list of regex patterns that can be defined to use custom input formats for targeting
// Use named capturing groups to match target values.
// Supported capturing groups: project, namespace, shoot
// +optional
Patterns []string `json:"patterns,omitempty"`
// AccessRestrictions is a list of access restriction definitions
// +optional
AccessRestrictions []ac.AccessRestriction `json:"accessRestrictions,omitempty"`
}
// LoadFromFile parses a gardenctl config file and returns a Config struct.
func LoadFromFile(filename string) (*Config, error) {
config := &Config{Filename: filename}
f, err := os.Open(filename)
if err != nil {
if os.IsNotExist(err) {
return config, nil
}
return nil, fmt.Errorf("failed to open file: %w", err)
}
defer f.Close()
stat, err := f.Stat()
if err != nil {
return nil, fmt.Errorf("failed to determine filesize: %w", err)
}
if stat.Size() > 0 {
buf, err := os.ReadFile(filename)
if err != nil {
return nil, fmt.Errorf("failed to read config file: %w", err)
}
if err = yaml.Unmarshal(buf, config); err != nil {
return nil, fmt.Errorf("failed to decode as YAML: %w", err)
}
// be nice and handle ~ in paths
for i, g := range config.Gardens {
expanded, err := homedir.Expand(g.Kubeconfig)
if err != nil {
return nil, fmt.Errorf("failed to resolve ~ in kubeconfig path: %w", err)
}
config.Gardens[i].Kubeconfig = expanded
}
}
// we don't want a dependency to root command here
str, ok := os.LookupEnv("GCTL_LINK_KUBECONFIG")
if ok {
val, err := strconv.ParseBool(str)
if err != nil {
return nil, fmt.Errorf("failed to parse environment variable GCTL_LINK_KUBECONFIG: %w", err)
}
config.LinkKubeconfig = &val
}
config.validate()
return config, nil
}
// validate checks the config for ambiguous definitions and prints warnings to the user.
func (config *Config) validate() {
seen := make(map[string]bool, len(config.Gardens))
for i := range config.Gardens {
garden := config.Gardens[i]
if logged, ok := seen[garden.Name]; ok && !logged {
klog.Warningf("identity and alias should be unique but %q was found multiple times in gardenctl configuration", garden.Name)
seen[garden.Name] = true
} else if !ok {
seen[garden.Name] = false
}
if garden.Alias != "" && garden.Alias != garden.Name {
if logged, ok := seen[garden.Alias]; ok && !logged {
klog.Warningf("identity and alias should be unique but %q was found multiple times in gardenctl configuration", garden.Alias)
seen[garden.Alias] = true
} else if !ok {
seen[garden.Alias] = false
}
}
}
}
// SymlinkTargetKubeconfig indicates if the kubeconfig of the current target should be always symlinked.
func (config *Config) SymlinkTargetKubeconfig() bool {
return config.LinkKubeconfig == nil || *config.LinkKubeconfig
}
// Save updates a gardenctl config file with the values passed via Config struct.
func (config *Config) Save() error {
dir := filepath.Dir(config.Filename)
err := os.MkdirAll(dir, 0o700)
if err != nil {
return fmt.Errorf("failed to create directory: %w", err)
}
buf, err := yaml.Marshal(config)
if err != nil {
return fmt.Errorf("failed to encode as YAML: %w", err)
}
if err := os.WriteFile(config.Filename, buf, 0o600); err != nil {
return fmt.Errorf("failed to write file: %w", err)
}
return nil
}
// IndexOfGarden returns the index of the Garden with the given name in the configured Gardens slice.
// If no Garden with this name is found it returns -1.
func (config *Config) IndexOfGarden(name string) (int, bool) {
for i, g := range config.Gardens {
if g.Name == name {
return i, true
}
}
return -1, false
}
// GardenNames returns a slice containing the names of the configured Gardens.
func (config *Config) GardenNames() []string {
names := []string{}
for _, g := range config.Gardens {
names = append(names, g.Name)
}
return names
}
// Garden returns the matching Garden cluster by name (identity or alias) from the list
// of configured Gardens. In case of ambigous names the first match is returned and identity is
// preferred over alias.
func (config *Config) Garden(name string) (*Garden, error) {
if name == "" {
return nil, fmt.Errorf("garden name or alias cannot be empty")
}
var firstMatchByAlias *Garden
for idx := range config.Gardens {
cfg := &config.Gardens[idx]
if name == cfg.Name {
return cfg, nil
}
if firstMatchByAlias == nil && name == cfg.Alias {
firstMatchByAlias = cfg
}
}
if firstMatchByAlias != nil {
return firstMatchByAlias, nil
}
return nil, fmt.Errorf("garden %q is not defined in gardenctl configuration", name)
}
// ClientConfig returns a deferred loading client config for a configured garden cluster.
func (config *Config) ClientConfig(name string) (clientcmd.ClientConfig, error) {
garden, err := config.Garden(name)
if err != nil {
return nil, err
}
loader := &clientcmd.ClientConfigLoadingRules{ExplicitPath: garden.Kubeconfig}
overrides := &clientcmd.ConfigOverrides{}
if garden.Context != "" {
overrides.CurrentContext = garden.Context
}
return clientcmd.NewNonInteractiveDeferredLoadingClientConfig(loader, overrides), nil
}
// DirectClientConfig returns a directly loaded client config for a configured garden cluster.
func (config *Config) DirectClientConfig(name string) (clientcmd.ClientConfig, error) {
garden, err := config.Garden(name)
if err != nil {
return nil, err
}
rawConfig, err := garden.LoadRawConfig()
if err != nil {
return nil, err
}
return clientcmd.NewDefaultClientConfig(*rawConfig, nil), nil
}
// LoadRawConfig directly loads the raw config from file, validates the content and removes all the irrelevant pieces.
func (g *Garden) LoadRawConfig() (*clientcmdapi.Config, error) {
rawConfig, err := clientcmd.LoadFromFile(g.Kubeconfig)
if err != nil {
return nil, fmt.Errorf("failed to load client configuration: %w", err)
}
err = clientcmd.Validate(*rawConfig)
if err != nil {
return nil, fmt.Errorf("failed to validate client configuration: %w", err)
}
if g.Context != "" {
rawConfig.CurrentContext = g.Context
}
// this function returns an error if the currentContext does not exist
err = clientcmdapi.MinifyConfig(rawConfig)
if err != nil {
return nil, fmt.Errorf("failed to minify client configuration: %w", err)
}
return rawConfig, nil
}
// PatternMatch holds (target) values extracted from a provided string.
type PatternMatch struct {
// Garden is the matched Garden
Garden string
// Project is the matched Project
Project string
// Namespace is the matched Namespace, can be used to find the related project
Namespace string
// Shoot is the matched Shoot
Shoot string
}
// PatternKey is a key that can be used to identify a value in a pattern.
type PatternKey string
const (
// PatternKeyProject is used to identify a Project.
PatternKeyProject = PatternKey("project")
// PatternKeyNamespace is used to identify a Project by the namespace it refers to.
PatternKeyNamespace = PatternKey("namespace")
// PatternKeyShoot is used to identify a Shoot.
PatternKeyShoot = PatternKey("shoot")
)
// MatchPattern matches a string against patterns defined in gardenctl config.
// If matched, the function creates and returns a PatternMatch from the provided target string.
func (config *Config) MatchPattern(preferredGardenName string, value string) (*PatternMatch, error) {
if preferredGardenName != "" {
g, err := config.Garden(preferredGardenName)
if err != nil {
return nil, err
}
match, err := matchPattern(g.Patterns, value)
if err != nil {
return nil, err
}
if match != nil {
match.Garden = g.Name
return match, nil
}
}
var patternMatch *PatternMatch
for _, g := range config.Gardens {
match, err := matchPattern(g.Patterns, value)
if err != nil {
return nil, err
}
if match != nil {
match.Garden = g.Name
if patternMatch != nil {
return nil, errors.New("the provided value resulted in an ambiguous match")
}
patternMatch = match
}
}
if patternMatch == nil {
return nil, errors.New("the provided value does not match any pattern")
}
return patternMatch, nil
}
// matchPattern matches pattern with provided list of patterns.
// If none of the provided patterns matches the given value no error is returned.
func matchPattern(patterns []string, value string) (*PatternMatch, error) {
for _, p := range patterns {
r, err := regexp.Compile(p)
if err != nil {
return nil, fmt.Errorf("failed to compile configured regular expression %q: %w", p, err)
}
names := r.SubexpNames()
matches := r.FindStringSubmatch(value)
if matches == nil {
continue
}
tm := &PatternMatch{}
for i, name := range names {
switch PatternKey(name) {
case PatternKeyProject:
tm.Project = matches[i]
case PatternKeyNamespace:
tm.Namespace = matches[i]
case PatternKeyShoot:
tm.Shoot = matches[i]
}
}
return tm, nil
}
return nil, nil
}