scrape: add Target.LabelsRange

This allows users of a Target to iterate labels without allocating heap memory.

Signed-off-by: Bryan Boreham <bjboreham@gmail.com>
This commit is contained in:
Bryan Boreham 2023-03-07 17:10:15 +00:00
parent a494c44746
commit 2fde2fb37d
2 changed files with 20 additions and 0 deletions

View file

@ -181,6 +181,15 @@ func (t *Target) Labels() labels.Labels {
return b.Labels()
}
// LabelsRange calls f on each public label of the target.
func (t *Target) LabelsRange(f func(l labels.Label)) {
t.labels.Range(func(l labels.Label) {
if !strings.HasPrefix(l.Name, model.ReservedLabelPrefix) {
f(l)
}
})
}
// DiscoveredLabels returns a copy of the target's labels before any processing.
func (t *Target) DiscoveredLabels() labels.Labels {
t.mtx.Lock()

View file

@ -43,6 +43,17 @@ func TestTargetLabels(t *testing.T) {
want := labels.FromStrings(model.JobLabel, "some_job", "foo", "bar")
got := target.Labels()
require.Equal(t, want, got)
i := 0
target.LabelsRange(func(l labels.Label) {
switch i {
case 0:
require.Equal(t, labels.Label{Name: "foo", Value: "bar"}, l)
case 1:
require.Equal(t, labels.Label{Name: model.JobLabel, Value: "some_job"}, l)
}
i++
})
require.Equal(t, 2, i)
}
func TestTargetOffset(t *testing.T) {