network.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. nil)
  32. }
  33. type NetworkTargetProvider struct {
  34. port int
  35. clusterCache clustercache.ClusterCache
  36. }
  37. func NewNetworkTargetProvider(port int, clusterCache clustercache.ClusterCache) *NetworkTargetProvider {
  38. return &NetworkTargetProvider{
  39. port: port,
  40. clusterCache: clusterCache,
  41. }
  42. }
  43. func (n *NetworkTargetProvider) GetTargets() []target.ScrapeTarget {
  44. // NOTE: The proper way to discover these targets is to first identify a Service that
  45. // NOTE: matches a specific selector. Then, locate the Endpoints kubernetes resource associated
  46. // NOTE: with that Service. This Endpoints resource has a list of all the targetted pods and their
  47. // NOTE: addresses. We do _not_ have the Endpoints resource on our cluster cache at the moment,
  48. // NOTE: so we'll perform this lookup ourselves.
  49. pods := n.clusterCache.GetAllPods()
  50. var targets []target.ScrapeTarget
  51. for _, pod := range pods {
  52. if pod.Status.Phase == v1.PodRunning && isNetworkCosts(pod.Labels) {
  53. log.Debugf("Network: found target for http://%s:%d/metrics", pod.Status.PodIP, n.port)
  54. t := target.NewUrlTarget(fmt.Sprintf("http://%s:%d/metrics", pod.Status.PodIP, n.port))
  55. targets = append(targets, t)
  56. }
  57. }
  58. return targets
  59. }
  60. func isNetworkCosts(labels map[string]string) bool {
  61. return labels["app.kubernetes.io/name"] == NetworkCostsNameLabel &&
  62. labels["app.kubernetes.io/instance"] == NetworkCostsInstanceLabel
  63. }