costmodel.go 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  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. a := costmodel.Initialize()
  32. err := StartExportWorker(context.Background(), a.Model)
  33. if err != nil {
  34. log.Errorf("couldn't start CSV export worker: %v", err)
  35. }
  36. if env.IsCloudCostEnabled() {
  37. repo := cloudcost.NewMemoryRepository()
  38. a.CloudCostPipelineService = cloudcost.NewPipelineService(repo, a.CloudConfigController, cloudcost.DefaultIngestorConfiguration())
  39. repoQuerier := cloudcost.NewRepositoryQuerier(repo)
  40. a.CloudCostQueryService = cloudcost.NewQueryService(repoQuerier, repoQuerier)
  41. }
  42. rootMux := http.NewServeMux()
  43. a.Router.GET("/healthz", Healthz)
  44. a.Router.GET("/allocation", a.ComputeAllocationHandler)
  45. a.Router.GET("/allocation/summary", a.ComputeAllocationHandlerSummary)
  46. a.Router.GET("/assets", a.ComputeAssetsHandler)
  47. a.Router.GET("/cloudCost", a.CloudCostQueryService.GetCloudCostHandler())
  48. a.Router.GET("/cloudCost/view/graph", a.CloudCostQueryService.GetCloudCostViewGraphHandler())
  49. a.Router.GET("/cloudCost/view/totals", a.CloudCostQueryService.GetCloudCostViewTotalsHandler())
  50. a.Router.GET("/cloudCost/view/table", a.CloudCostQueryService.GetCloudCostViewTableHandler())
  51. a.Router.GET("/cloudCost/status", a.CloudCostPipelineService.GetCloudCostStatusHandler())
  52. a.Router.GET("/cloudCost/rebuild", a.CloudCostPipelineService.GetCloudCostRebuildHandler())
  53. a.Router.GET("/cloudCost/repair", a.CloudCostPipelineService.GetCloudCostRepairHandler())
  54. if env.IsPProfEnabled() {
  55. a.Router.HandlerFunc(http.MethodGet, "/debug/pprof/", pprof.Index)
  56. a.Router.HandlerFunc(http.MethodGet, "/debug/pprof/cmdline", pprof.Cmdline)
  57. a.Router.HandlerFunc(http.MethodGet, "/debug/pprof/profile", pprof.Profile)
  58. a.Router.HandlerFunc(http.MethodGet, "/debug/pprof/symbol", pprof.Symbol)
  59. a.Router.HandlerFunc(http.MethodGet, "/debug/pprof/trace", pprof.Trace)
  60. a.Router.Handler(http.MethodGet, "/debug/pprof/goroutine", pprof.Handler("goroutine"))
  61. a.Router.Handler(http.MethodGet, "/debug/pprof/heap", pprof.Handler("heap"))
  62. }
  63. rootMux.Handle("/", a.Router)
  64. rootMux.Handle("/metrics", promhttp.Handler())
  65. telemetryHandler := metrics.ResponseMetricMiddleware(rootMux)
  66. handler := cors.AllowAll().Handler(telemetryHandler)
  67. return http.ListenAndServe(fmt.Sprint(":", env.GetAPIPort()), errors.PanicHandlerMiddleware(handler))
  68. }
  69. func StartExportWorker(ctx context.Context, model costmodel.AllocationModel) error {
  70. exportPath := env.GetExportCSVFile()
  71. if exportPath == "" {
  72. log.Infof("%s is not set, CSV export is disabled", env.ExportCSVFile)
  73. return nil
  74. }
  75. fm, err := filemanager.NewFileManager(exportPath)
  76. if err != nil {
  77. return fmt.Errorf("could not create file manager: %v", err)
  78. }
  79. go func() {
  80. log.Info("Starting CSV exporter worker...")
  81. // perform first update immediately
  82. nextRunAt := time.Now()
  83. for {
  84. select {
  85. case <-ctx.Done():
  86. return
  87. case <-time.After(nextRunAt.Sub(time.Now())):
  88. err := costmodel.UpdateCSV(ctx, fm, model, env.GetExportCSVLabelsAll(), env.GetExportCSVLabelsList())
  89. if err != nil {
  90. // it's background worker, log error and carry on, maybe next time it will work
  91. log.Errorf("Error updating CSV: %s", err)
  92. }
  93. now := time.Now().UTC()
  94. // next launch is at 00:10 UTC tomorrow
  95. // extra 10 minutes is to let prometheus to collect all the data for the previous day
  96. nextRunAt = time.Date(now.Year(), now.Month(), now.Day(), 0, 10, 0, 0, now.Location()).AddDate(0, 0, 1)
  97. }
  98. }
  99. }()
  100. return nil
  101. }