network.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package scrape
  2. import (
  3. "fmt"
  4. "github.com/opencost/opencost/core/pkg/clustercache"
  5. "github.com/opencost/opencost/core/pkg/log"
  6. "github.com/opencost/opencost/modules/collector-source/pkg/event"
  7. "github.com/opencost/opencost/modules/collector-source/pkg/metric"
  8. "github.com/opencost/opencost/modules/collector-source/pkg/scrape/target"
  9. v1 "k8s.io/api/core/v1"
  10. )
  11. const (
  12. NetworkCostsNameLabel = "network-costs"
  13. NetworkCostsInstanceLabel = "kubecost"
  14. )
  15. func newNetworkScraper(
  16. port int,
  17. clusterCache clustercache.ClusterCache,
  18. ) Scraper {
  19. tp := NewNetworkTargetProvider(port, clusterCache)
  20. return newNetworkTargetScraper(tp)
  21. }
  22. func newNetworkTargetScraper(provider target.TargetProvider) *TargetScraper {
  23. return newTargetScrapper(
  24. event.NetworkCostsScraperName,
  25. provider,
  26. []string{
  27. metric.KubecostPodNetworkEgressBytesTotal,
  28. metric.KubecostPodNetworkIngressBytesTotal,
  29. },
  30. true)
  31. }
  32. type NetworkTargetProvider struct {
  33. port int
  34. clusterCache clustercache.ClusterCache
  35. }
  36. func NewNetworkTargetProvider(port int, clusterCache clustercache.ClusterCache) *NetworkTargetProvider {
  37. return &NetworkTargetProvider{
  38. port: port,
  39. clusterCache: clusterCache,
  40. }
  41. }
  42. func (n *NetworkTargetProvider) GetTargets() []target.ScrapeTarget {
  43. // NOTE: The proper way to discover these targets is to first identify a Service that
  44. // NOTE: matches a specific selector. Then, locate the Endpoints kubernetes resource associated
  45. // NOTE: with that Service. This Endpoints resource has a list of all the targetted pods and their
  46. // NOTE: addresses. We do _not_ have the Endpoints resource on our cluster cache at the moment,
  47. // NOTE: so we'll perform this lookup ourselves.
  48. pods := n.clusterCache.GetAllPods()
  49. var targets []target.ScrapeTarget
  50. for _, pod := range pods {
  51. if pod.Status.Phase == v1.PodRunning && isNetworkCosts(pod.Labels) {
  52. log.Debugf("Network: found target for http://%s:%d/metrics", pod.Status.PodIP, n.port)
  53. t := target.NewUrlTarget(fmt.Sprintf("http://%s:%d/metrics", pod.Status.PodIP, n.port))
  54. targets = append(targets, t)
  55. }
  56. }
  57. return targets
  58. }
  59. func isNetworkCosts(labels map[string]string) bool {
  60. return labels["app.kubernetes.io/name"] == NetworkCostsNameLabel &&
  61. labels["app.kubernetes.io/instance"] == NetworkCostsInstanceLabel
  62. }