costmodel.go 14 KB

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