From 77896ca6a18341da1416c6d56feae9e459c00202 Mon Sep 17 00:00:00 2001 From: johncming Date: Fri, 13 Dec 2019 14:17:55 +0800 Subject: [PATCH] deduplicate addresses. Signed-off-by: johncming --- pkg/discovery/cache/cache.go | 13 +++++++++-- pkg/discovery/cache/cache_test.go | 39 +++++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+), 2 deletions(-) create mode 100644 pkg/discovery/cache/cache_test.go diff --git a/pkg/discovery/cache/cache.go b/pkg/discovery/cache/cache.go index 22b5feb5ea..c619eaa793 100644 --- a/pkg/discovery/cache/cache.go +++ b/pkg/discovery/cache/cache.go @@ -38,12 +38,21 @@ func (c *Cache) Update(tgs []*targetgroup.Group) { // Addresses returns all the addresses from all target groups present in the Cache. func (c *Cache) Addresses() []string { + var addresses []string + var unique map[string]struct{} + c.Lock() defer c.Unlock() - var addresses []string + + unique = make(map[string]struct{}) for _, group := range c.tgs { for _, target := range group.Targets { - addresses = append(addresses, string(target[model.AddressLabel])) + addr := string(target[model.AddressLabel]) + if _, ok := unique[addr]; ok { + continue + } + addresses = append(addresses, addr) + unique[addr] = struct{}{} } } return addresses diff --git a/pkg/discovery/cache/cache_test.go b/pkg/discovery/cache/cache_test.go new file mode 100644 index 0000000000..cd40de760a --- /dev/null +++ b/pkg/discovery/cache/cache_test.go @@ -0,0 +1,39 @@ +package cache + +import ( + "reflect" + "testing" + + "github.com/prometheus/common/model" + "github.com/prometheus/prometheus/discovery/targetgroup" +) + +func TestCacheAddresses(t *testing.T) { + tgs := make(map[string]*targetgroup.Group) + tgs["g1"] = &targetgroup.Group{ + Targets: []model.LabelSet{ + model.LabelSet{model.AddressLabel: "localhost:9090"}, + model.LabelSet{model.AddressLabel: "localhost:9091"}, + model.LabelSet{model.AddressLabel: "localhost:9092"}, + }, + } + tgs["g2"] = &targetgroup.Group{ + Targets: []model.LabelSet{ + model.LabelSet{model.AddressLabel: "localhost:9091"}, + model.LabelSet{model.AddressLabel: "localhost:9092"}, + model.LabelSet{model.AddressLabel: "localhost:9093"}, + }, + } + + c := &Cache{tgs: tgs} + + expected := []string{ + "localhost:9090", + "localhost:9091", + "localhost:9092", + "localhost:9093", + } + if got := c.Addresses(); !reflect.DeepEqual(got, expected) { + t.Errorf("expected %v, want %v", got, expected) + } +}