service.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package kubemodel
  2. import (
  3. "time"
  4. "github.com/opencost/opencost/core/pkg/log"
  5. "github.com/opencost/opencost/core/pkg/model/kubemodel"
  6. "github.com/opencost/opencost/core/pkg/source"
  7. )
  8. func (km *KubeModel) computeServices(kms *kubemodel.KubeModelSet, start, end time.Time) error {
  9. grp := source.NewQueryGroup()
  10. metrics := km.ds.Metrics()
  11. serviceInfoResultFuture := source.WithGroup(grp, metrics.QueryServiceInfo(start, end))
  12. serviceUptimeResultFuture := source.WithGroup(grp, metrics.QueryServiceUptime(start, end))
  13. serviceSelectorLabelsResultFuture := source.WithGroup(grp, metrics.QueryServiceSelectorLabels(start, end))
  14. serviceMap := make(map[string]*kubemodel.Service)
  15. // Initialize services from info
  16. serviceInfoResult, _ := serviceInfoResultFuture.Await()
  17. for _, res := range serviceInfoResult {
  18. serviceMap[res.UID] = &kubemodel.Service{
  19. UID: res.UID,
  20. NamespaceUID: res.NamespaceUID,
  21. Name: res.Service,
  22. Type: kubemodel.ParseServiceType(res.ServiceType),
  23. LBIngressAddress: res.LBIngressAddress,
  24. }
  25. }
  26. serviceUptimeResult, _ := serviceUptimeResultFuture.Await()
  27. for _, res := range serviceUptimeResult {
  28. service, ok := serviceMap[res.UID]
  29. if !ok {
  30. log.Warnf("service with UID '%s' has not been initialized to add uptime", res.UID)
  31. continue
  32. }
  33. s, e := res.GetStartEnd(start, end, km.ds.Resolution())
  34. service.Start = s
  35. service.End = e
  36. }
  37. serviceSelectorLabelsResult, _ := serviceSelectorLabelsResultFuture.Await()
  38. for _, res := range serviceSelectorLabelsResult {
  39. service, ok := serviceMap[res.UID]
  40. if !ok {
  41. log.Warnf("service with UID '%s' has not been initialized to add selector labels", res.UID)
  42. continue
  43. }
  44. service.Selector = res.Labels
  45. }
  46. for _, service := range serviceMap {
  47. err := kms.RegisterService(service)
  48. if err != nil {
  49. log.Warnf("Failed to register service: %s", err.Error())
  50. }
  51. }
  52. return nil
  53. }