This repository has been archived by the owner on Apr 29, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
resource.go
342 lines (293 loc) · 8.8 KB
/
resource.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
package clientgo
import (
"context"
"fmt"
"github.com/caos/orbos/mntr"
"github.com/pkg/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/client-go/discovery"
"k8s.io/client-go/dynamic"
"strings"
)
var (
ignoredResources = []string{
"componentstatuses",
"endpoints",
"bindings",
"nodes",
"nodes",
"replicationcontrollers",
"podtemplates",
"limitranges",
"apiservices",
"controllerrevisions",
"leases",
"backendconfigs",
"updateinfos",
"runtimeclasses",
"storagestates",
"storageversionmigrations",
"csidrivers",
"csinodes",
"localsubjectaccessreviews",
"selfsubjectaccessreviews",
"selfsubjectrulesreviews",
"subjectaccessreviews",
"tokenreviews",
"scalingpolicies",
"priorityclasses",
}
ignoredGroupResources = []string{
// "metrics.k8s.io/pods",
"metrics.k8s.io/nodes",
"networking.gke.io/managedcertificates",
"networking.gke.io/ingresses",
"networking.gke.io/networkpolicies",
}
)
var (
Limit int64 = 50
)
type ResourceInfo struct {
Group string
Version string
Resource string
Namespaced bool
}
type Resource struct {
Group string
Version string
Resource string
Kind string
Name string
Namespace string
Labels map[string]string
}
type ResourceSorter []*Resource
func (a ResourceSorter) Len() int { return len(a) }
func (a ResourceSorter) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a ResourceSorter) Less(i, j int) bool {
return (a[i].Group < a[j].Group ||
(a[i].Group == a[j].Group && a[i].Version < a[j].Version) ||
(a[i].Group == a[j].Group && a[i].Version == a[j].Version && a[i].Resource < a[j].Resource) ||
(a[i].Group == a[j].Group && a[i].Version == a[j].Version && a[i].Resource == a[j].Resource && a[i].Kind < a[j].Kind) ||
(a[i].Group == a[j].Group && a[i].Version == a[j].Version && a[i].Resource == a[j].Resource && a[i].Kind == a[j].Kind && a[i].Name < a[j].Name) ||
(a[i].Group == a[j].Group && a[i].Version == a[j].Version && a[i].Resource == a[j].Resource && a[i].Kind == a[j].Kind && a[i].Name == a[j].Name && a[i].Namespace < a[j].Namespace))
}
func GetResource(group, version, resource, namespace, name string) (*Resource, error) {
res := schema.GroupVersionResource{Group: group, Version: version, Resource: resource}
conf, err := GetClusterConfig()
if err != nil {
return nil, err
}
clientset, err := dynamic.NewForConfig(conf)
if err != nil {
return nil, err
}
result, err := clientset.Resource(res).Namespace(namespace).Get(context.Background(), name, metav1.GetOptions{})
if err != nil {
return nil, err
}
return &Resource{
Kind: result.GetKind(),
Name: result.GetName(),
Namespace: result.GetNamespace(),
Labels: result.GetLabels(),
}, nil
}
func DeleteResource(resource *Resource) error {
res := schema.GroupVersionResource{Group: resource.Group, Version: resource.Version, Resource: resource.Resource}
conf, err := GetClusterConfig()
if err != nil {
return err
}
client, err := dynamic.NewForConfig(conf)
if err != nil {
return err
}
deletePolicy := metav1.DeletePropagationForeground
deleteOptions := &metav1.DeleteOptions{
PropagationPolicy: &deletePolicy,
}
clientRes := client.Resource(res)
if resource.Namespace != "" {
err = clientRes.Namespace(resource.Namespace).Delete(context.Background(), resource.Name, *deleteOptions)
} else {
err = clientRes.Delete(context.Background(), resource.Name, *deleteOptions)
}
return errors.Wrapf(err, "Error while deleting %s", resource.Name)
}
func GetGroupVersionsResources(monitor mntr.Monitor, filtersResources []string) ([]*ResourceInfo, error) {
listMonitor := monitor.WithFields(map[string]interface{}{
"action": "groupVersionResources",
})
conf, err := GetClusterConfig()
if err != nil {
return nil, err
}
client, err := discovery.NewDiscoveryClientForConfig(conf)
if err != nil {
return nil, err
}
apiGroups, err := client.ServerGroups()
if err != nil {
return nil, err
}
resourceInfoList := make([]*ResourceInfo, 0)
for _, apiGroup := range apiGroups.Groups {
version := apiGroup.PreferredVersion
apiResources, err := client.ServerResourcesForGroupVersion(version.GroupVersion)
if err != nil {
return nil, err
}
for _, apiResource := range apiResources.APIResources {
if filtersResources != nil &&
len(filtersResources) > 0 &&
containsFilter(filtersResources, apiGroup.Name, version.Version, apiResource.Kind) {
continue
}
resourceInfo := &ResourceInfo{
Group: apiGroup.Name,
Version: version.Version,
Resource: apiResource.Name,
Namespaced: apiResource.Namespaced,
}
groupResource := strings.Join([]string{resourceInfo.Group, resourceInfo.Resource}, "/")
if !contains(ignoredResources, resourceInfo.Resource) &&
!contains(ignoredGroupResources, groupResource) {
resourceInfoList = append(resourceInfoList, resourceInfo)
}
}
}
listMonitor.WithField("count", len(resourceInfoList)).Debug("Listed groupVersionsResources")
return resourceInfoList, nil
}
func contains(s []string, e string) bool {
for _, a := range s {
if a == e {
return true
}
}
return false
}
func ListResources(monitor mntr.Monitor, resourceInfoList []*ResourceInfo, labels map[string]string) ([]*Resource, error) {
listMonitor := monitor.WithFields(map[string]interface{}{
"action": "listResources",
})
conf, err := GetClusterConfig()
if err != nil {
return nil, err
}
client, err := dynamic.NewForConfig(conf)
if err != nil {
return nil, err
}
labelSelector := ""
for k, v := range labels {
if labelSelector == "" {
labelSelector = strings.Join([]string{k, v}, "=")
} else {
keyValue := strings.Join([]string{k, v}, "=")
labelSelector = strings.Join([]string{labelSelector, keyValue}, ", ")
}
}
listMonitor.WithFields(map[string]interface{}{
"labelSelector": labelSelector,
}).Debug(fmt.Sprintf("Used labels"))
resourceList := make([]*Resource, 0)
for _, resourceInfo := range resourceInfoList {
gvr := schema.GroupVersionResource{Group: resourceInfo.Group, Version: resourceInfo.Version, Resource: resourceInfo.Resource}
listOpt := metav1.ListOptions{
LabelSelector: labelSelector,
Limit: Limit,
}
list, err := client.Resource(gvr).List(context.Background(), listOpt)
if err != nil {
continue
}
resList, err := getResourcesFromList(resourceInfo.Group, resourceInfo.Version, resourceInfo.Resource, list.Items)
if err != nil {
return nil, err
}
for list.GetContinue() != "" {
listOpt.Continue = list.GetContinue()
listInternal, err := client.Resource(gvr).List(context.Background(), listOpt)
if err != nil {
continue
}
list = listInternal
resListContinue, err := getResourcesFromList(resourceInfo.Group, resourceInfo.Version, resourceInfo.Resource, list.Items)
if err != nil {
return nil, err
}
resList = append(resList, resListContinue...)
}
listMonitor.WithFields(map[string]interface{}{
"group": resourceInfo.Group,
"version": resourceInfo.Version,
"resource": resourceInfo.Resource,
"count": len(resList),
}).Debug("Listed resources")
resourceList = append(resourceList, resList...)
}
listMonitor.WithFields(map[string]interface{}{
"count": len(resourceList),
}).Info("All current resources")
return resourceList, nil
}
func getResourcesFromList(group, version, resource string, list []unstructured.Unstructured) ([]*Resource, error) {
resourceList := make([]*Resource, 0)
for _, item := range list {
name, found, err := unstructured.NestedString(item.Object, "metadata", "name")
if err != nil || !found {
return nil, err
}
kind, _, err := unstructured.NestedString(item.Object, "kind")
if err != nil {
return nil, err
}
namespace, _, err := unstructured.NestedString(item.Object, "metadata", "namespace")
if err != nil {
return nil, err
}
labels, _, err := unstructured.NestedMap(item.Object, "metadata", "labels")
if err != nil {
return nil, err
}
_, found, err = unstructured.NestedSlice(item.Object, "metadata", "ownerReferences")
if err != nil {
return nil, err
}
if found == true {
continue
}
labelStrs := make(map[string]string)
for k, label := range labels {
labelStrs[k] = label.(string)
}
resourceList = append(resourceList, &Resource{
Group: group,
Version: version,
Resource: resource,
Name: name,
Kind: kind,
Namespace: namespace,
Labels: labelStrs,
})
}
return resourceList, nil
}
func GetFilter(group, version, kind string) string {
return strings.Join([]string{group, version, kind}, "/")
}
func containsFilter(filters []string, group, version, kind string) bool {
compFilter := GetFilter(group, version, kind)
for _, filter := range filters {
if filter == compFilter {
return true
}
}
return false
}