-
Notifications
You must be signed in to change notification settings - Fork 16
/
utils.go
997 lines (834 loc) · 28.7 KB
/
utils.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
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
package kubernetes
import (
"context"
"errors"
"fmt"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
goYaml "gopkg.in/yaml.v3"
apiextension "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/util/yaml"
"k8s.io/client-go/dynamic"
"k8s.io/client-go/kubernetes"
_ "k8s.io/client-go/plugin/pkg/client/auth/azure"
_ "k8s.io/client-go/plugin/pkg/client/auth/gcp"
_ "k8s.io/client-go/plugin/pkg/client/auth/oidc"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
clientcmdapi "k8s.io/client-go/tools/clientcmd/api"
"github.com/mitchellh/go-homedir"
filehelpers "github.com/turbot/go-kit/files"
"github.com/turbot/go-kit/helpers"
"github.com/turbot/steampipe-plugin-sdk/v5/connection"
"github.com/turbot/steampipe-plugin-sdk/v5/plugin"
"github.com/turbot/steampipe-plugin-sdk/v5/plugin/transform"
)
type SourceType string
const (
Deployed SourceType = "deployed"
Helm SourceType = "helm"
Manifest SourceType = "manifest"
All SourceType = "all"
)
// Validate the source type.
func (sourceType SourceType) IsValid() error {
switch sourceType {
case Deployed, Helm, Manifest, All:
return nil
}
return fmt.Errorf("invalid source type: %s", sourceType)
}
// Convert the source type to its string equivalent
func (sourceType SourceType) String() string {
return string(sourceType)
}
// ToSourceTypes is used to convert SourceType to []string
func (sourceType SourceType) ToSourceTypes() []string {
if sourceType == All {
return []string{Deployed.String(), Helm.String(), Manifest.String()}
} else {
return []string{sourceType.String()}
}
}
// GetNewClientset :: gets client for querying k8s apis for the provided context
func GetNewClientset(ctx context.Context, d *plugin.QueryData) (*kubernetes.Clientset, error) {
logger := plugin.Logger(ctx)
// have we already created and cached the session?
serviceCacheKey := "k8sClient"
if cachedData, ok := d.ConnectionManager.Cache.Get(serviceCacheKey); ok {
return cachedData.(*kubernetes.Clientset), nil
}
kubeconfig, err := getK8Config(ctx, d)
if err != nil {
logger.Error("GetNewClientset", "getK8Config", err)
return nil, err
}
// Return nil if deployed resources should not be included
if kubeconfig == nil {
return nil, nil
}
// Get a rest.Config from the kubeconfig file.
restconfig, err := kubeconfig.ClientConfig()
if err != nil {
// if .kube/config file is not available check for inClusterConfig
configErr := err
if strings.Contains(err.Error(), ".kube/config: no such file or directory") {
clientset, err := inClusterConfig(ctx)
if err != nil {
return nil, errors.New(configErr.Error() + ", " + err.Error())
}
// save clientset in cache
d.ConnectionManager.Cache.Set(serviceCacheKey, clientset)
return clientset, nil
}
return nil, err
}
clientset, err := kubernetes.NewForConfig(restconfig)
if err != nil {
return nil, err
}
// save clientset in cache
d.ConnectionManager.Cache.Set(serviceCacheKey, clientset)
return clientset, err
}
func inClusterConfig(ctx context.Context) (*kubernetes.Clientset, error) {
clusterConfig, err := rest.InClusterConfig()
if err != nil {
plugin.Logger(ctx).Error("InClusterConfig", "InClusterConfig", err)
return nil, err
}
clientset, err := kubernetes.NewForConfig(clusterConfig)
if err != nil {
plugin.Logger(ctx).Error("InClusterConfig", "NewForConfig", err)
return nil, err
}
return clientset, nil
}
// GetNewClientCRD :: gets client for querying k8s apis for CustomResourceDefinition
func GetNewClientCRD(ctx context.Context, d *plugin.QueryData) (*apiextension.Clientset, error) {
// have we already created and cached the session?
serviceCacheKey := "GetNewClientCRD"
if cachedData, ok := d.ConnectionManager.Cache.Get(serviceCacheKey); ok {
return cachedData.(*apiextension.Clientset), nil
}
kubeconfig, err := getK8Config(ctx, d)
if err != nil {
plugin.Logger(ctx).Error("GetNewClientCRD", "getK8Config", err)
return nil, err
}
// Return nil if deployed resources should not be included
if kubeconfig == nil {
return nil, nil
}
// Get a rest.Config from the kubeconfig file.
restconfig, err := kubeconfig.ClientConfig()
if err != nil {
// if .kube/config file is not available check for inClusterConfig
configErr := err
if strings.Contains(err.Error(), ".kube/config: no such file or directory") {
clientset, err := inClusterConfigCRD(ctx)
if err != nil {
return nil, errors.New(configErr.Error() + ", " + err.Error())
}
// save clientset in cache
d.ConnectionManager.Cache.Set(serviceCacheKey, clientset)
return clientset, nil
}
return nil, err
}
clientset, err := apiextension.NewForConfig(restconfig)
if err != nil {
plugin.Logger(ctx).Error("GetNewClientCRD", "NewForConfig", err)
return nil, err
}
// save clientset in cache
d.ConnectionManager.Cache.Set(serviceCacheKey, clientset)
return clientset, err
}
// GetNewClientCRDRaw :: gets client for querying k8s apis for CustomResourceDefinition
func GetNewClientCRDRaw(ctx context.Context, cc *connection.ConnectionCache, c *plugin.Connection) (*apiextension.Clientset, error) {
logger := plugin.Logger(ctx)
// have we already created and cached the session?
serviceCacheKey := "GetNewClientCRDRaw"
if cachedData, ok := cc.Get(ctx, serviceCacheKey); ok {
return cachedData.(*apiextension.Clientset), nil
}
kubeconfig, err := getK8ConfigRaw(ctx, cc, c)
if err != nil {
logger.Error("GetNewClientCRDRaw", "getK8ConfigRaw", err)
return nil, err
}
// Return nil if deployed resources should not be included
if kubeconfig == nil {
return nil, nil
}
// Get a rest.Config from the kubeconfig file.
restconfig, err := kubeconfig.ClientConfig()
if err != nil {
// if .kube/config file is not available check for inClusterConfig
configErr := err
if strings.Contains(err.Error(), ".kube/config: no such file or directory") {
clientset, err := inClusterConfigCRD(ctx)
if err != nil {
return nil, errors.New(configErr.Error() + ", " + err.Error())
}
// save clientset in cache
cacheErr := cc.Set(ctx, serviceCacheKey, clientset)
if cacheErr != nil {
plugin.Logger(ctx).Error("inClusterConfigCRD", "cache-set", cacheErr)
return nil, err
}
return clientset, nil
}
return nil, err
}
clientset, err := apiextension.NewForConfig(restconfig)
if err != nil {
return nil, err
}
// save clientset in cache
cacheErr := cc.Set(ctx, serviceCacheKey, clientset)
if cacheErr != nil {
plugin.Logger(ctx).Error("GetNewClientCRDRaw", "cache-set", cacheErr)
return nil, err
}
return clientset, nil
}
func inClusterConfigCRD(ctx context.Context) (*apiextension.Clientset, error) {
clusterConfig, err := rest.InClusterConfig()
if err != nil {
plugin.Logger(ctx).Error("inClusterConfigCRD", "InClusterConfig", err)
return nil, err
}
clientset, err := apiextension.NewForConfig(clusterConfig)
if err != nil {
plugin.Logger(ctx).Error("inClusterConfigCRD", "NewForConfig", err)
return nil, err
}
return clientset, nil
}
// GetNewClientDynamic :: gets client for querying k8s apis for Dynamic Interface
func GetNewClientDynamic(ctx context.Context, d *plugin.QueryData) (dynamic.Interface, error) {
// have we already created and cached the session?
serviceCacheKey := "GetNewClientDynamic"
if cachedData, ok := d.ConnectionManager.Cache.Get(serviceCacheKey); ok {
return cachedData.(dynamic.Interface), nil
}
kubeconfig, err := getK8Config(ctx, d)
if err != nil {
return nil, err
}
if kubeconfig == nil {
return nil, nil
}
// Get a rest.Config from the kubeconfig file.
restconfig, err := kubeconfig.ClientConfig()
if err != nil {
// if .kube/config file is not available check for inClusterConfig
configErr := err
if strings.Contains(err.Error(), ".kube/config: no such file or directory") {
clientset, err := inClusterConfigCRDDynamic(ctx)
if err != nil {
return nil, errors.New(configErr.Error() + ", " + err.Error())
}
// save clientset in cache
d.ConnectionManager.Cache.Set(serviceCacheKey, clientset)
return clientset, nil
}
return nil, err
}
clientset, err := dynamic.NewForConfig(restconfig)
if err != nil {
return nil, err
}
// save clientset in cache
d.ConnectionManager.Cache.Set(serviceCacheKey, clientset)
return clientset, err
}
func inClusterConfigCRDDynamic(ctx context.Context) (dynamic.Interface, error) {
clusterConfig, err := rest.InClusterConfig()
if err != nil {
plugin.Logger(ctx).Error("inClusterConfigCRDDynamic", "InClusterConfig", err)
return nil, err
}
clientset, err := dynamic.NewForConfig(clusterConfig)
if err != nil {
plugin.Logger(ctx).Error("inClusterConfigCRDDynamic", "NewForConfig", err)
return nil, err
}
return clientset, nil
}
// Get kubernetes config based on environment variable and plugin config
func getK8Config(ctx context.Context, d *plugin.QueryData) (clientcmd.ClientConfig, error) {
logger := plugin.Logger(ctx)
logger.Trace("getK8Config")
// have we already created and cached the session?
cacheKey := "getK8Config"
if cachedData, ok := d.ConnectionManager.Cache.Get(cacheKey); ok {
return cachedData.(clientcmd.ClientConfig), nil
}
// get kubernetes config info
kubernetesConfig := GetConfig(d.Connection)
// Check for the sourceTypes argument in the config
// Default set to include values
var sources = All.ToSourceTypes()
if kubernetesConfig.SourceTypes != nil {
sources = kubernetesConfig.SourceTypes
}
// TODO: Remove once `SourceType` is obsolete
if kubernetesConfig.SourceTypes == nil && kubernetesConfig.SourceType != nil {
if *kubernetesConfig.SourceType != "all" { // if is all, sources is already set by default
sources = []string{*kubernetesConfig.SourceType}
}
}
if !helpers.StringSliceContains(sources, "deployed") {
plugin.Logger(ctx).Debug("getK8Config", "Returning nil for API server client.", "source_types", sources, "connection", d.Connection.Name)
return nil, nil
}
// Set default loader and overriding rules
loader := &clientcmd.ClientConfigLoadingRules{}
overrides := &clientcmd.ConfigOverrides{}
// variable to store paths for kubernetes config
// default kube config path
var configPaths = []string{"~/.kube/config"}
if kubernetesConfig.ConfigPath != nil {
configPaths = []string{*kubernetesConfig.ConfigPath}
} else if kubernetesConfig.ConfigPaths != nil && len(kubernetesConfig.ConfigPaths) > 0 {
plugin.Logger(ctx).Warn("config_paths parameter is deprecated and will be removed after 31st July 2023, please use config_path instead.")
configPaths = kubernetesConfig.ConfigPaths
} else if v := os.Getenv("KUBECONFIG"); v != "" {
configPaths = []string{v}
} else if v := os.Getenv("KUBE_CONFIG_PATH"); v != "" {
configPaths = []string{v}
} else if v := os.Getenv("KUBE_CONFIG_PATHS"); v != "" {
plugin.Logger(ctx).Warn("KUBE_CONFIG_PATHS parameter is deprecated and will be removed after 31st July 2023, please use KUBECONFIG or KUBE_CONFIG_PATH instead.")
configPaths = filepath.SplitList(v)
} else if v := os.Getenv("KUBERNETES_MASTER"); v != "" {
plugin.Logger(ctx).Warn("KUBERNETES_MASTER parameter is deprecated and will be removed after 31st July 2023, please use KUBECONFIG or KUBE_CONFIG_PATH instead.")
configPaths = []string{v}
}
if len(configPaths) > 0 {
expandedPaths := []string{}
for _, p := range configPaths {
path, err := homedir.Expand(p)
if err != nil {
return nil, err
}
expandedPaths = append(expandedPaths, path)
}
if len(expandedPaths) == 1 {
loader.ExplicitPath = expandedPaths[0]
} else {
loader.Precedence = expandedPaths
}
if kubernetesConfig.ConfigContext != nil {
overrides.CurrentContext = *kubernetesConfig.ConfigContext
overrides.Context = clientcmdapi.Context{}
}
}
kubeconfig := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(loader, overrides)
// save the config in cache
d.ConnectionManager.Cache.Set(cacheKey, kubeconfig)
return kubeconfig, nil
}
// Get kubernetes config based on environment variable and plugin config
func getK8ConfigRaw(ctx context.Context, cc *connection.ConnectionCache, c *plugin.Connection) (clientcmd.ClientConfig, error) {
logger := plugin.Logger(ctx)
// have we already created and cached the session?
cacheKey := "getK8ConfigRaw"
if cachedData, ok := cc.Get(ctx, cacheKey); ok {
return cachedData.(clientcmd.ClientConfig), nil
}
// get kubernetes config info
kubernetesConfig := GetConfig(c)
// Check for the sourceTypes argument in the config.
// Default set to include values.
var sources = All.ToSourceTypes()
if kubernetesConfig.SourceTypes != nil {
sources = kubernetesConfig.SourceTypes
}
// TODO: Remove once `SourceType` is obsolete
if kubernetesConfig.SourceTypes == nil && kubernetesConfig.SourceType != nil {
if *kubernetesConfig.SourceType != "all" { // if is all, sources is already set by default
sources = []string{*kubernetesConfig.SourceType}
}
}
if !helpers.StringSliceContains(sources, "deployed") {
plugin.Logger(ctx).Debug("getK8ConfigRaw", "Returning nil for API server client.", "source_types", sources, "connection", c.Name)
return nil, nil
}
// Set default loader and overriding rules
loader := &clientcmd.ClientConfigLoadingRules{}
overrides := &clientcmd.ConfigOverrides{}
// variable to store paths for kubernetes config
// default kube config path
var configPaths = []string{"~/.kube/config"}
if kubernetesConfig.ConfigPath != nil {
configPaths = []string{*kubernetesConfig.ConfigPath}
} else if kubernetesConfig.ConfigPaths != nil && len(kubernetesConfig.ConfigPaths) > 0 {
plugin.Logger(ctx).Warn("config_paths parameter is deprecated and will be removed after 31st July 2023, please use config_path instead.")
configPaths = kubernetesConfig.ConfigPaths
} else if v := os.Getenv("KUBECONFIG"); v != "" {
configPaths = []string{v}
} else if v := os.Getenv("KUBE_CONFIG_PATH"); v != "" {
configPaths = []string{v}
} else if v := os.Getenv("KUBE_CONFIG_PATHS"); v != "" {
plugin.Logger(ctx).Warn("KUBE_CONFIG_PATHS parameter is deprecated and will be removed after 31st July 2023, please use KUBECONFIG or KUBE_CONFIG_PATH instead.")
configPaths = filepath.SplitList(v)
} else if v := os.Getenv("KUBERNETES_MASTER"); v != "" {
plugin.Logger(ctx).Warn("KUBERNETES_MASTER parameter is deprecated and will be removed after 31st July 2023, please use KUBECONFIG or KUBE_CONFIG_PATH instead.")
configPaths = []string{v}
}
if len(configPaths) > 0 {
expandedPaths := []string{}
for _, p := range configPaths {
path, err := homedir.Expand(p)
if err != nil {
return nil, err
}
expandedPaths = append(expandedPaths, path)
}
if len(expandedPaths) == 1 {
loader.ExplicitPath = expandedPaths[0]
} else {
loader.Precedence = expandedPaths
}
if kubernetesConfig.ConfigContext != nil {
overrides.CurrentContext = *kubernetesConfig.ConfigContext
overrides.Context = clientcmdapi.Context{}
}
}
kubeconfig := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(loader, overrides)
// save the config in cache
err := cc.Set(ctx, cacheKey, kubeconfig)
if err != nil {
logger.Error("getK8ConfigRaw", "cache-set", err)
}
return kubeconfig, nil
}
//// HYDRATE FUNCTIONS
func getKubectlContext(ctx context.Context, d *plugin.QueryData, _ *plugin.HydrateData) (interface{}, error) {
cacheKey := "getKubectlContext"
if cachedData, ok := d.ConnectionManager.Cache.Get(cacheKey); ok {
return cachedData.(string), nil
}
kubeconfig, err := getK8Config(ctx, d)
if err != nil {
return nil, err
}
if kubeconfig == nil {
return nil, nil
}
rawConfig, _ := kubeconfig.RawConfig()
currentContext := rawConfig.CurrentContext
// get kubernetes config info
kubernetesConfig := GetConfig(d.Connection)
// If set in plugin's (~/.steampipe/config/kubernetes.spc) connection profile
if kubernetesConfig.ConfigContext != nil {
currentContext = *kubernetesConfig.ConfigContext
}
// save current context in cache
d.ConnectionManager.Cache.Set(cacheKey, currentContext)
return currentContext, nil
}
//// COMMON TRANSFORM FUNCTIONS
func v1TimeToRFC3339(_ context.Context, d *transform.TransformData) (interface{}, error) {
if d.Value == nil {
return nil, nil
}
switch v := d.Value.(type) {
case v1.Time:
return v.ToUnstructured(), nil
case *v1.Time:
if v == nil {
return nil, nil
}
return v.ToUnstructured(), nil
default:
return nil, fmt.Errorf("invalid time format %T! ", v)
}
}
func v1MicroTimeToRFC3339(_ context.Context, d *transform.TransformData) (interface{}, error) {
if d.Value == nil {
return nil, nil
}
switch v := d.Value.(type) {
case v1.MicroTime:
return v1.NewTime(v.Time).ToUnstructured(), nil
case *v1.MicroTime:
if v == nil {
return nil, nil
}
return v1.NewTime(v.Time).ToUnstructured(), nil
default:
return nil, fmt.Errorf("invalid time format %T! ", v)
}
}
func labelSelectorToString(_ context.Context, d *transform.TransformData) (interface{}, error) {
if d.Value == nil {
return nil, nil
}
selector := d.Value.(*v1.LabelSelector)
ss, err := v1.LabelSelectorAsSelector(selector)
if err != nil {
return nil, err
}
return ss.String(), nil
}
func selectorMapToString(ctx context.Context, d *transform.TransformData) (interface{}, error) {
logger := plugin.Logger(ctx)
logger.Trace("selectorMapToString")
selector_map := d.Value.(map[string]string)
if len(selector_map) == 0 {
return nil, nil
}
selector_string := labels.SelectorFromSet(selector_map).String()
return selector_string, nil
}
//// Other Utility functions
func isNotFoundError(err error) bool {
return strings.HasSuffix(err.Error(), "not found")
}
func getCommonOptionalKeyQuals() []*plugin.KeyColumn {
return []*plugin.KeyColumn{
{Name: "name", Require: plugin.Optional},
{Name: "namespace", Require: plugin.Optional},
}
}
func getOptionalKeyQualWithCommonKeyQuals(otherOptionalQuals []*plugin.KeyColumn) []*plugin.KeyColumn {
return append(otherOptionalQuals, getCommonOptionalKeyQuals()...)
}
func getCommonOptionalKeyQualsValueForFieldSelector(d *plugin.QueryData) []string {
fieldSelectors := []string{}
if d.EqualsQualString("name") != "" {
fieldSelectors = append(fieldSelectors, fmt.Sprintf("metadata.name=%v", d.EqualsQualString("name")))
}
return fieldSelectors
}
func mergeTags(labels map[string]string, annotations map[string]string) map[string]string {
tags := make(map[string]string)
for k, v := range annotations {
tags[k] = v
}
for k, v := range labels {
tags[k] = v
}
return tags
}
//// Utility functions for manifest files
type parsedContent struct {
ParsedData any
Kind string
Path string
SourceType string
StartLine int
EndLine int
}
// Returns the manifest file content based on the kind provided
func fetchResourceFromManifestFileByKind(ctx context.Context, d *plugin.QueryData, kind string) ([]parsedContent, error) {
if kind == "" {
return nil, fmt.Errorf("missing required property: kind")
}
var data []parsedContent
// Get parsed content from manifest files
parsedContents, err := getParsedManifestFileContent(ctx, d)
if err != nil {
return nil, err
}
// Get parsed content from rendered Helm templates
renderedTemplateContents, err := getRenderedHelmTemplateContent(ctx, d)
if err != nil {
return nil, err
}
parsedContents = append(parsedContents, renderedTemplateContents...)
for _, content := range parsedContents {
if content.Kind == kind {
data = append(data, content)
}
}
return data, nil
}
// Get the parsed contents of the given files.
func getParsedManifestFileContent(ctx context.Context, d *plugin.QueryData) ([]parsedContent, error) {
conn, err := parsedManifestFileContentCached(ctx, d, nil)
if err != nil {
return nil, err
}
return conn.([]parsedContent), nil
}
// Cached form of the parsed file content.
var parsedManifestFileContentCached = plugin.HydrateFunc(parsedManifestFileContentUncached).Memoize()
// parsedManifestFileContentUncached is the actual implementation of getParsedManifestFileContent, which should
// be run only once per connection. Do not call this directly, use
// getParsedManifestFileContent instead.
func parsedManifestFileContentUncached(ctx context.Context, d *plugin.QueryData, _ *plugin.HydrateData) (any, error) {
plugin.Logger(ctx).Debug("parsedManifestFileContentUncached", "Parsing file content", "connection", d.Connection.Name)
// Read the config
resolvedPaths, err := resolveManifestFilePaths(ctx, d)
if err != nil {
return nil, err
}
var parsedContents []parsedContent
for _, path := range resolvedPaths {
// Load the file into a buffer
content, err := os.ReadFile(path)
if err != nil {
plugin.Logger(ctx).Error("parsedManifestFileContentUncached", "failed to read file", err, "path", path)
return nil, err
}
// Check for the start of the document
pos := 0
for _, resource := range strings.Split(string(content), "---") {
// Skip empty documents, `Decode` will fail on them
// Also, increment the pos to include the separator position (e.g. ---)
if len(resource) == 0 {
pos++
continue
}
// Calculate the length of the YAML resource block
blockLength := strings.Split(strings.ReplaceAll(resource, " ", ""), "\n")
// Remove the extra lines added during the split operation based on the separator
blockLength = blockLength[:len(blockLength)-1]
if blockLength[0] == "" {
blockLength = blockLength[1:]
}
// skip if no kind defined
if !(strings.Contains(resource, "kind:") || strings.Contains(resource, "\"kind\":")) {
pos = pos + len(blockLength) + 1
continue
}
obj := &unstructured.Unstructured{}
err = yaml.Unmarshal([]byte(resource), obj)
if err != nil {
plugin.Logger(ctx).Error("parsedManifestFileContentUncached", "failed to unmarshal the content", err, "path", path)
return nil, err
}
obj.SetAPIVersion(obj.GetAPIVersion())
obj.SetKind(obj.GetKind())
gvk := obj.GetObjectKind().GroupVersionKind()
obj.SetGroupVersionKind(schema.GroupVersionKind{
Group: gvk.Group,
Version: gvk.Version,
Kind: gvk.Kind,
})
// Convert the content to concrete type based on the resource kind
targetObj, err := convertUnstructuredDataToType(obj)
if err != nil {
plugin.Logger(ctx).Error("parsedManifestFileContentUncached", "failed to convert content into a concrete type", err, "path", path)
return nil, err
}
parsedContents = append(parsedContents, parsedContent{
ParsedData: targetObj,
Kind: obj.GetKind(),
Path: path,
SourceType: "manifest",
StartLine: pos + 1, // Since starts from 0
EndLine: pos + len(blockLength),
})
// Increment the position by the length of the block
// the value is added with 1 to include the separator
pos = pos + len(blockLength) + 1
}
}
return parsedContents, nil
}
// Returns the list of file paths/glob patterns after resolving all the given manifest file paths.
func resolveManifestFilePaths(ctx context.Context, d *plugin.QueryData) ([]string, error) {
// Read the config
kubernetesConfig := GetConfig(d.Connection)
// Check for the sourceTypes argument in the config. Valid values are: "deployed", "manifest" and "helm".
// Default set to include values.
var sources = All.ToSourceTypes()
if kubernetesConfig.SourceTypes != nil {
sources = kubernetesConfig.SourceTypes
}
// TODO: Remove once `SourceType` is obsolete
if kubernetesConfig.SourceTypes == nil && kubernetesConfig.SourceType != nil {
if *kubernetesConfig.SourceType != "all" { // if is all, sources is already set by default
sources = []string{*kubernetesConfig.SourceType}
}
}
// Return no files if manifest not set in source_types or if we omit setting any file paths
if !helpers.StringSliceContains(sources, "manifest") {
return nil, nil
}
if kubernetesConfig.ManifestFilePaths == nil {
return nil, nil
}
// Gather file path matches for the glob
var matches, resolvedPaths []string
paths := kubernetesConfig.ManifestFilePaths
for _, i := range paths {
// List the files in the given source directory
files, err := d.GetSourceFiles(i)
if err != nil {
return nil, err
}
matches = append(matches, files...)
}
// Sanitize the matches to ignore the directories
for _, i := range matches {
// Ignore directories
if filehelpers.DirectoryExists(i) {
continue
}
resolvedPaths = append(resolvedPaths, i)
}
return resolvedPaths, nil
}
//// HELM values
type Rows []Row
type Row struct {
Path string
Key []string
Value interface{}
Tag *string
PreComments []string
HeadComment string
LineComment string
FootComment string
StartLine int
StartColumn int
}
func treeToList(tree *goYaml.Node, prefix []string, rows *Rows, preComments []string, headComments []string, footComments []string) {
switch tree.Kind {
case goYaml.DocumentNode:
for i, v := range tree.Content {
localComments := []string{}
headComments = []string{}
footComments = []string{}
if i == 0 {
localComments = append(localComments, preComments...)
if tree.HeadComment != "" {
localComments = append(localComments, tree.HeadComment)
headComments = append(headComments, tree.HeadComment)
}
if tree.FootComment != "" {
footComments = append(footComments, tree.FootComment)
}
if tree.LineComment != "" {
localComments = append(localComments, tree.LineComment)
}
}
treeToList(v, prefix, rows, localComments, headComments, footComments)
}
case goYaml.SequenceNode:
if len(tree.Content) == 0 {
row := Row{
Key: prefix,
Value: []string{},
Tag: &tree.Tag,
StartLine: tree.Line,
StartColumn: tree.Column,
PreComments: preComments,
HeadComment: strings.Join(headComments, ","),
LineComment: tree.LineComment,
FootComment: strings.Join(footComments, ","),
}
*rows = append(*rows, row)
}
for i, v := range tree.Content {
localComments := []string{}
headComments = []string{}
footComments = []string{}
if i == 0 {
localComments = append(localComments, preComments...)
if tree.HeadComment != "" {
localComments = append(localComments, tree.HeadComment)
headComments = append(headComments, tree.HeadComment)
}
if tree.LineComment != "" {
localComments = append(localComments, tree.LineComment)
}
}
newKey := make([]string, len(prefix))
copy(newKey, prefix)
newKey = append(newKey, strconv.Itoa(i))
treeToList(v, newKey, rows, localComments, headComments, footComments)
}
case goYaml.MappingNode:
localComments := []string{}
headComments = []string{}
footComments = []string{}
localComments = append(localComments, preComments...)
if tree.HeadComment != "" {
localComments = append(localComments, tree.HeadComment)
headComments = append(headComments, tree.HeadComment)
}
if tree.FootComment != "" {
footComments = append(footComments, tree.FootComment)
}
if tree.LineComment != "" {
localComments = append(localComments, tree.LineComment)
}
if len(tree.Content) == 0 {
row := Row{
Key: prefix,
Value: map[string]interface{}{},
Tag: &tree.Tag,
StartLine: tree.Line,
StartColumn: tree.Column,
PreComments: preComments,
HeadComment: strings.Join(headComments, ","),
LineComment: tree.LineComment,
FootComment: strings.Join(footComments, ","),
}
*rows = append(*rows, row)
}
i := 0
for i < len(tree.Content)-1 {
key := tree.Content[i]
val := tree.Content[i+1]
i = i + 2
if key.HeadComment != "" {
localComments = append(localComments, key.HeadComment)
headComments = append(headComments, key.HeadComment)
}
if key.FootComment != "" {
footComments = append(footComments, key.FootComment)
}
if key.LineComment != "" {
localComments = append(localComments, key.LineComment)
}
newKey := make([]string, len(prefix))
copy(newKey, prefix)
newKey = append(newKey, key.Value)
treeToList(val, newKey, rows, localComments, headComments, footComments)
localComments = make([]string, 0)
headComments = make([]string, 0)
footComments = make([]string, 0)
}
case goYaml.ScalarNode:
row := Row{
Key: prefix,
Value: tree.Value,
Tag: &tree.Tag,
StartLine: tree.Line,
StartColumn: tree.Column,
PreComments: preComments,
HeadComment: strings.Join(headComments, ","),
LineComment: tree.LineComment,
FootComment: strings.Join(footComments, ","),
}
if tree.Tag == "!!null" {
row.Value = nil
}
*rows = append(*rows, row)
}
}
func keysToSnakeCase(_ context.Context, d *transform.TransformData) (interface{}, error) {
keys := d.Value.([]string)
snakes := []string{}
re := regexp.MustCompile(`[^A-Za-z0-9_]`)
for _, k := range keys {
snakes = append(snakes, re.ReplaceAllString(k, "_"))
}
return strings.Join(snakes, "."), nil
}