-
Notifications
You must be signed in to change notification settings - Fork 672
/
metrics.go
83 lines (70 loc) · 2.05 KB
/
metrics.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
// Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package tests
import (
"context"
"fmt"
"github.com/prometheus/client_golang/prometheus"
"github.com/ava-labs/avalanchego/api/metrics"
dto "github.com/prometheus/client_model/go"
)
// "metric name" -> "metric value"
type NodeMetrics map[string]*dto.MetricFamily
// URI -> "metric name" -> "metric value"
type NodesMetrics map[string]NodeMetrics
// GetNodeMetrics retrieves the specified metrics the provided node URI.
func GetNodeMetrics(ctx context.Context, nodeURI string) (NodeMetrics, error) {
client := metrics.NewClient(nodeURI)
return client.GetMetrics(ctx)
}
// GetNodesMetrics retrieves the specified metrics for the provided node URIs.
func GetNodesMetrics(ctx context.Context, nodeURIs []string) (NodesMetrics, error) {
metrics := make(NodesMetrics, len(nodeURIs))
for _, u := range nodeURIs {
var err error
metrics[u], err = GetNodeMetrics(ctx, u)
if err != nil {
return nil, fmt.Errorf("failed to retrieve metrics for %s: %w", u, err)
}
}
return metrics, nil
}
// GetMetricValue returns the value of the specified metric which has the
// required labels.
//
// If multiple metrics match the provided labels, the first metric found is
// returned.
//
// Only Counter and Gauge metrics are supported.
func GetMetricValue(metrics NodeMetrics, name string, labels prometheus.Labels) (float64, bool) {
metricFamily, ok := metrics[name]
if !ok {
return 0, false
}
for _, metric := range metricFamily.Metric {
if !labelsMatch(metric, labels) {
continue
}
switch {
case metric.Gauge != nil:
return metric.Gauge.GetValue(), true
case metric.Counter != nil:
return metric.Counter.GetValue(), true
}
}
return 0, false
}
func labelsMatch(metric *dto.Metric, labels prometheus.Labels) bool {
var found int
for _, label := range metric.Label {
expectedValue, ok := labels[label.GetName()]
if !ok {
continue
}
if label.GetValue() != expectedValue {
return false
}
found++
}
return found == len(labels)
}