This repository has been archived by the owner on Jan 19, 2023. It is now read-only.
/
customresource.go
117 lines (94 loc) · 2.44 KB
/
customresource.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
package kubernetes
import (
"errors"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime/schema"
)
// CRDResources returns a list of resources identified by group/version/kind a CRD supports.
func CRDResources(crd *unstructured.Unstructured) ([]schema.GroupVersionKind, error) {
if crd == nil {
return nil, errors.New("crd is nil")
}
var list []schema.GroupVersionKind
group, ok, err := unstructured.NestedString(crd.Object, "spec", "group")
if err != nil {
return nil, err
}
if !ok {
return nil, errors.New("crd did not have a spec.group")
}
kind, ok, err := unstructured.NestedString(crd.Object, "spec", "names", "kind")
if err != nil {
return nil, err
}
if !ok {
return nil, errors.New("crd did not have a spec.names.kind")
}
versionsRaw, ok, err := unstructured.NestedSlice(crd.Object, "spec", "versions")
if err != nil {
return nil, err
}
if ok {
for _, versionRaw := range versionsRaw {
version, ok := versionRaw.(map[string]interface{})
if !ok {
return nil, errors.New("version was of an unknown type")
}
isServed, ok, err := unstructured.NestedBool(version, "served")
if err != nil {
return nil, err
}
if !ok {
return nil, errors.New("version doesn't have served entry")
}
name, ok, err := unstructured.NestedString(version, "name")
if err != nil {
return nil, err
}
if !ok {
return nil, errors.New("version doesn't have name")
}
if isServed {
g := schema.GroupVersionKind{
Group: group,
Version: name,
Kind: kind,
}
if !groupVersionKindsContains(g, list) {
list = append(list, g)
}
}
}
}
version, ok, err := unstructured.NestedString(crd.Object, "spec", "version")
if err != nil {
return nil, err
}
if ok {
g := schema.GroupVersionKind{
Group: group,
Version: version,
Kind: kind,
}
if !groupVersionKindsContains(g, list) {
list = append(list, g)
}
}
return list, nil
}
// CRDContainsResource returns true if a CRD contains a resource.
func CRDContainsResource(crd *unstructured.Unstructured, g schema.GroupVersionKind) (bool, error) {
list, err := CRDResources(crd)
if err != nil {
return false, err
}
return groupVersionKindsContains(g, list), nil
}
func groupVersionKindsContains(g schema.GroupVersionKind, list []schema.GroupVersionKind) bool {
for i := range list {
if g.String() == list[i].String() {
return true
}
}
return false
}