costmodel.go 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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. rootMux.Handle("/", a.Router)
  39. rootMux.Handle("/metrics", promhttp.Handler())
  40. telemetryHandler := metrics.ResponseMetricMiddleware(rootMux)
  41. handler := cors.AllowAll().Handler(telemetryHandler)
  42. return http.ListenAndServe(":9003", errors.PanicHandlerMiddleware(handler))
  43. }
  44. func StartExportWorker(ctx context.Context, model costmodel.AllocationModel) error {
  45. exportPath := env.GetExportCSVFile()
  46. if exportPath == "" {
  47. return fmt.Errorf("%s is not set, skipping CSV exporter", exportPath)
  48. }
  49. fm, err := filemanager.NewFileManager(exportPath)
  50. if err != nil {
  51. return fmt.Errorf("could not create file manager: %v", err)
  52. }
  53. go func() {
  54. log.Info("Starting CSV exporter worker...")
  55. // perform first update immediately
  56. nextRunAt := time.Now()
  57. for {
  58. select {
  59. case <-ctx.Done():
  60. return
  61. case <-time.After(nextRunAt.Sub(time.Now())):
  62. err := costmodel.UpdateCSV(ctx, fm, model, env.GetExportCSVLabelsAll(), env.GetExportCSVLabelsList())
  63. if err != nil {
  64. // it's background worker, log error and carry on, maybe next time it will work
  65. log.Errorf("Error updating CSV: %s", err)
  66. }
  67. now := time.Now().UTC()
  68. // next launch is at 00:10 UTC tomorrow
  69. // extra 10 minutes is to let prometheus to collect all the data for the previous day
  70. nextRunAt = time.Date(now.Year(), now.Month(), now.Day(), 0, 10, 0, 0, now.Location()).AddDate(0, 0, 1)
  71. }
  72. }
  73. }()
  74. return nil
  75. }