-
-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
Copy pathconfig.go
411 lines (342 loc) · 9.25 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
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
// SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package client
import (
"errors"
"fmt"
"net/http"
"net/url"
"strings"
"sync"
"time"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/cli-runtime/pkg/genericclioptions"
restclient "k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/client-go/tools/clientcmd/api"
)
const (
defaultCallTimeoutDuration time.Duration = 10 * time.Second
// UsePersistentConfig caches client config to avoid reloads.
UsePersistentConfig = true
inClusterConfig = "incluster"
)
// Config tracks a kubernetes configuration.
type Config struct {
flags *genericclioptions.ConfigFlags
mx sync.RWMutex
proxy func(*http.Request) (*url.URL, error)
}
// NewConfig returns a new k8s config or an error if the flags are invalid.
func NewConfig(f *genericclioptions.ConfigFlags) *Config {
return &Config{
flags: f,
}
}
// CallTimeout returns the call timeout if set or the default if not set.
func (c *Config) CallTimeout() time.Duration {
if !isSet(c.flags.Timeout) {
return defaultCallTimeoutDuration
}
dur, err := time.ParseDuration(*c.flags.Timeout)
if err != nil {
return defaultCallTimeoutDuration
}
return dur
}
func (c *Config) RESTConfig() (*restclient.Config, error) {
cfg, err := c.clientConfig().ClientConfig()
if err != nil {
return nil, err
}
if c.proxy != nil {
cfg.Proxy = c.proxy
}
return cfg, nil
}
// Flags returns configuration flags.
func (c *Config) Flags() *genericclioptions.ConfigFlags {
return c.flags
}
func (c *Config) RawConfig() (api.Config, error) {
return c.clientConfig().RawConfig()
}
func (c *Config) clientConfig() clientcmd.ClientConfig {
return c.flags.ToRawKubeConfigLoader()
}
func (c *Config) reset() {}
// SwitchContext changes the kubeconfig context to a new cluster.
func (c *Config) SwitchContext(name string) error {
ct, err := c.GetContext(name)
if err != nil {
return fmt.Errorf("context %q does not exist", name)
}
if name == inClusterConfig && ct.LocationOfOrigin == inClusterConfig {
return nil
}
// !!BOZO!! Do you need to reset the flags?
flags := genericclioptions.NewConfigFlags(UsePersistentConfig)
flags.Context, flags.ClusterName = &name, &ct.Cluster
flags.Namespace = c.flags.Namespace
flags.Timeout = c.flags.Timeout
flags.KubeConfig = c.flags.KubeConfig
flags.Impersonate = c.flags.Impersonate
flags.ImpersonateGroup = c.flags.ImpersonateGroup
flags.ImpersonateUID = c.flags.ImpersonateUID
c.flags = flags
return nil
}
func (c *Config) Clone(ns string) (*genericclioptions.ConfigFlags, error) {
flags := genericclioptions.NewConfigFlags(false)
ct, err := c.CurrentContextName()
if err != nil {
return nil, err
}
cl, err := c.CurrentClusterName()
if err != nil {
return nil, err
}
flags.Context, flags.ClusterName = &ct, &cl
flags.Namespace = &ns
flags.Timeout = c.Flags().Timeout
flags.KubeConfig = c.Flags().KubeConfig
return flags, nil
}
// CurrentClusterName returns the currently active cluster name.
func (c *Config) CurrentClusterName() (string, error) {
if isSet(c.flags.ClusterName) {
return *c.flags.ClusterName, nil
}
cfg, err := c.RawConfig()
if err != nil {
return "", err
}
ct, ok := cfg.Contexts[cfg.CurrentContext]
if !ok {
if c.isInCluster(cfg) {
return inClusterConfig, nil
}
return "", fmt.Errorf("invalid current context specified: %q", cfg.CurrentContext)
}
if isSet(c.flags.Context) {
ct, ok = cfg.Contexts[*c.flags.Context]
if !ok {
return "", fmt.Errorf("current-cluster - invalid context specified: %q", *c.flags.Context)
}
}
return ct.Cluster, nil
}
// CurrentContextName returns the currently active config context.
func (c *Config) CurrentContextName() (string, error) {
if isSet(c.flags.Context) {
return *c.flags.Context, nil
}
cfg, err := c.RawConfig()
if err != nil {
return "", fmt.Errorf("fail to load rawConfig: %w", err)
}
if c.isInCluster(cfg) {
return inClusterConfig, nil
}
return cfg.CurrentContext, nil
}
func (c *Config) CurrentContextNamespace() (string, error) {
name, err := c.CurrentContextName()
if err != nil {
return "", err
}
context, err := c.GetContext(name)
if err != nil {
return "", err
}
return context.Namespace, nil
}
// CurrentContext returns the current context configuration.
func (c *Config) CurrentContext() (*api.Context, error) {
n, err := c.CurrentContextName()
if err != nil {
return nil, err
}
return c.GetContext(n)
}
// GetContext fetch a given context or error if it does not exist.
func (c *Config) GetContext(n string) (*api.Context, error) {
cfg, err := c.RawConfig()
if err != nil {
return nil, err
}
if c, ok := cfg.Contexts[n]; ok {
return c, nil
}
if n == inClusterConfig {
return c.newInclusterContext(), nil
}
return nil, fmt.Errorf("getcontext - invalid context specified: %q", n)
}
// SetProxy sets the proxy function.
func (c *Config) SetProxy(proxy func(*http.Request) (*url.URL, error)) {
c.proxy = proxy
}
// Contexts fetch all available contexts.
func (c *Config) Contexts() (map[string]*api.Context, error) {
cfg, err := c.RawConfig()
if err != nil {
return nil, err
}
if len(cfg.Contexts) == 0 && c.isInCluster(cfg) {
return map[string]*api.Context{
inClusterConfig: c.newInclusterContext(),
}, nil
}
return cfg.Contexts, nil
}
// DelContext remove a given context from the configuration.
func (c *Config) DelContext(n string) error {
cfg, err := c.RawConfig()
if err != nil {
return err
}
delete(cfg.Contexts, n)
acc, err := c.ConfigAccess()
if err != nil {
return err
}
return clientcmd.ModifyConfig(acc, cfg, true)
}
// RenameContext renames a context.
func (c *Config) RenameContext(old string, new string) error {
cfg, err := c.RawConfig()
if err != nil {
return err
}
if _, ok := cfg.Contexts[new]; ok {
return fmt.Errorf("context with name %s already exists", new)
}
cfg.Contexts[new] = cfg.Contexts[old]
delete(cfg.Contexts, old)
acc, err := c.ConfigAccess()
if err != nil {
return err
}
if e := clientcmd.ModifyConfig(acc, cfg, true); e != nil {
return e
}
current, err := c.CurrentContextName()
if err != nil {
return err
}
if current == old {
return c.SwitchContext(new)
}
return nil
}
// ContextNames fetch all available contexts.
func (c *Config) ContextNames() (map[string]struct{}, error) {
cfg, err := c.RawConfig()
if err != nil {
return nil, err
}
cc := make(map[string]struct{}, len(cfg.Contexts))
for n := range cfg.Contexts {
cc[n] = struct{}{}
}
return cc, nil
}
// CurrentGroupNames retrieves the active group names.
func (c *Config) CurrentGroupNames() ([]string, error) {
if areSet(c.flags.ImpersonateGroup) {
return *c.flags.ImpersonateGroup, nil
}
return []string{}, errors.New("unable to locate current group")
}
// ImpersonateGroups retrieves the active groups if set on the CLI.
func (c *Config) ImpersonateGroups() (string, error) {
if areSet(c.flags.ImpersonateGroup) {
return strings.Join(*c.flags.ImpersonateGroup, ","), nil
}
return "", errors.New("no groups set")
}
// ImpersonateUser retrieves the active user name if set on the CLI.
func (c *Config) ImpersonateUser() (string, error) {
if isSet(c.flags.Impersonate) {
return *c.flags.Impersonate, nil
}
return "", errors.New("no user set")
}
// CurrentUserName retrieves the active user name.
func (c *Config) CurrentUserName() (string, error) {
if isSet(c.flags.Impersonate) {
return *c.flags.Impersonate, nil
}
if isSet(c.flags.AuthInfoName) {
return *c.flags.AuthInfoName, nil
}
cfg, err := c.RawConfig()
if err != nil {
return "", err
}
current := cfg.CurrentContext
if isSet(c.flags.Context) {
current = *c.flags.Context
}
if ctx, ok := cfg.Contexts[current]; ok {
return ctx.AuthInfo, nil
}
if c.isInCluster(cfg) {
return inClusterConfig, nil
}
return "", errors.New("unable to locate current user")
}
// CurrentNamespaceName retrieves the active namespace.
func (c *Config) CurrentNamespaceName() (string, error) {
ns, overridden, err := c.clientConfig().Namespace()
if err != nil {
return BlankNamespace, err
}
// Checks if ns is passed is in args.
if overridden {
return ns, nil
}
// Return ns set in context if any??
return c.CurrentContextNamespace()
}
// ConfigAccess return the current kubeconfig api server access configuration.
func (c *Config) ConfigAccess() (clientcmd.ConfigAccess, error) {
c.mx.RLock()
defer c.mx.RUnlock()
return c.clientConfig().ConfigAccess(), nil
}
func (c *Config) newInclusterContext() *api.Context {
ns, _, _ := c.clientConfig().Namespace()
if ns == "" {
ns = DefaultNamespace
}
return &api.Context{
LocationOfOrigin: inClusterConfig,
Cluster: inClusterConfig,
Namespace: ns,
AuthInfo: inClusterConfig,
Extensions: make(map[string]runtime.Object),
}
}
func (c *Config) isInCluster(cfg api.Config) bool {
if (cfg.CurrentContext == "" || cfg.CurrentContext == inClusterConfig) &&
len(cfg.Contexts) == 0 &&
isEmptyString(c.flags.KubeConfig) &&
isEmptyString(c.flags.ClusterName) &&
isEmptyString(c.flags.APIServer) {
return true
}
return false
}
// ----------------------------------------------------------------------------
// Helpers...
func isSet(s *string) bool {
return s != nil && len(*s) != 0
}
func areSet(s *[]string) bool {
return s != nil && len(*s) != 0
}
func isEmptyString(s *string) bool {
return s != nil && *s == ""
}