Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

deduplicate addresses. #1887

Merged
merged 1 commit into from
Dec 14, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 11 additions & 2 deletions pkg/discovery/cache/cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -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{})
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do you mind adding test case for it? (:

Copy link
Contributor Author

@johncming johncming Dec 14, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ok. fixed. @bwplotka

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
Expand Down
39 changes: 39 additions & 0 deletions pkg/discovery/cache/cache_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}