@@ -219,39 +219,22 @@ func (p *PodMetricsClientImpl) getMetric(logger logr.Logger, metricFamilies map[
219
219
if len (mf .GetMetric ()) == 0 {
220
220
return nil , fmt .Errorf ("no metrics available for %q" , spec .MetricName )
221
221
}
222
- // if there is a specified label, return only that metric in the family
223
- if spec .Labels != nil {
224
- return getLabeledMetric (logger , mf , & spec )
225
- }
226
- return getLatestMetric (logger , mf )
227
- }
228
222
229
- // getLatestMetric gets the latest metric of a family (for metrics without labels).
230
- func getLatestMetric (logger logr.Logger , mf * dto.MetricFamily ) (* dto.Metric , error ) {
231
- var latestTs int64 = - 1
232
- var latest * dto.Metric
233
- for _ , m := range mf .GetMetric () {
234
- if m .GetTimestampMs () >= latestTs {
235
- latestTs = m .GetTimestampMs ()
236
- latest = m
237
- }
238
- }
239
-
240
- if latest == nil {
241
- return nil , fmt .Errorf ("no metrics found for %q" , mf .GetName ())
242
- }
243
-
244
- logger .V (logutil .TRACE ).Info ("Latest metric value selected" , "value" , latest , "metric" , mf .GetName ())
245
- return latest , nil
223
+ return getLatestMetric (logger , mf , & spec )
246
224
}
247
225
248
226
// getLabeledMetric gets the latest metric with matching labels.
249
- func getLabeledMetric (logger logr.Logger , mf * dto.MetricFamily , spec * MetricSpec ) (* dto.Metric , error ) {
227
+ func getLatestMetric (logger logr.Logger , mf * dto.MetricFamily , spec * MetricSpec ) (* dto.Metric , error ) {
250
228
var latestMetric * dto.Metric
251
229
var latestTimestamp int64 = - 1 // Initialize to -1 so any timestamp is greater
252
230
231
+ var labels map [string ]string = nil
232
+ if spec .Labels != nil {
233
+ labels = spec .Labels
234
+ }
235
+
253
236
for _ , m := range mf .GetMetric () {
254
- if spec == nil || labelsMatch (m .GetLabel (), spec .Labels ) {
237
+ if labels == nil || labelsMatch (m .GetLabel (), spec .Labels ) {
255
238
if m .GetTimestampMs () > latestTimestamp {
256
239
latestTimestamp = m .GetTimestampMs ()
257
240
latestMetric = m
@@ -260,11 +243,11 @@ func getLabeledMetric(logger logr.Logger, mf *dto.MetricFamily, spec *MetricSpec
260
243
}
261
244
262
245
if latestMetric != nil {
263
- logger .V (logutil .TRACE ).Info ("Labeled metric found" , "value" , latestMetric , "metric " , spec .MetricName )
246
+ logger .V (logutil .TRACE ).Info ("Labeled metric found" , "value" , latestMetric , "name " , spec .MetricName )
264
247
return latestMetric , nil
265
248
}
266
249
267
- return nil , fmt .Errorf ("no matching labeled metric found for %q with labels %v" , spec .MetricName , spec . Labels )
250
+ return nil , fmt .Errorf ("no matching metric found for %q with labels %+ v" , spec .MetricName , labels )
268
251
}
269
252
270
253
// labelsMatch checks if a metric's labels contain all the labels in the spec.
0 commit comments