forked from Shopify/kubeaudit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.go
89 lines (73 loc) · 2.17 KB
/
util.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
package kubeaudit
import (
"bytes"
"fmt"
"github.com/Shopify/kubeaudit/internal/k8sinternal"
"github.com/Shopify/kubeaudit/pkg/k8s"
"gopkg.in/yaml.v3"
)
func getResourcesFromClient(client k8sinternal.KubeClient, options k8sinternal.ClientOptions) ([]KubeResource, error) {
var resources []KubeResource
k8sresources, err := client.GetAllResources(options)
if err != nil {
return nil, err
}
for _, resource := range k8sresources {
resources = append(resources, &kubeResource{object: resource})
}
return resources, nil
}
func getResourcesFromManifest(data []byte) ([]KubeResource, error) {
var resources []KubeResource
bufSlice := bytes.Split(data, []byte("---"))
for _, b := range bufSlice {
obj, err := k8sinternal.DecodeResource(b)
if err == nil && obj != nil {
source := &kubeResource{
object: obj,
bytes: b,
}
resources = append(resources, source)
} else if err := yaml.Unmarshal(data, &yaml.Node{}); err != nil {
return nil, fmt.Errorf("Invalid yaml: %w", err)
} else {
resources = append(resources, &kubeResource{bytes: b})
}
}
return resources, nil
}
func auditResources(resources []KubeResource, auditable []Auditable) ([]Result, error) {
var results []Result
for _, resource := range resources {
result, err := auditResource(resource, resources, auditable)
if err != nil {
return nil, err
}
results = append(results, result)
}
return results, nil
}
func auditResource(resource KubeResource, resources []KubeResource, auditables []Auditable) (Result, error) {
result := &WorkloadResult{
Resource: resource,
AuditResults: []*AuditResult{},
}
if resource.Object() == nil {
return result, nil
}
for _, auditable := range auditables {
auditResults, err := auditable.Audit(resource.Object(), unwrapResources(resources))
if err != nil {
return nil, err
}
result.AuditResults = append(result.AuditResults, auditResults...)
}
return result, nil
}
func unwrapResources(resources []KubeResource) []k8s.Resource {
unwrappedResources := make([]k8s.Resource, 0, len(resources))
for _, resource := range resources {
unwrappedResources = append(unwrappedResources, resource.Object())
}
return unwrappedResources
}