-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
metadata.go
226 lines (195 loc) · 7.22 KB
/
metadata.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
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package kubelet // import "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/kubeletstatsreceiver/internal/kubelet"
import (
"errors"
"fmt"
"regexp"
"strings"
conventions "go.opentelemetry.io/collector/semconv/v1.6.1"
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/types"
stats "k8s.io/kubelet/pkg/apis/stats/v1alpha1"
"github.com/open-telemetry/opentelemetry-collector-contrib/receiver/kubeletstatsreceiver/internal/metadata"
)
type MetadataLabel string
// Values for MetadataLabel enum.
const (
MetadataLabelContainerID MetadataLabel = conventions.AttributeContainerID
MetadataLabelVolumeType MetadataLabel = labelVolumeType
)
var supportedLabels = map[MetadataLabel]bool{
MetadataLabelContainerID: true,
MetadataLabelVolumeType: true,
}
// ValidateMetadataLabelsConfig validates that provided list of metadata labels is supported
func ValidateMetadataLabelsConfig(labels []MetadataLabel) error {
labelsFound := map[MetadataLabel]bool{}
for _, label := range labels {
if _, supported := supportedLabels[label]; supported {
if _, duplicate := labelsFound[label]; duplicate {
return fmt.Errorf("duplicate metadata label: %q", label)
}
labelsFound[label] = true
} else {
return fmt.Errorf("label %q is not supported", label)
}
}
return nil
}
type Metadata struct {
Labels map[MetadataLabel]bool
PodsMetadata *v1.PodList
DetailedPVCResourceSetter func(rb *metadata.ResourceBuilder, volCacheID, volumeClaim, namespace string) error
podResources map[string]resources
containerResources map[string]resources
}
type resources struct {
cpuRequest float64
cpuLimit float64
memoryRequest int64
memoryLimit int64
}
func getContainerResources(r *v1.ResourceRequirements) resources {
if r == nil {
return resources{}
}
return resources{
cpuRequest: r.Requests.Cpu().AsApproximateFloat64(),
cpuLimit: r.Limits.Cpu().AsApproximateFloat64(),
memoryRequest: r.Requests.Memory().Value(),
memoryLimit: r.Limits.Memory().Value(),
}
}
func NewMetadata(labels []MetadataLabel, podsMetadata *v1.PodList,
detailedPVCResourceSetter func(rb *metadata.ResourceBuilder, volCacheID, volumeClaim, namespace string) error) Metadata {
m := Metadata{
Labels: getLabelsMap(labels),
PodsMetadata: podsMetadata,
DetailedPVCResourceSetter: detailedPVCResourceSetter,
podResources: make(map[string]resources, 0),
containerResources: make(map[string]resources, 0),
}
if podsMetadata != nil {
for _, pod := range podsMetadata.Items {
var podResource resources
allContainersCPULimitsDefined := true
allContainersCPURequestsDefined := true
allContainersMemoryLimitsDefined := true
allContainersMemoryRequestsDefined := true
for i := range pod.Spec.Containers {
container := pod.Spec.Containers[i]
containerResource := getContainerResources(&container.Resources)
if allContainersCPULimitsDefined && containerResource.cpuLimit == 0 {
allContainersCPULimitsDefined = false
podResource.cpuLimit = 0
}
if allContainersCPURequestsDefined && containerResource.cpuRequest == 0 {
allContainersCPURequestsDefined = false
podResource.cpuRequest = 0
}
if allContainersMemoryLimitsDefined && containerResource.memoryLimit == 0 {
allContainersMemoryLimitsDefined = false
podResource.memoryLimit = 0
}
if allContainersMemoryRequestsDefined && containerResource.memoryRequest == 0 {
allContainersMemoryRequestsDefined = false
podResource.memoryRequest = 0
}
if allContainersCPULimitsDefined {
podResource.cpuLimit += containerResource.cpuLimit
}
if allContainersCPURequestsDefined {
podResource.cpuRequest += containerResource.cpuRequest
}
if allContainersMemoryLimitsDefined {
podResource.memoryLimit += containerResource.memoryLimit
}
if allContainersMemoryRequestsDefined {
podResource.memoryRequest += containerResource.memoryRequest
}
m.containerResources[string(pod.UID)+container.Name] = containerResource
}
m.podResources[string(pod.UID)] = podResource
}
}
return m
}
func getLabelsMap(metadataLabels []MetadataLabel) map[MetadataLabel]bool {
out := make(map[MetadataLabel]bool, len(metadataLabels))
for _, l := range metadataLabels {
out[l] = true
}
return out
}
// getExtraResources gets extra resources based on provided metadata label.
func (m *Metadata) setExtraResources(rb *metadata.ResourceBuilder, podRef stats.PodReference,
extraMetadataLabel MetadataLabel, extraMetadataFrom string) error {
// Ensure MetadataLabel exists before proceeding.
if !m.Labels[extraMetadataLabel] || len(m.Labels) == 0 {
return nil
}
// Cannot proceed, if metadata is unavailable.
if m.PodsMetadata == nil {
return errors.New("pods metadata were not fetched")
}
switch extraMetadataLabel {
case MetadataLabelContainerID:
containerID, err := m.getContainerID(podRef.UID, extraMetadataFrom)
if err != nil {
return err
}
rb.SetContainerID(containerID)
case MetadataLabelVolumeType:
volume, err := m.getPodVolume(podRef.UID, extraMetadataFrom)
if err != nil {
return err
}
setResourcesFromVolume(rb, volume)
// Get more labels from PersistentVolumeClaim volume type.
if volume.PersistentVolumeClaim != nil {
volCacheID := fmt.Sprintf("%s/%s", podRef.UID, extraMetadataFrom)
err := m.DetailedPVCResourceSetter(rb, volCacheID, volume.PersistentVolumeClaim.ClaimName, podRef.Namespace)
if err != nil {
return fmt.Errorf("failed to set labels from volume claim: %w", err)
}
}
}
return nil
}
// getContainerID retrieves container id from metadata for given pod UID and container name,
// returns an error if no container found in the metadata that matches the requirements
// or if the apiServer returned a newly created container with empty containerID.
func (m *Metadata) getContainerID(podUID string, containerName string) (string, error) {
uid := types.UID(podUID)
for _, pod := range m.PodsMetadata.Items {
if pod.UID == uid {
for _, containerStatus := range append(pod.Status.ContainerStatuses, pod.Status.InitContainerStatuses...) {
if containerName == containerStatus.Name {
if len(strings.TrimSpace(containerStatus.ContainerID)) == 0 {
return "", fmt.Errorf("pod %q with container %q has an empty containerID", podUID, containerName)
}
return stripContainerID(containerStatus.ContainerID), nil
}
}
}
}
return "", fmt.Errorf("pod %q with container %q not found in the fetched metadata", podUID, containerName)
}
var containerSchemeRegexp = regexp.MustCompile(`^[\w_-]+://`)
// stripContainerID returns a pure container id without the runtime scheme://
func stripContainerID(id string) string {
return containerSchemeRegexp.ReplaceAllString(id, "")
}
func (m *Metadata) getPodVolume(podUID string, volumeName string) (v1.Volume, error) {
for _, pod := range m.PodsMetadata.Items {
if pod.UID == types.UID(podUID) {
for _, volume := range pod.Spec.Volumes {
if volumeName == volume.Name {
return volume, nil
}
}
}
}
return v1.Volume{}, fmt.Errorf("pod %q with volume %q not found in the fetched metadata", podUID, volumeName)
}