2
0

costmodel.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  1. package costmodel
  2. import (
  3. "context"
  4. "fmt"
  5. "net/http"
  6. "os"
  7. "os/signal"
  8. "syscall"
  9. "time"
  10. "github.com/julienschmidt/httprouter"
  11. "github.com/opencost/opencost/core/pkg/util/apiutil"
  12. "github.com/opencost/opencost/core/pkg/util/timeutil"
  13. "github.com/opencost/opencost/pkg/cloudcost"
  14. "github.com/opencost/opencost/pkg/customcost"
  15. "github.com/prometheus/client_golang/prometheus/promhttp"
  16. "github.com/rs/cors"
  17. mcp_sdk "github.com/modelcontextprotocol/go-sdk/mcp"
  18. "github.com/opencost/opencost/core/pkg/errors"
  19. "github.com/opencost/opencost/core/pkg/log"
  20. "github.com/opencost/opencost/core/pkg/version"
  21. "github.com/opencost/opencost/pkg/costmodel"
  22. "github.com/opencost/opencost/pkg/env"
  23. "github.com/opencost/opencost/pkg/filemanager"
  24. opencost_mcp "github.com/opencost/opencost/pkg/mcp"
  25. "github.com/opencost/opencost/pkg/metrics"
  26. )
  27. const shutdownTimeout = 30 * time.Second
  28. func Execute(conf *Config) error {
  29. log.Infof("Starting cost-model version %s", version.FriendlyVersion())
  30. if conf == nil {
  31. conf = DefaultConfig()
  32. }
  33. conf.log()
  34. // Create cancellable context for graceful shutdown
  35. ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
  36. defer cancel()
  37. router := httprouter.New()
  38. var a *costmodel.Accesses
  39. if conf.KubernetesEnabled {
  40. a = costmodel.Initialize(router)
  41. err := StartExportWorker(context.Background(), a.Model)
  42. if err != nil {
  43. log.Errorf("couldn't start CSV export worker: %v", err)
  44. }
  45. // Register OpenCost Specific Endpoints
  46. router.GET("/allocation", a.ComputeAllocationHandler)
  47. router.GET("/allocation/summary", a.ComputeAllocationHandlerSummary)
  48. router.GET("/assets", a.ComputeAssetsHandler)
  49. if conf.CarbonEstimatesEnabled {
  50. router.GET("/assets/carbon", a.ComputeAssetsCarbonHandler)
  51. }
  52. router.GET("/kubemodel", a.KubeModelHandler)
  53. }
  54. var cloudCostPipelineService *cloudcost.PipelineService
  55. if conf.CloudCostEnabled {
  56. cloudCostPipelineService = costmodel.InitializeCloudCost(router)
  57. }
  58. var customCostPipelineService *customcost.PipelineService
  59. if conf.CustomCostEnabled {
  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. // Initialize MCP Server if enabled and Kubernetes is available
  66. if conf.MCPServerEnabled && a != nil {
  67. // Get cloud cost querier if cloud costs are enabled
  68. var cloudCostQuerier cloudcost.Querier
  69. if conf.CloudCostEnabled && cloudCostPipelineService != nil {
  70. cloudCostQuerier = cloudCostPipelineService.GetCloudCostQuerier()
  71. }
  72. err := StartMCPServer(ctx, a, cloudCostQuerier)
  73. if err != nil {
  74. log.Errorf("Failed to start MCP server: %v", err)
  75. }
  76. } else if conf.MCPServerEnabled {
  77. log.Warnf("MCP Server is enabled but Kubernetes is not available. MCP server requires Kubernetes to function.")
  78. } else {
  79. if value, exists := os.LookupEnv(env.MCPServerEnabledEnvVar); !exists || value == "" {
  80. log.Infof("MCP server is now disabled by default. If you wish to use the MCP server, please set the %s environment variable to true.", env.MCPServerEnabledEnvVar)
  81. }
  82. }
  83. apiutil.ApplyContainerDiagnosticEndpoints(router)
  84. rootMux := http.NewServeMux()
  85. rootMux.Handle("/", router)
  86. rootMux.Handle("/metrics", promhttp.Handler())
  87. telemetryHandler := metrics.ResponseMetricMiddleware(rootMux)
  88. handler := cors.AllowAll().Handler(telemetryHandler)
  89. server := &http.Server{
  90. Addr: fmt.Sprint(":", conf.Port),
  91. Handler: errors.PanicHandlerMiddleware(handler),
  92. }
  93. serverErrors := make(chan error, 1)
  94. go func() {
  95. log.Infof("HTTP server starting on port %d", conf.Port)
  96. serverErrors <- server.ListenAndServe()
  97. }()
  98. select {
  99. case err := <-serverErrors:
  100. if err != nil && err != http.ErrServerClosed {
  101. return err
  102. }
  103. return nil
  104. case <-ctx.Done():
  105. log.Infof("Shutdown signal received, starting graceful shutdown...")
  106. if a.KubeModelPipeline != nil {
  107. a.KubeModelPipeline.Stop()
  108. }
  109. if customCostPipelineService != nil {
  110. customCostPipelineService.Stop()
  111. }
  112. shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), shutdownTimeout)
  113. defer shutdownCancel()
  114. if err := server.Shutdown(shutdownCtx); err != nil {
  115. log.Errorf("Error during server shutdown: %v", err)
  116. server.Close()
  117. return err
  118. }
  119. log.Infof("Graceful shutdown completed")
  120. return nil
  121. }
  122. }
  123. func StartExportWorker(ctx context.Context, model costmodel.AllocationModel) error {
  124. exportPath := env.GetExportCSVFile()
  125. if exportPath == "" {
  126. log.Infof("%s is not set, CSV export is disabled", env.ExportCSVFile)
  127. return nil
  128. }
  129. fm, err := filemanager.NewFileManager(exportPath)
  130. if err != nil {
  131. return fmt.Errorf("could not create file manager: %v", err)
  132. }
  133. go func() {
  134. log.Info("Starting CSV exporter worker...")
  135. // perform first update immediately
  136. nextRunAt := time.Now()
  137. for {
  138. select {
  139. case <-ctx.Done():
  140. return
  141. case <-time.After(time.Until(nextRunAt)):
  142. err := costmodel.UpdateCSV(ctx, fm, model, env.GetExportCSVLabelsAll(), env.GetExportCSVLabelsList())
  143. if err != nil {
  144. // it's background worker, log error and carry on, maybe next time it will work
  145. log.Errorf("Error updating CSV: %s", err)
  146. }
  147. now := time.Now().UTC()
  148. // next launch is at 00:10 UTC tomorrow
  149. // extra 10 minutes is to let prometheus to collect all the data for the previous day
  150. nextRunAt = time.Date(now.Year(), now.Month(), now.Day(), 0, 10, 0, 0, now.Location()).AddDate(0, 0, 1)
  151. }
  152. }
  153. }()
  154. return nil
  155. }
  156. // StartMCPServer starts the MCP server as a background service
  157. func StartMCPServer(ctx context.Context, accesses *costmodel.Accesses, cloudCostQuerier cloudcost.Querier) error {
  158. log.Info("Initializing MCP server...")
  159. // Create MCP server using existing OpenCost dependencies
  160. mcpServer := opencost_mcp.NewMCPServer(accesses.Model, accesses.CloudProvider, cloudCostQuerier)
  161. // Create MCP SDK server
  162. sdkServer := mcp_sdk.NewServer(&mcp_sdk.Implementation{
  163. Name: "opencost-mcp-server",
  164. Version: version.Version,
  165. }, nil)
  166. // Define tool handlers
  167. handleAllocationCosts := func(ctx context.Context, req *mcp_sdk.CallToolRequest, args AllocationArgs) (*mcp_sdk.CallToolResult, interface{}, error) {
  168. var step time.Duration
  169. if args.Step != "" {
  170. var err error
  171. step, err = timeutil.ParseDuration(args.Step)
  172. if err != nil {
  173. return nil, nil, fmt.Errorf("invalid step duration '%s': %w", args.Step, err)
  174. }
  175. if step <= 0 {
  176. return nil, nil, fmt.Errorf("invalid step duration '%s': must be > 0", args.Step)
  177. }
  178. }
  179. queryRequest := &opencost_mcp.OpenCostQueryRequest{
  180. QueryType: opencost_mcp.AllocationQueryType,
  181. Window: args.Window,
  182. AllocationParams: &opencost_mcp.AllocationQuery{
  183. Step: step,
  184. Accumulate: args.Accumulate,
  185. ShareIdle: args.ShareIdle,
  186. Aggregate: args.Aggregate,
  187. IncludeIdle: args.IncludeIdle,
  188. IdleByNode: args.IdleByNode,
  189. IncludeProportionalAssetResourceCosts: args.IncludeProportionalAssetResourceCosts,
  190. IncludeAggregatedMetadata: args.IncludeAggregatedMetadata,
  191. ShareLB: args.ShareLB,
  192. Filter: args.Filter,
  193. },
  194. }
  195. mcpReq := &opencost_mcp.MCPRequest{
  196. Query: queryRequest,
  197. }
  198. mcpResp, err := mcpServer.ProcessMCPRequest(ctx, mcpReq)
  199. if err != nil {
  200. return nil, nil, fmt.Errorf("failed to process allocation request: %w", err)
  201. }
  202. return nil, mcpResp, nil
  203. }
  204. handleAssetCosts := func(ctx context.Context, req *mcp_sdk.CallToolRequest, args AssetArgs) (*mcp_sdk.CallToolResult, interface{}, error) {
  205. queryRequest := &opencost_mcp.OpenCostQueryRequest{
  206. QueryType: opencost_mcp.AssetQueryType,
  207. Window: args.Window,
  208. AssetParams: &opencost_mcp.AssetQuery{},
  209. }
  210. mcpReq := &opencost_mcp.MCPRequest{
  211. Query: queryRequest,
  212. }
  213. mcpResp, err := mcpServer.ProcessMCPRequest(ctx, mcpReq)
  214. if err != nil {
  215. return nil, nil, fmt.Errorf("failed to process asset request: %w", err)
  216. }
  217. return nil, mcpResp, nil
  218. }
  219. handleCloudCosts := func(ctx context.Context, req *mcp_sdk.CallToolRequest, args CloudCostArgs) (*mcp_sdk.CallToolResult, interface{}, error) {
  220. queryRequest := &opencost_mcp.OpenCostQueryRequest{
  221. QueryType: opencost_mcp.CloudCostQueryType,
  222. Window: args.Window,
  223. CloudCostParams: &opencost_mcp.CloudCostQuery{
  224. Aggregate: args.Aggregate,
  225. Accumulate: args.Accumulate,
  226. Filter: args.Filter,
  227. Provider: args.Provider,
  228. Service: args.Service,
  229. Category: args.Category,
  230. Region: args.Region,
  231. AccountID: args.Account,
  232. },
  233. }
  234. mcpReq := &opencost_mcp.MCPRequest{
  235. Query: queryRequest,
  236. }
  237. mcpResp, err := mcpServer.ProcessMCPRequest(ctx, mcpReq)
  238. if err != nil {
  239. return nil, nil, fmt.Errorf("failed to process cloud cost request: %w", err)
  240. }
  241. return nil, mcpResp, nil
  242. }
  243. handleEfficiency := func(ctx context.Context, req *mcp_sdk.CallToolRequest, args EfficiencyArgs) (*mcp_sdk.CallToolResult, interface{}, error) {
  244. var step time.Duration
  245. if args.Step != "" {
  246. var err error
  247. step, err = timeutil.ParseDuration(args.Step)
  248. if err != nil {
  249. return nil, nil, fmt.Errorf("invalid step duration '%s': %w", args.Step, err)
  250. }
  251. if step <= 0 {
  252. return nil, nil, fmt.Errorf("invalid step duration '%s': must be > 0", args.Step)
  253. }
  254. }
  255. queryRequest := &opencost_mcp.OpenCostQueryRequest{
  256. QueryType: opencost_mcp.EfficiencyQueryType,
  257. Window: args.Window,
  258. EfficiencyParams: &opencost_mcp.EfficiencyQuery{
  259. Step: step,
  260. Aggregate: args.Aggregate,
  261. Filter: args.Filter,
  262. EfficiencyBufferMultiplier: args.BufferMultiplier,
  263. },
  264. }
  265. mcpReq := &opencost_mcp.MCPRequest{
  266. Query: queryRequest,
  267. }
  268. mcpResp, err := mcpServer.ProcessMCPRequest(ctx, mcpReq)
  269. if err != nil {
  270. return nil, nil, fmt.Errorf("failed to process efficiency request: %w", err)
  271. }
  272. return nil, mcpResp, nil
  273. }
  274. // Register tools
  275. mcp_sdk.AddTool(sdkServer, &mcp_sdk.Tool{
  276. Name: "get_allocation_costs",
  277. Description: "Retrieves allocation cost data.",
  278. }, handleAllocationCosts)
  279. mcp_sdk.AddTool(sdkServer, &mcp_sdk.Tool{
  280. Name: "get_asset_costs",
  281. Description: "Retrieves asset cost data.",
  282. }, handleAssetCosts)
  283. mcp_sdk.AddTool(sdkServer, &mcp_sdk.Tool{
  284. Name: "get_cloud_costs",
  285. Description: "Retrieves cloud cost data.",
  286. }, handleCloudCosts)
  287. mcp_sdk.AddTool(sdkServer, &mcp_sdk.Tool{
  288. Name: "get_efficiency",
  289. Description: "Retrieves resource efficiency metrics with rightsizing recommendations and cost savings analysis. Computes CPU and memory efficiency (usage/request ratio), provides recommended resource requests, and calculates potential cost savings. Optional buffer_multiplier parameter (default: 1.2 for 20% headroom) can be set to values like 1.4 for 40% headroom.",
  290. }, handleEfficiency)
  291. // Create HTTP handler
  292. handler := mcp_sdk.NewStreamableHTTPHandler(func(r *http.Request) *mcp_sdk.Server {
  293. return sdkServer
  294. }, &mcp_sdk.StreamableHTTPOptions{
  295. JSONResponse: true,
  296. })
  297. // Add logging middleware
  298. loggingHandler := http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
  299. log.Debugf("MCP HTTP request: %s %s from %s", req.Method, req.URL.Path, req.RemoteAddr)
  300. handler.ServeHTTP(w, req)
  301. })
  302. // Start HTTP server on configured port
  303. port := env.GetMCPHTTPPort()
  304. log.Infof("Starting MCP HTTP server on port %d...", port)
  305. server := &http.Server{
  306. Addr: fmt.Sprintf(":%d", port),
  307. Handler: loggingHandler,
  308. }
  309. // Start server in a goroutine
  310. go func() {
  311. if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
  312. log.Errorf("MCP server failed: %v", err)
  313. }
  314. }()
  315. // Graceful shutdown goroutine
  316. go func() {
  317. <-ctx.Done()
  318. log.Info("Shutting down MCP server...")
  319. shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  320. defer cancel()
  321. if err := server.Shutdown(shutdownCtx); err != nil {
  322. log.Errorf("MCP server shutdown error: %v", err)
  323. } else {
  324. log.Info("MCP server shut down successfully")
  325. }
  326. }()
  327. log.Info("MCP server started successfully")
  328. return nil
  329. }
  330. // Tool argument structures for MCP server
  331. type AllocationArgs struct {
  332. Window string `json:"window"`
  333. Aggregate string `json:"aggregate"`
  334. // Allocation query parameters
  335. Step string `json:"step,omitempty"`
  336. Resolution string `json:"resolution,omitempty"`
  337. Accumulate bool `json:"accumulate,omitempty"`
  338. ShareIdle bool `json:"share_idle,omitempty"`
  339. IncludeIdle bool `json:"include_idle,omitempty"`
  340. IdleByNode bool `json:"idle_by_node,omitempty"`
  341. IncludeProportionalAssetResourceCosts bool `json:"include_proportional_asset_resource_costs,omitempty"`
  342. IncludeAggregatedMetadata bool `json:"include_aggregated_metadata,omitempty"`
  343. ShareLB bool `json:"share_lb,omitempty"`
  344. Filter string `json:"filter,omitempty"`
  345. }
  346. type AssetArgs struct {
  347. Window string `json:"window"`
  348. }
  349. type CloudCostArgs struct {
  350. Window string `json:"window"`
  351. Aggregate string `json:"aggregate"`
  352. // Cloud cost query parameters
  353. Accumulate string `json:"accumulate,omitempty"`
  354. Filter string `json:"filter,omitempty"`
  355. Provider string `json:"provider,omitempty"`
  356. Service string `json:"service,omitempty"`
  357. Category string `json:"category,omitempty"`
  358. Region string `json:"region,omitempty"`
  359. Account string `json:"account,omitempty"`
  360. }
  361. type EfficiencyArgs struct {
  362. Window string `json:"window"` // Time window (e.g., "today", "yesterday", "7d", "lastweek")
  363. Aggregate string `json:"aggregate,omitempty"` // Aggregation level (e.g., "pod", "namespace", "controller")
  364. Filter string `json:"filter,omitempty"` // Filter expression (same as allocation filters)
  365. BufferMultiplier *float64 `json:"buffer_multiplier,omitempty"` // Buffer multiplier for recommendations (default: 1.2 for 20% headroom, e.g., 1.4 for 40%)
  366. Step string `json:"step,omitempty"` // Query step size (e.g., "1h", "6h"); smaller steps reduce peak memory by batching large windows, but may increase query time/requests
  367. }