costmodel.go 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. package costmodel
  2. import (
  3. "context"
  4. "fmt"
  5. "net/http"
  6. "time"
  7. "github.com/julienschmidt/httprouter"
  8. "github.com/prometheus/client_golang/prometheus/promhttp"
  9. "github.com/rs/cors"
  10. "github.com/opencost/opencost/pkg/costmodel"
  11. "github.com/opencost/opencost/pkg/env"
  12. "github.com/opencost/opencost/pkg/errors"
  13. "github.com/opencost/opencost/pkg/filemanager"
  14. "github.com/opencost/opencost/pkg/log"
  15. "github.com/opencost/opencost/pkg/metrics"
  16. "github.com/opencost/opencost/pkg/version"
  17. )
  18. // CostModelOpts contain configuration options that can be passed to the Execute() method
  19. type CostModelOpts struct {
  20. // Stubbed for future configuration
  21. }
  22. func Healthz(w http.ResponseWriter, _ *http.Request, _ httprouter.Params) {
  23. w.WriteHeader(200)
  24. w.Header().Set("Content-Length", "0")
  25. w.Header().Set("Content-Type", "text/plain")
  26. }
  27. func Execute(opts *CostModelOpts) error {
  28. log.Infof("Starting cost-model version %s", version.FriendlyVersion())
  29. a := costmodel.Initialize()
  30. err := StartExportWorker(context.Background(), a.Model)
  31. if err != nil {
  32. log.Errorf("couldn't start CSV export worker: %v", err)
  33. }
  34. rootMux := http.NewServeMux()
  35. a.Router.GET("/healthz", Healthz)
  36. a.Router.GET("/allocation", a.ComputeAllocationHandler)
  37. a.Router.GET("/allocation/summary", a.ComputeAllocationHandlerSummary)
  38. a.Router.GET("/assets", a.ComputeAssetsHandler)
  39. rootMux.Handle("/", a.Router)
  40. rootMux.Handle("/metrics", promhttp.Handler())
  41. telemetryHandler := metrics.ResponseMetricMiddleware(rootMux)
  42. handler := cors.AllowAll().Handler(telemetryHandler)
  43. return http.ListenAndServe(":9003", errors.PanicHandlerMiddleware(handler))
  44. }
  45. func StartExportWorker(ctx context.Context, model costmodel.AllocationModel) error {
  46. exportPath := env.GetExportCSVFile()
  47. if exportPath == "" {
  48. return fmt.Errorf("%s is not set, skipping CSV exporter", exportPath)
  49. }
  50. fm, err := filemanager.NewFileManager(exportPath)
  51. if err != nil {
  52. return fmt.Errorf("could not create file manager: %v", err)
  53. }
  54. go func() {
  55. log.Info("Starting CSV exporter worker...")
  56. // perform first update immediately
  57. nextRunAt := time.Now()
  58. for {
  59. select {
  60. case <-ctx.Done():
  61. return
  62. case <-time.After(nextRunAt.Sub(time.Now())):
  63. err := costmodel.UpdateCSV(ctx, fm, model, env.GetExportCSVLabelsAll(), env.GetExportCSVLabelsList())
  64. if err != nil {
  65. // it's background worker, log error and carry on, maybe next time it will work
  66. log.Errorf("Error updating CSV: %s", err)
  67. }
  68. now := time.Now().UTC()
  69. // next launch is at 00:10 UTC tomorrow
  70. // extra 10 minutes is to let prometheus to collect all the data for the previous day
  71. nextRunAt = time.Date(now.Year(), now.Month(), now.Day(), 0, 10, 0, 0, now.Location()).AddDate(0, 0, 1)
  72. }
  73. }
  74. }()
  75. return nil
  76. }