costmodel.go 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  1. package costmodel
  2. import (
  3. "context"
  4. "fmt"
  5. "net/http"
  6. "net/http/pprof"
  7. "time"
  8. "github.com/julienschmidt/httprouter"
  9. "github.com/opencost/opencost/pkg/cloudcost"
  10. "github.com/prometheus/client_golang/prometheus/promhttp"
  11. "github.com/rs/cors"
  12. "github.com/opencost/opencost/core/pkg/log"
  13. "github.com/opencost/opencost/core/pkg/version"
  14. "github.com/opencost/opencost/pkg/costmodel"
  15. "github.com/opencost/opencost/pkg/env"
  16. "github.com/opencost/opencost/pkg/errors"
  17. "github.com/opencost/opencost/pkg/filemanager"
  18. "github.com/opencost/opencost/pkg/metrics"
  19. )
  20. // CostModelOpts contain configuration options that can be passed to the Execute() method
  21. type CostModelOpts struct {
  22. // Stubbed for future configuration
  23. }
  24. func Healthz(w http.ResponseWriter, _ *http.Request, _ httprouter.Params) {
  25. w.WriteHeader(200)
  26. w.Header().Set("Content-Length", "0")
  27. w.Header().Set("Content-Type", "text/plain")
  28. }
  29. func Execute(opts *CostModelOpts) error {
  30. log.Infof("Starting cost-model version %s", version.FriendlyVersion())
  31. log.Infof("Kubernetes enabled: %t", env.IsKubernetesEnabled())
  32. var a *costmodel.Accesses
  33. if env.IsKubernetesEnabled() {
  34. a = costmodel.Initialize()
  35. err := StartExportWorker(context.Background(), a.Model)
  36. if err != nil {
  37. log.Errorf("couldn't start CSV export worker: %v", err)
  38. }
  39. } else {
  40. a = costmodel.InitializeWithoutKubernetes()
  41. log.Debugf("Cloud Cost config path: %s", env.GetCloudCostConfigPath())
  42. }
  43. log.Infof("Cloud Costs enabled: %t", env.IsCloudCostEnabled())
  44. if env.IsCloudCostEnabled() {
  45. repo := cloudcost.NewMemoryRepository()
  46. a.CloudCostPipelineService = cloudcost.NewPipelineService(repo, a.CloudConfigController, cloudcost.DefaultIngestorConfiguration())
  47. repoQuerier := cloudcost.NewRepositoryQuerier(repo)
  48. a.CloudCostQueryService = cloudcost.NewQueryService(repoQuerier, repoQuerier)
  49. }
  50. rootMux := http.NewServeMux()
  51. a.Router.GET("/healthz", Healthz)
  52. if env.IsKubernetesEnabled() {
  53. a.Router.GET("/allocation", a.ComputeAllocationHandler)
  54. a.Router.GET("/allocation/summary", a.ComputeAllocationHandlerSummary)
  55. a.Router.GET("/assets", a.ComputeAssetsHandler)
  56. }
  57. a.Router.GET("/cloudCost", a.CloudCostQueryService.GetCloudCostHandler())
  58. a.Router.GET("/cloudCost/view/graph", a.CloudCostQueryService.GetCloudCostViewGraphHandler())
  59. a.Router.GET("/cloudCost/view/totals", a.CloudCostQueryService.GetCloudCostViewTotalsHandler())
  60. a.Router.GET("/cloudCost/view/table", a.CloudCostQueryService.GetCloudCostViewTableHandler())
  61. a.Router.GET("/cloudCost/status", a.CloudCostPipelineService.GetCloudCostStatusHandler())
  62. a.Router.GET("/cloudCost/rebuild", a.CloudCostPipelineService.GetCloudCostRebuildHandler())
  63. a.Router.GET("/cloudCost/repair", a.CloudCostPipelineService.GetCloudCostRepairHandler())
  64. if env.IsPProfEnabled() {
  65. a.Router.HandlerFunc(http.MethodGet, "/debug/pprof/", pprof.Index)
  66. a.Router.HandlerFunc(http.MethodGet, "/debug/pprof/cmdline", pprof.Cmdline)
  67. a.Router.HandlerFunc(http.MethodGet, "/debug/pprof/profile", pprof.Profile)
  68. a.Router.HandlerFunc(http.MethodGet, "/debug/pprof/symbol", pprof.Symbol)
  69. a.Router.HandlerFunc(http.MethodGet, "/debug/pprof/trace", pprof.Trace)
  70. a.Router.Handler(http.MethodGet, "/debug/pprof/goroutine", pprof.Handler("goroutine"))
  71. a.Router.Handler(http.MethodGet, "/debug/pprof/heap", pprof.Handler("heap"))
  72. }
  73. rootMux.Handle("/", a.Router)
  74. rootMux.Handle("/metrics", promhttp.Handler())
  75. telemetryHandler := metrics.ResponseMetricMiddleware(rootMux)
  76. handler := cors.AllowAll().Handler(telemetryHandler)
  77. return http.ListenAndServe(fmt.Sprint(":", env.GetAPIPort()), errors.PanicHandlerMiddleware(handler))
  78. }
  79. func StartExportWorker(ctx context.Context, model costmodel.AllocationModel) error {
  80. exportPath := env.GetExportCSVFile()
  81. if exportPath == "" {
  82. log.Infof("%s is not set, CSV export is disabled", env.ExportCSVFile)
  83. return nil
  84. }
  85. fm, err := filemanager.NewFileManager(exportPath)
  86. if err != nil {
  87. return fmt.Errorf("could not create file manager: %v", err)
  88. }
  89. go func() {
  90. log.Info("Starting CSV exporter worker...")
  91. // perform first update immediately
  92. nextRunAt := time.Now()
  93. for {
  94. select {
  95. case <-ctx.Done():
  96. return
  97. case <-time.After(nextRunAt.Sub(time.Now())):
  98. err := costmodel.UpdateCSV(ctx, fm, model, env.GetExportCSVLabelsAll(), env.GetExportCSVLabelsList())
  99. if err != nil {
  100. // it's background worker, log error and carry on, maybe next time it will work
  101. log.Errorf("Error updating CSV: %s", err)
  102. }
  103. now := time.Now().UTC()
  104. // next launch is at 00:10 UTC tomorrow
  105. // extra 10 minutes is to let prometheus to collect all the data for the previous day
  106. nextRunAt = time.Date(now.Year(), now.Month(), now.Day(), 0, 10, 0, 0, now.Location()).AddDate(0, 0, 1)
  107. }
  108. }
  109. }()
  110. return nil
  111. }