nodelabelprovider.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. package external
  2. import (
  3. "maps"
  4. "sync"
  5. "github.com/opencost/opencost/core/pkg/log"
  6. )
  7. // NodeLabelProvider maintains a key/value map of external labels sourced from any
  8. // watcher function. It is intended to be wired up to a WatchFunc such as ConfigMapWatcher
  9. // the caller is responsible for registering it.
  10. type NodeLabelProvider struct {
  11. mu sync.RWMutex
  12. labels map[string]string
  13. }
  14. // NewNodeLabelProvider creates a NodeLabelProvider with an empty label cache.
  15. func NewNodeLabelProvider() *NodeLabelProvider {
  16. return &NodeLabelProvider{
  17. labels: make(map[string]string),
  18. }
  19. }
  20. // Update replaces the cached labels with the full contents of any source of data.
  21. func (nlp *NodeLabelProvider) Update(name string, data map[string]string) error {
  22. nlp.mu.Lock()
  23. defer nlp.mu.Unlock()
  24. // Clone to avoid retaining a reference to a map that may be mutated by the caller.
  25. nlp.labels = maps.Clone(data)
  26. log.Debugf("External: NodeLabelProvider: updated %d label(s) %s", len(data), name)
  27. return nil
  28. }
  29. // Labels returns a copy of the currently cached external labels.
  30. func (nlp *NodeLabelProvider) Labels() (map[string]string, error) {
  31. nlp.mu.RLock()
  32. defer nlp.mu.RUnlock()
  33. return maps.Clone(nlp.labels), nil
  34. }