github.com/thanos-io/thanos@v0.32.5/pkg/discovery/cache/cache.go (about) 1 // Copyright (c) The Thanos Authors. 2 // Licensed under the Apache License 2.0. 3 4 package cache 5 6 import ( 7 "sync" 8 9 "github.com/prometheus/common/model" 10 "github.com/prometheus/prometheus/discovery/targetgroup" 11 ) 12 13 // Cache is a store for target groups. It provides thread safe updates and a way for obtaining all addresses from 14 // the stored target groups. 15 type Cache struct { 16 tgs map[string]*targetgroup.Group 17 sync.Mutex 18 } 19 20 // New returns a new empty Cache. 21 func New() *Cache { 22 return &Cache{ 23 tgs: make(map[string]*targetgroup.Group), 24 } 25 } 26 27 // Update stores the targets for the given groups. 28 // Note: targets for a group are replaced entirely on update. If a group with no target is given this is equivalent to 29 // deleting all the targets for this group. 30 func (c *Cache) Update(tgs []*targetgroup.Group) { 31 c.Lock() 32 defer c.Unlock() 33 for _, tg := range tgs { 34 // Some Discoverers send nil target group so need to check for it to avoid panics. 35 if tg == nil { 36 continue 37 } 38 c.tgs[tg.Source] = tg 39 } 40 } 41 42 // Addresses returns all the addresses from all target groups present in the Cache. 43 func (c *Cache) Addresses() []string { 44 var addresses []string 45 var unique map[string]struct{} 46 47 c.Lock() 48 defer c.Unlock() 49 50 unique = make(map[string]struct{}) 51 for _, group := range c.tgs { 52 for _, target := range group.Targets { 53 addr := string(target[model.AddressLabel]) 54 if _, ok := unique[addr]; ok { 55 continue 56 } 57 addresses = append(addresses, addr) 58 unique[addr] = struct{}{} 59 } 60 } 61 return addresses 62 }