-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathdiscover.go
76 lines (62 loc) · 1.97 KB
/
discover.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
// Unless explicitly stated otherwise all files in this repository are licensed
// under the Apache License Version 2.0.
// This product includes software developed at Datadog (https://www.datadoghq.com/).
// Copyright 2016-present Datadog, Inc.
//nolint:revive // TODO(CINT) Fix revive linter
package autoscalers
import (
"fmt"
"github.com/DataDog/datadog-agent/pkg/util/log"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/client-go/discovery"
"k8s.io/client-go/kubernetes"
)
const (
autoscalingGroup = "autoscaling"
hpaResource = "horizontalpodautoscalers"
)
var preferredHPAVersions = map[string]int{
"v2": 3,
"v2beta2": 2,
"v2beta1": 1,
}
// DiscoverHPAGroupVersionResource returns the HPA GroupVersionResource available.
func DiscoverHPAGroupVersionResource(client kubernetes.Interface) (schema.GroupVersionResource, error) {
groups, _, err := client.Discovery().ServerGroupsAndResources()
if err != nil {
if !discovery.IsGroupDiscoveryFailedError(err) {
return schema.GroupVersionResource{}, err
}
for group, apiGroupErr := range err.(*discovery.ErrGroupDiscoveryFailed).Groups {
log.Warnf("unable to perform resource discovery for group %s: %s", group, apiGroupErr)
}
}
for _, group := range groups {
if group.Name != autoscalingGroup {
continue
}
var (
chosenVersion string
chosenVersionWeight int
)
for _, version := range group.Versions {
weight, ok := preferredHPAVersions[version.Version]
if !ok {
continue
}
if weight > chosenVersionWeight {
chosenVersion = version.Version
chosenVersionWeight = weight
}
}
if chosenVersion == "" {
return schema.GroupVersionResource{}, fmt.Errorf("cannot find supported HPA version. available versions: %v", group.Versions)
}
return schema.GroupVersionResource{
Group: autoscalingGroup,
Version: chosenVersion,
Resource: hpaResource,
}, nil
}
return schema.GroupVersionResource{}, fmt.Errorf("cannot find group %q", autoscalingGroup)
}