costmodel.go 13 KB

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