costmodel.go 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package costmodel
  2. import (
  3. "context"
  4. "net/http"
  5. "os"
  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. StartExportWorker(context.Background(), a.Model)
  31. rootMux := http.NewServeMux()
  32. a.Router.GET("/healthz", Healthz)
  33. a.Router.GET("/allocation", a.ComputeAllocationHandler)
  34. a.Router.GET("/allocation/summary", a.ComputeAllocationHandlerSummary)
  35. rootMux.Handle("/", a.Router)
  36. rootMux.Handle("/metrics", promhttp.Handler())
  37. telemetryHandler := metrics.ResponseMetricMiddleware(rootMux)
  38. handler := cors.AllowAll().Handler(telemetryHandler)
  39. return http.ListenAndServe(":9003", errors.PanicHandlerMiddleware(handler))
  40. }
  41. func StartExportWorker(ctx context.Context, model costmodel.AllocationModel) {
  42. // TODO: there should be a better way to load the configuration
  43. exportPath := os.Getenv(env.ExportCSVFile)
  44. if exportPath == "" {
  45. log.Infof("%s is not set, skipping CSV exporter", env.ExportCSVFile)
  46. return
  47. }
  48. fm, err := filemanager.NewFileManager(exportPath)
  49. if err != nil {
  50. log.Errorf("could not start CSV exporter: %v", err)
  51. return
  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)
  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. }