-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
client.go
636 lines (533 loc) · 13.7 KB
/
client.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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
// SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package client
import (
"context"
"errors"
"fmt"
"path/filepath"
"strings"
"sync"
"time"
"github.com/rs/zerolog/log"
authorizationv1 "k8s.io/api/authorization/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/cache"
"k8s.io/apimachinery/pkg/version"
"k8s.io/client-go/discovery/cached/disk"
"k8s.io/client-go/dynamic"
"k8s.io/client-go/kubernetes"
restclient "k8s.io/client-go/rest"
metricsapi "k8s.io/metrics/pkg/apis/metrics"
"k8s.io/metrics/pkg/client/clientset/versioned"
)
const (
cacheSize = 100
cacheExpiry = 5 * time.Minute
cacheMXAPIKey = "metricsAPI"
serverVersion = "serverVersion"
cacheNSKey = "validNamespaces"
)
var supportedMetricsAPIVersions = []string{"v1beta1"}
// NamespaceNames tracks a collection of namespace names.
type NamespaceNames map[string]struct{}
// APIClient represents a Kubernetes api client.
type APIClient struct {
client, logClient kubernetes.Interface
dClient dynamic.Interface
nsClient dynamic.NamespaceableResourceInterface
mxsClient *versioned.Clientset
cachedClient *disk.CachedDiscoveryClient
config *Config
mx sync.RWMutex
cache *cache.LRUExpireCache
connOK bool
}
// NewTestAPIClient for testing ONLY!!
func NewTestAPIClient() *APIClient {
return &APIClient{
config: NewConfig(nil),
cache: cache.NewLRUExpireCache(cacheSize),
}
}
// InitConnection initialize connection from command line args.
// Checks for connectivity with the api server.
func InitConnection(config *Config) (*APIClient, error) {
a := APIClient{
config: config,
cache: cache.NewLRUExpireCache(cacheSize),
connOK: true,
}
err := a.supportsMetricsResources()
if err != nil {
log.Error().Err(err).Msgf("Fail to locate metrics-server")
}
if err == nil || errors.Is(err, noMetricServerErr) || errors.Is(err, metricsUnsupportedErr) {
return &a, nil
}
a.connOK = false
return &a, err
}
// ConnectionOK returns connection status.
func (a *APIClient) ConnectionOK() bool {
return a.connOK
}
func makeSAR(ns, gvr, name string) *authorizationv1.SelfSubjectAccessReview {
if ns == ClusterScope {
ns = BlankNamespace
}
spec := NewGVR(gvr)
res := spec.GVR()
return &authorizationv1.SelfSubjectAccessReview{
Spec: authorizationv1.SelfSubjectAccessReviewSpec{
ResourceAttributes: &authorizationv1.ResourceAttributes{
Namespace: ns,
Group: res.Group,
Version: res.Version,
Resource: res.Resource,
Subresource: spec.SubResource(),
Name: name,
},
},
}
}
func makeCacheKey(ns, gvr, n string, vv []string) string {
return ns + ":" + gvr + ":" + n + "::" + strings.Join(vv, ",")
}
// ActiveContext returns the current context name.
func (a *APIClient) ActiveContext() string {
c, err := a.config.CurrentContextName()
if err != nil {
log.Error().Msgf("Unable to located active cluster")
return ""
}
return c
}
// IsActiveNamespace returns true if namespaces matches.
func (a *APIClient) IsActiveNamespace(ns string) bool {
if a.ActiveNamespace() == BlankNamespace {
return true
}
return a.ActiveNamespace() == ns
}
// ActiveNamespace returns the current namespace.
func (a *APIClient) ActiveNamespace() string {
if ns, err := a.CurrentNamespaceName(); err == nil {
return ns
}
return BlankNamespace
}
func (a *APIClient) clearCache() {
for _, k := range a.cache.Keys() {
a.cache.Remove(k)
}
}
// CanI checks if user has access to a certain resource.
func (a *APIClient) CanI(ns, gvr, name string, verbs []string) (auth bool, err error) {
if !a.getConnOK() {
return false, errors.New("ACCESS -- No API server connection")
}
if IsClusterWide(ns) {
ns = BlankNamespace
}
key := makeCacheKey(ns, gvr, name, verbs)
if v, ok := a.cache.Get(key); ok {
if auth, ok = v.(bool); ok {
return auth, nil
}
}
dial, err := a.Dial()
if err != nil {
return false, err
}
client, sar := dial.AuthorizationV1().SelfSubjectAccessReviews(), makeSAR(ns, gvr, name)
ctx, cancel := context.WithTimeout(context.Background(), a.config.CallTimeout())
defer cancel()
for _, v := range verbs {
sar.Spec.ResourceAttributes.Verb = v
resp, err := client.Create(ctx, sar, metav1.CreateOptions{})
log.Trace().Msgf("[CAN] %s(%s) %v <<%v>>", gvr, verbs, resp, err)
if err != nil {
log.Warn().Err(err).Msgf(" Dial Failed!")
a.cache.Add(key, false, cacheExpiry)
return auth, err
}
if !resp.Status.Allowed {
a.cache.Add(key, false, cacheExpiry)
return auth, fmt.Errorf("`%s access denied for user on %q:%s", v, ns, gvr)
}
}
auth = true
a.cache.Add(key, true, cacheExpiry)
return
}
// CurrentNamespaceName return namespace name set via either cli arg or cluster config.
func (a *APIClient) CurrentNamespaceName() (string, error) {
return a.config.CurrentNamespaceName()
}
// ServerVersion returns the current server version info.
func (a *APIClient) ServerVersion() (*version.Info, error) {
if v, ok := a.cache.Get(serverVersion); ok {
if vi, ok := v.(*version.Info); ok {
return vi, nil
}
}
dial, err := a.CachedDiscovery()
if err != nil {
return nil, err
}
info, err := dial.ServerVersion()
if err != nil {
return nil, err
}
a.cache.Add(serverVersion, info, cacheExpiry)
return info, nil
}
func (a *APIClient) IsValidNamespace(ns string) bool {
if IsClusterWide(ns) || ns == NotNamespaced {
return true
}
ok, err := a.CanI(ClusterScope, "v1/namespaces", "", []string{ListVerb})
if ok && err == nil {
nn, _ := a.ValidNamespaceNames()
_, ok = nn[ns]
return ok
}
ok, err = a.isValidNamespace(ns)
if ok && err == nil {
return ok
}
log.Warn().Err(err).Msgf("namespace validation failed for: %q", ns)
return false
}
func (a *APIClient) cachedNamespaceNames() NamespaceNames {
cns, ok := a.cache.Get(cacheNSKey)
if !ok {
return make(NamespaceNames)
}
return cns.(NamespaceNames)
}
func (a *APIClient) isValidNamespace(n string) (bool, error) {
if IsClusterWide(n) || n == NotNamespaced {
return true, nil
}
if a == nil {
return false, errors.New("invalid client")
}
cnss := a.cachedNamespaceNames()
if _, ok := cnss[n]; ok {
return true, nil
}
dial, err := a.Dial()
if err != nil {
return false, err
}
ctx, cancel := context.WithTimeout(context.Background(), a.config.CallTimeout())
defer cancel()
_, err = dial.CoreV1().Namespaces().Get(ctx, n, metav1.GetOptions{})
if err != nil {
return false, err
}
cnss[n] = struct{}{}
a.cache.Add(cacheNSKey, cnss, cacheExpiry)
return true, nil
}
// ValidNamespaceNames returns all available namespaces.
func (a *APIClient) ValidNamespaceNames() (NamespaceNames, error) {
if a == nil {
return nil, fmt.Errorf("validNamespaces: no available client found")
}
if nn, ok := a.cache.Get(cacheNSKey); ok {
if nss, ok := nn.(NamespaceNames); ok {
return nss, nil
}
}
dial, err := a.Dial()
if err != nil {
return nil, err
}
ctx, cancel := context.WithTimeout(context.Background(), a.config.CallTimeout())
defer cancel()
nn, err := dial.CoreV1().Namespaces().List(ctx, metav1.ListOptions{})
if err != nil {
return nil, err
}
nns := make(NamespaceNames, len(nn.Items))
for _, n := range nn.Items {
nns[n.Name] = struct{}{}
}
a.cache.Add(cacheNSKey, nns, cacheExpiry)
return nns, nil
}
// CheckConnectivity return true if api server is cool or false otherwise.
func (a *APIClient) CheckConnectivity() bool {
defer func() {
if err := recover(); err != nil {
a.setConnOK(false)
}
if !a.getConnOK() {
a.clearCache()
}
}()
// Need reload to pick up any kubeconfig changes.
cfg, err := NewConfig(a.config.flags).RESTConfig()
if err != nil {
log.Error().Err(err).Msgf("restConfig load failed")
a.connOK = false
return a.connOK
}
cfg.Timeout = a.config.CallTimeout()
client, err := kubernetes.NewForConfig(cfg)
if err != nil {
log.Error().Err(err).Msgf("Unable to connect to api server")
a.setConnOK(false)
return a.getConnOK()
}
// Check connection
if _, err := client.ServerVersion(); err == nil {
if !a.getConnOK() {
a.reset()
}
} else {
log.Error().Err(err).Msgf("can't connect to cluster")
a.setConnOK(false)
}
return a.getConnOK()
}
// Config return a kubernetes configuration.
func (a *APIClient) Config() *Config {
return a.config
}
// HasMetrics checks if the cluster supports metrics.
func (a *APIClient) HasMetrics() bool {
return a.supportsMetricsResources() == nil
}
func (a *APIClient) getMxsClient() *versioned.Clientset {
a.mx.RLock()
defer a.mx.RUnlock()
return a.mxsClient
}
func (a *APIClient) setMxsClient(c *versioned.Clientset) {
a.mx.Lock()
defer a.mx.Unlock()
a.mxsClient = c
}
func (a *APIClient) getCachedClient() *disk.CachedDiscoveryClient {
a.mx.RLock()
defer a.mx.RUnlock()
return a.cachedClient
}
func (a *APIClient) setCachedClient(c *disk.CachedDiscoveryClient) {
a.mx.Lock()
defer a.mx.Unlock()
a.cachedClient = c
}
func (a *APIClient) getDClient() dynamic.Interface {
a.mx.RLock()
defer a.mx.RUnlock()
return a.dClient
}
func (a *APIClient) setDClient(c dynamic.Interface) {
a.mx.Lock()
defer a.mx.Unlock()
a.dClient = c
}
func (a *APIClient) getConnOK() bool {
a.mx.RLock()
defer a.mx.RUnlock()
return a.connOK
}
func (a *APIClient) setConnOK(b bool) {
a.mx.Lock()
defer a.mx.Unlock()
a.connOK = b
}
func (a *APIClient) setLogClient(k kubernetes.Interface) {
a.mx.Lock()
defer a.mx.Unlock()
a.logClient = k
}
func (a *APIClient) getLogClient() kubernetes.Interface {
a.mx.RLock()
defer a.mx.RUnlock()
return a.logClient
}
func (a *APIClient) setClient(k kubernetes.Interface) {
a.mx.Lock()
defer a.mx.Unlock()
a.client = k
}
func (a *APIClient) getClient() kubernetes.Interface {
a.mx.RLock()
defer a.mx.RUnlock()
return a.client
}
// DialLogs returns a handle to api server for logs.
func (a *APIClient) DialLogs() (kubernetes.Interface, error) {
if !a.getConnOK() {
return nil, errors.New("dialLogs - no connection to dial")
}
if clt := a.getLogClient(); clt != nil {
return clt, nil
}
cfg, err := a.RestConfig()
if err != nil {
return nil, err
}
cfg.Timeout = 0
c, err := kubernetes.NewForConfig(cfg)
if err != nil {
return nil, err
}
a.setLogClient(c)
return a.getLogClient(), nil
}
// Dial returns a handle to api server or die.
func (a *APIClient) Dial() (kubernetes.Interface, error) {
if !a.getConnOK() {
return nil, errors.New("no connection to dial")
}
if c := a.getClient(); c != nil {
return c, nil
}
cfg, err := a.RestConfig()
if err != nil {
return nil, err
}
if c, err := kubernetes.NewForConfig(cfg); err != nil {
return nil, err
} else {
a.setClient(c)
}
return a.getClient(), nil
}
// RestConfig returns a rest api client.
func (a *APIClient) RestConfig() (*restclient.Config, error) {
return a.config.RESTConfig()
}
// CachedDiscovery returns a cached discovery client.
func (a *APIClient) CachedDiscovery() (*disk.CachedDiscoveryClient, error) {
if !a.getConnOK() {
return nil, errors.New("no connection to cached dial")
}
if c := a.getCachedClient(); c != nil {
return c, nil
}
cfg, err := a.RestConfig()
if err != nil {
return nil, err
}
httpCacheDir := filepath.Join(mustHomeDir(), ".kube", "http-cache")
discCacheDir := filepath.Join(mustHomeDir(), ".kube", "cache", "discovery", toHostDir(cfg.Host))
c, err := disk.NewCachedDiscoveryClientForConfig(cfg, discCacheDir, httpCacheDir, cacheExpiry)
if err != nil {
return nil, err
}
a.setCachedClient(c)
return a.getCachedClient(), nil
}
// DynDial returns a handle to a dynamic interface.
func (a *APIClient) DynDial() (dynamic.Interface, error) {
if c := a.getDClient(); c != nil {
return c, nil
}
cfg, err := a.RestConfig()
if err != nil {
return nil, err
}
c, err := dynamic.NewForConfig(cfg)
if err != nil {
return nil, err
}
a.setDClient(c)
return a.getDClient(), nil
}
// MXDial returns a handle to the metrics server.
func (a *APIClient) MXDial() (*versioned.Clientset, error) {
if c := a.getMxsClient(); c != nil {
return c, nil
}
cfg, err := a.RestConfig()
if err != nil {
return nil, err
}
c, err := versioned.NewForConfig(cfg)
if err != nil {
return nil, err
}
a.setMxsClient(c)
return a.getMxsClient(), err
}
// SwitchContext handles kubeconfig context switches.
func (a *APIClient) SwitchContext(name string) error {
log.Debug().Msgf("Switching context %q", name)
if err := a.config.SwitchContext(name); err != nil {
return err
}
a.reset()
ResetMetrics()
if !a.CheckConnectivity() {
return fmt.Errorf("unable to connect to context %q", name)
}
return nil
}
func (a *APIClient) reset() {
a.config.reset()
a.cache = cache.NewLRUExpireCache(cacheSize)
a.nsClient = nil
a.setDClient(nil)
a.setMxsClient(nil)
a.setCachedClient(nil)
a.setClient(nil)
a.setLogClient(nil)
a.setConnOK(true)
}
func (a *APIClient) checkCacheBool(key string) (state bool, ok bool) {
v, found := a.cache.Get(key)
if !found {
return
}
state, ok = v.(bool)
return
}
func (a *APIClient) supportsMetricsResources() error {
supported, ok := a.checkCacheBool(cacheMXAPIKey)
if ok {
if supported {
return nil
}
return noMetricServerErr
}
defer func() {
a.cache.Add(cacheMXAPIKey, supported, cacheExpiry)
}()
dial, err := a.Dial()
if err != nil {
log.Warn().Err(err).Msgf("Unable to dial discovery API")
return err
}
apiGroups, err := dial.Discovery().ServerGroups()
if err != nil {
return err
}
for _, grp := range apiGroups.Groups {
if grp.Name != metricsapi.GroupName {
continue
}
if checkMetricsVersion(grp) {
supported = true
return nil
}
}
return metricsUnsupportedErr
}
func checkMetricsVersion(grp metav1.APIGroup) bool {
for _, v := range grp.Versions {
for _, supportedVersion := range supportedMetricsAPIVersions {
if v.Version == supportedVersion {
return true
}
}
}
return false
}