2
0

costmodel.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  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/core/pkg/util/json"
  10. "github.com/opencost/opencost/pkg/cloud/models"
  11. "github.com/opencost/opencost/pkg/customcost"
  12. "github.com/prometheus/client_golang/prometheus/promhttp"
  13. "github.com/rs/cors"
  14. "github.com/opencost/opencost/core/pkg/log"
  15. "github.com/opencost/opencost/core/pkg/version"
  16. "github.com/opencost/opencost/pkg/costmodel"
  17. "github.com/opencost/opencost/pkg/env"
  18. "github.com/opencost/opencost/pkg/errors"
  19. "github.com/opencost/opencost/pkg/filemanager"
  20. "github.com/opencost/opencost/pkg/metrics"
  21. )
  22. // CostModelOpts contain configuration options that can be passed to the Execute() method
  23. type CostModelOpts struct {
  24. // Stubbed for future configuration
  25. }
  26. func Healthz(w http.ResponseWriter, _ *http.Request, _ httprouter.Params) {
  27. w.WriteHeader(200)
  28. w.Header().Set("Content-Length", "0")
  29. w.Header().Set("Content-Type", "text/plain")
  30. }
  31. func Execute(opts *CostModelOpts) error {
  32. log.Infof("Starting cost-model version %s", version.FriendlyVersion())
  33. log.Infof("Kubernetes enabled: %t", env.IsKubernetesEnabled())
  34. router := httprouter.New()
  35. var a *costmodel.Accesses
  36. var cp models.Provider
  37. if env.IsKubernetesEnabled() {
  38. a = costmodel.Initialize(router)
  39. err := StartExportWorker(context.Background(), a.Model)
  40. if err != nil {
  41. log.Errorf("couldn't start CSV export worker: %v", err)
  42. }
  43. // Register OpenCost Specific Endpoints
  44. router.GET("/allocation", a.ComputeAllocationHandler)
  45. router.GET("/allocation/summary", a.ComputeAllocationHandlerSummary)
  46. router.GET("/assets", a.ComputeAssetsHandler)
  47. if env.IsCarbonEstimatesEnabled() {
  48. router.GET("/assets/carbon", a.ComputeAssetsCarbonHandler)
  49. }
  50. // set cloud provider for cloud cost
  51. cp = a.CloudProvider
  52. }
  53. log.Infof("Cloud Costs enabled: %t", env.IsCloudCostEnabled())
  54. if env.IsCloudCostEnabled() {
  55. costmodel.InitializeCloudCost(router, cp)
  56. }
  57. log.Infof("Custom Costs enabled: %t", env.IsCustomCostEnabled())
  58. var customCostPipelineService *customcost.PipelineService
  59. if env.IsCustomCostEnabled() {
  60. customCostPipelineService = costmodel.InitializeCustomCost(router)
  61. }
  62. // this endpoint is intentionally left out of the "if env.IsCustomCostEnabled()" conditional; in the handler, it is
  63. // valid for CustomCostPipelineService to be nil
  64. router.GET("/customCost/status", customCostPipelineService.GetCustomCostStatusHandler())
  65. router.GET("/healthz", Healthz)
  66. router.GET("/logs/level", GetLogLevel)
  67. router.POST("/logs/level", SetLogLevel)
  68. if env.IsPProfEnabled() {
  69. router.HandlerFunc(http.MethodGet, "/debug/pprof/", pprof.Index)
  70. router.HandlerFunc(http.MethodGet, "/debug/pprof/cmdline", pprof.Cmdline)
  71. router.HandlerFunc(http.MethodGet, "/debug/pprof/profile", pprof.Profile)
  72. router.HandlerFunc(http.MethodGet, "/debug/pprof/symbol", pprof.Symbol)
  73. router.HandlerFunc(http.MethodGet, "/debug/pprof/trace", pprof.Trace)
  74. router.Handler(http.MethodGet, "/debug/pprof/goroutine", pprof.Handler("goroutine"))
  75. router.Handler(http.MethodGet, "/debug/pprof/heap", pprof.Handler("heap"))
  76. }
  77. rootMux := http.NewServeMux()
  78. rootMux.Handle("/", router)
  79. rootMux.Handle("/metrics", promhttp.Handler())
  80. telemetryHandler := metrics.ResponseMetricMiddleware(rootMux)
  81. handler := cors.AllowAll().Handler(telemetryHandler)
  82. return http.ListenAndServe(fmt.Sprint(":", env.GetAPIPort()), errors.PanicHandlerMiddleware(handler))
  83. }
  84. func StartExportWorker(ctx context.Context, model costmodel.AllocationModel) error {
  85. exportPath := env.GetExportCSVFile()
  86. if exportPath == "" {
  87. log.Infof("%s is not set, CSV export is disabled", env.ExportCSVFile)
  88. return nil
  89. }
  90. fm, err := filemanager.NewFileManager(exportPath)
  91. if err != nil {
  92. return fmt.Errorf("could not create file manager: %v", err)
  93. }
  94. go func() {
  95. log.Info("Starting CSV exporter worker...")
  96. // perform first update immediately
  97. nextRunAt := time.Now()
  98. for {
  99. select {
  100. case <-ctx.Done():
  101. return
  102. case <-time.After(nextRunAt.Sub(time.Now())):
  103. err := costmodel.UpdateCSV(ctx, fm, model, env.GetExportCSVLabelsAll(), env.GetExportCSVLabelsList())
  104. if err != nil {
  105. // it's background worker, log error and carry on, maybe next time it will work
  106. log.Errorf("Error updating CSV: %s", err)
  107. }
  108. now := time.Now().UTC()
  109. // next launch is at 00:10 UTC tomorrow
  110. // extra 10 minutes is to let prometheus to collect all the data for the previous day
  111. nextRunAt = time.Date(now.Year(), now.Month(), now.Day(), 0, 10, 0, 0, now.Location()).AddDate(0, 0, 1)
  112. }
  113. }
  114. }()
  115. return nil
  116. }
  117. type LogLevelRequestResponse struct {
  118. Level string `json:"level"`
  119. }
  120. func GetLogLevel(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
  121. w.Header().Set("Content-Type", "application/json")
  122. w.Header().Set("Access-Control-Allow-Origin", "*")
  123. level := log.GetLogLevel()
  124. llrr := LogLevelRequestResponse{
  125. Level: level,
  126. }
  127. body, err := json.Marshal(llrr)
  128. if err != nil {
  129. http.Error(w, fmt.Sprintf("unable to retrive log level"), http.StatusInternalServerError)
  130. return
  131. }
  132. _, err = w.Write(body)
  133. if err != nil {
  134. http.Error(w, fmt.Sprintf("unable to write response: %s", body), http.StatusInternalServerError)
  135. return
  136. }
  137. }
  138. func SetLogLevel(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
  139. params := LogLevelRequestResponse{}
  140. err := json.NewDecoder(r.Body).Decode(&params)
  141. if err != nil {
  142. http.Error(w, fmt.Sprintf("unable to decode request body, error: %s", err), http.StatusBadRequest)
  143. return
  144. }
  145. err = log.SetLogLevel(params.Level)
  146. if err != nil {
  147. http.Error(w, fmt.Sprintf("level must be a valid log level according to zerolog; level given: %s, error: %s", params.Level, err), http.StatusBadRequest)
  148. return
  149. }
  150. w.WriteHeader(http.StatusOK)
  151. }