Skip to content

Commit

Permalink
Merge pull request #12474 from monstermunchkin/fixes/metrics
Browse files Browse the repository at this point in the history
metrics: Fix label merging in metric sets
  • Loading branch information
tomponline authored Nov 2, 2023
2 parents 9640381 + d251ead commit e57a070
Show file tree
Hide file tree
Showing 4 changed files with 35 additions and 4 deletions.
2 changes: 1 addition & 1 deletion lxd/instance/drivers/driver_lxc.go
Original file line number Diff line number Diff line change
Expand Up @@ -8509,7 +8509,7 @@ func (d *lxc) getFSStats() (*metrics.MetricSet, error) {
FSType string
}

out := metrics.NewMetricSet(map[string]string{"project": d.project.Name, "name": d.name})
out := metrics.NewMetricSet(nil)

mounts, err := os.ReadFile("/proc/mounts")
if err != nil {
Expand Down
16 changes: 13 additions & 3 deletions lxd/metrics/metrics.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,14 +61,24 @@ func (m *MetricSet) AddSamples(metricType MetricType, samples ...Sample) {
m.set[metricType] = append(m.set[metricType], samples...)
}

// Merge merges two MetricSets.
// Merge merges two MetricSets. Missing labels from m's samples are added to all samples in n.
func (m *MetricSet) Merge(metricSet *MetricSet) {
if metricSet == nil {
return
}

for k := range metricSet.set {
m.set[k] = append(m.set[k], metricSet.set[k]...)
for metricType := range metricSet.set {
for _, sample := range metricSet.set[metricType] {
// Add missing labels from m.
for k, v := range m.labels {
_, ok := sample.Labels[k]
if !ok {
sample.Labels[k] = v
}
}

m.set[metricType] = append(m.set[metricType], sample)
}
}
}

Expand Down
18 changes: 18 additions & 0 deletions lxd/metrics/metrics_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,4 +37,22 @@ func TestMetricSet_FilterSamples(t *testing.T) {

// Should no longer contain the sample.
require.Equal(t, []Sample{}, m.set[CPUSecondsTotal])

m = NewMetricSet(map[string]string{"project": "default"})
m.AddSamples(CPUSecondsTotal, Sample{Value: 10})

n := NewMetricSet(map[string]string{"name": "jammy"})
n.AddSamples(CPUSecondsTotal, Sample{Value: 20})

m.Merge(n)

for _, sample := range m.set[CPUSecondsTotal] {
hasKeys := []string{}

for k := range sample.Labels {
hasKeys = append(hasKeys, k)
}

require.Contains(t, hasKeys, "project")
}
}
3 changes: 3 additions & 0 deletions test/suites/metrics.sh
Original file line number Diff line number Diff line change
Expand Up @@ -49,5 +49,8 @@ test_metrics() {
lxc config set core.metrics_authentication=false
curl -k -s -X GET "https://${metrics_addr}/1.0/metrics" | grep "name=\"c1\""

# Filesystem metrics should contain instance type
curl -k -s -X GET "https://${metrics_addr}/1.0/metrics" | grep "lxd_filesystem_avail_bytes" | grep "type=\"container\""

lxc delete -f c1 c2
}

0 comments on commit e57a070

Please sign in to comment.