/
scale.go
74 lines (61 loc) · 2.04 KB
/
scale.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
package utils
import (
"context"
"fmt"
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/labels"
"sigs.k8s.io/controller-runtime/pkg/client"
autoscalingapiv1 "k8s.io/api/autoscaling/v1"
autoscalingv2 "k8s.io/api/autoscaling/v2beta2"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/client-go/scale"
)
func GetScale(ctx context.Context, restMapper meta.RESTMapper, scaleClient scale.ScalesGetter, namespace string, ref autoscalingv2.CrossVersionObjectReference) (*autoscalingapiv1.Scale, *meta.RESTMapping, error) {
targetGV, err := schema.ParseGroupVersion(ref.APIVersion)
if err != nil {
return nil, nil, err
}
targetGK := schema.GroupKind{
Group: targetGV.Group,
Kind: ref.Kind,
}
mappings, err := restMapper.RESTMappings(targetGK)
if err != nil {
return nil, nil, err
}
var errs []error
for _, mapping := range mappings {
scale, err := scaleClient.Scales(namespace).Get(ctx, mapping.Resource.GroupResource(), ref.Name, metav1.GetOptions{})
if err == nil {
return scale, mapping, nil
}
errs = append(errs, err)
}
return nil, nil, fmt.Errorf("unrecognized resource: %+v", errs)
}
func GetScaleFromObjectReference(ctx context.Context, restMapper meta.RESTMapper, scaleClient scale.ScalesGetter, ref v1.ObjectReference) (*autoscalingapiv1.Scale, *meta.RESTMapping, error) {
newRef := autoscalingv2.CrossVersionObjectReference{
APIVersion: ref.APIVersion,
Kind: ref.Kind,
Name: ref.Name,
}
return GetScale(ctx, restMapper, scaleClient, ref.Namespace, newRef)
}
func GetPodsFromScale(kubeClient client.Client, scale *autoscalingapiv1.Scale) ([]v1.Pod, error) {
selector, err := labels.ConvertSelectorToLabelsMap(scale.Status.Selector)
if err != nil {
return nil, err
}
opts := []client.ListOption{
client.InNamespace(scale.GetNamespace()),
client.MatchingLabels(selector),
}
podList := &v1.PodList{}
err = kubeClient.List(context.TODO(), podList, opts...)
if err != nil {
return nil, err
}
return podList.Items, nil
}