server.go 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188
  1. package mcp
  2. import (
  3. "context"
  4. "crypto/rand"
  5. "encoding/hex"
  6. "fmt"
  7. "strings"
  8. "sync"
  9. "time"
  10. "github.com/go-playground/validator/v10"
  11. "github.com/opencost/opencost/core/pkg/filter"
  12. "github.com/opencost/opencost/core/pkg/filter/allocation"
  13. cloudcostfilter "github.com/opencost/opencost/core/pkg/filter/cloudcost"
  14. "github.com/opencost/opencost/core/pkg/opencost"
  15. models "github.com/opencost/opencost/pkg/cloud/models"
  16. "github.com/opencost/opencost/pkg/cloudcost"
  17. "github.com/opencost/opencost/pkg/costmodel"
  18. )
  19. // QueryType defines the type of query to be executed.
  20. type QueryType string
  21. const (
  22. AllocationQueryType QueryType = "allocation"
  23. AssetQueryType QueryType = "asset"
  24. CloudCostQueryType QueryType = "cloudcost"
  25. EfficiencyQueryType QueryType = "efficiency"
  26. )
  27. // Efficiency calculation constants
  28. const (
  29. efficiencyBufferMultiplier = 1.2 // 20% headroom for stability
  30. efficiencyMinCPU = 0.001 // minimum CPU cores
  31. efficiencyMinRAM = 1024 * 1024 // 1 MB minimum RAM
  32. )
  33. // MCPRequest represents a single turn in a conversation with the OpenCost MCP server.
  34. type MCPRequest struct {
  35. SessionID string `json:"sessionId"`
  36. Query *OpenCostQueryRequest `json:"query"`
  37. }
  38. // MCPResponse is the response from the OpenCost MCP server for a single turn.
  39. type MCPResponse struct {
  40. Data interface{} `json:"data"`
  41. QueryInfo QueryMetadata `json:"queryInfo"`
  42. }
  43. // QueryMetadata contains metadata about the query execution.
  44. type QueryMetadata struct {
  45. QueryID string `json:"queryId"`
  46. Timestamp time.Time `json:"timestamp"`
  47. ProcessingTime time.Duration `json:"processingTime"`
  48. }
  49. // OpenCostQueryRequest provides a unified interface for all OpenCost query types.
  50. type OpenCostQueryRequest struct {
  51. QueryType QueryType `json:"queryType" validate:"required,oneof=allocation asset cloudcost efficiency"`
  52. Window string `json:"window" validate:"required"`
  53. AllocationParams *AllocationQuery `json:"allocationParams,omitempty"`
  54. AssetParams *AssetQuery `json:"assetParams,omitempty"`
  55. CloudCostParams *CloudCostQuery `json:"cloudCostParams,omitempty"`
  56. EfficiencyParams *EfficiencyQuery `json:"efficiencyParams,omitempty"`
  57. }
  58. // AllocationQuery contains the parameters for an allocation query.
  59. type AllocationQuery struct {
  60. Step time.Duration `json:"step,omitempty"`
  61. Accumulate bool `json:"accumulate,omitempty"`
  62. ShareIdle bool `json:"shareIdle,omitempty"`
  63. Aggregate string `json:"aggregate,omitempty"`
  64. IncludeIdle bool `json:"includeIdle,omitempty"`
  65. IdleByNode bool `json:"idleByNode,omitempty"`
  66. IncludeProportionalAssetResourceCosts bool `json:"includeProportionalAssetResourceCosts,omitempty"`
  67. IncludeAggregatedMetadata bool `json:"includeAggregatedMetadata,omitempty"`
  68. ShareLB bool `json:"sharelb,omitempty"`
  69. Filter string `json:"filter,omitempty"` // Filter expression for allocations (e.g., "cluster:production", "namespace:kube-system")
  70. }
  71. // AssetQuery contains the parameters for an asset query.
  72. type AssetQuery struct {
  73. // Currently no specific parameters needed for asset queries as it only takes window as parameter
  74. }
  75. // CloudCostQuery contains the parameters for a cloud cost query.
  76. type CloudCostQuery struct {
  77. Aggregate string `json:"aggregate,omitempty"` // Comma-separated list of aggregation properties
  78. Accumulate string `json:"accumulate,omitempty"` // e.g., "week", "day", "month"
  79. Filter string `json:"filter,omitempty"` // Filter expression for cloud costs
  80. Provider string `json:"provider,omitempty"` // Cloud provider filter (aws, gcp, azure, etc.)
  81. Service string `json:"service,omitempty"` // Service filter (ec2, s3, compute, etc.)
  82. Category string `json:"category,omitempty"` // Category filter (compute, storage, network, etc.)
  83. Region string `json:"region,omitempty"` // Region filter
  84. // Additional explicit fields for filtering
  85. AccountID string `json:"accountID,omitempty"` // Alias of Account; maps to accountID
  86. InvoiceEntityID string `json:"invoiceEntityID,omitempty"` // Invoice entity ID filter
  87. ProviderID string `json:"providerID,omitempty"` // Cloud provider resource ID filter
  88. Labels map[string]string `json:"labels,omitempty"` // Label filters (key->value)
  89. }
  90. // EfficiencyQuery contains the parameters for an efficiency query.
  91. type EfficiencyQuery struct {
  92. Aggregate string `json:"aggregate,omitempty"` // Aggregation properties (e.g., "pod", "namespace", "controller")
  93. Filter string `json:"filter,omitempty"` // Filter expression for allocations (same as AllocationQuery)
  94. EfficiencyBufferMultiplier *float64 `json:"efficiencyBufferMultiplier,omitempty"` // Buffer multiplier for recommendations (default: 1.2 for 20% headroom)
  95. }
  96. // AllocationResponse represents the allocation data returned to the AI agent.
  97. type AllocationResponse struct {
  98. // The allocation data, as a map of allocation sets.
  99. Allocations map[string]*AllocationSet `json:"allocations"`
  100. }
  101. // AllocationSet represents a set of allocation data.
  102. type AllocationSet struct {
  103. // The name of the allocation set.
  104. Name string `json:"name"`
  105. Properties map[string]string `json:"properties"`
  106. Allocations []*Allocation `json:"allocations"`
  107. }
  108. // TotalCost calculates the total cost of all allocations in the set.
  109. func (as *AllocationSet) TotalCost() float64 {
  110. var total float64
  111. for _, alloc := range as.Allocations {
  112. total += alloc.TotalCost
  113. }
  114. return total
  115. }
  116. // Allocation represents a single allocation data point.
  117. type Allocation struct {
  118. Name string `json:"name"` // Allocation key (namespace, cluster, etc.)
  119. CPUCost float64 `json:"cpuCost"` // Cost of CPU usage
  120. GPUCost float64 `json:"gpuCost"` // Cost of GPU usage
  121. RAMCost float64 `json:"ramCost"` // Cost of memory usage
  122. PVCost float64 `json:"pvCost"` // Cost of persistent volumes
  123. NetworkCost float64 `json:"networkCost"` // Cost of network usage
  124. SharedCost float64 `json:"sharedCost"` // Shared/unallocated costs assigned here
  125. ExternalCost float64 `json:"externalCost"` // External costs (cloud services, etc.)
  126. TotalCost float64 `json:"totalCost"` // Sum of all costs above
  127. CPUCoreHours float64 `json:"cpuCoreHours"` // Usage metrics: CPU core-hours
  128. RAMByteHours float64 `json:"ramByteHours"` // Usage metrics: RAM byte-hours
  129. GPUHours float64 `json:"gpuHours"` // Usage metrics: GPU-hours
  130. PVByteHours float64 `json:"pvByteHours"` // Usage metrics: PV byte-hours
  131. Start time.Time `json:"start"` // Start timestamp for this allocation
  132. End time.Time `json:"end"` // End timestamp for this allocation
  133. }
  134. // AssetResponse represents the asset data returned to the AI agent.
  135. type AssetResponse struct {
  136. // The asset data, as a map of asset sets.
  137. Assets map[string]*AssetSet `json:"assets"`
  138. }
  139. // AssetSet represents a set of asset data.
  140. type AssetSet struct {
  141. // The name of the asset set.
  142. Name string `json:"name"`
  143. // The asset data for the set.
  144. Assets []*Asset `json:"assets"`
  145. }
  146. // Asset represents a single asset data point.
  147. type Asset struct {
  148. Type string `json:"type"`
  149. Properties AssetProperties `json:"properties"`
  150. Labels map[string]string `json:"labels,omitempty"`
  151. Start time.Time `json:"start"`
  152. End time.Time `json:"end"`
  153. Minutes float64 `json:"minutes"`
  154. Adjustment float64 `json:"adjustment"`
  155. TotalCost float64 `json:"totalCost"`
  156. // Disk-specific fields
  157. ByteHours float64 `json:"byteHours,omitempty"`
  158. ByteHoursUsed *float64 `json:"byteHoursUsed,omitempty"`
  159. ByteUsageMax *float64 `json:"byteUsageMax,omitempty"`
  160. StorageClass string `json:"storageClass,omitempty"`
  161. VolumeName string `json:"volumeName,omitempty"`
  162. ClaimName string `json:"claimName,omitempty"`
  163. ClaimNamespace string `json:"claimNamespace,omitempty"`
  164. Local float64 `json:"local,omitempty"`
  165. // Node-specific fields
  166. NodeType string `json:"nodeType,omitempty"`
  167. CPUCoreHours float64 `json:"cpuCoreHours,omitempty"`
  168. RAMByteHours float64 `json:"ramByteHours,omitempty"`
  169. GPUHours float64 `json:"gpuHours,omitempty"`
  170. GPUCount float64 `json:"gpuCount,omitempty"`
  171. CPUCost float64 `json:"cpuCost,omitempty"`
  172. GPUCost float64 `json:"gpuCost,omitempty"`
  173. RAMCost float64 `json:"ramCost,omitempty"`
  174. Discount float64 `json:"discount,omitempty"`
  175. Preemptible float64 `json:"preemptible,omitempty"`
  176. // Breakdown fields (can be used for different types)
  177. Breakdown *AssetBreakdown `json:"breakdown,omitempty"`
  178. CPUBreakdown *AssetBreakdown `json:"cpuBreakdown,omitempty"`
  179. RAMBreakdown *AssetBreakdown `json:"ramBreakdown,omitempty"`
  180. // Overhead (Node-specific)
  181. Overhead *NodeOverhead `json:"overhead,omitempty"`
  182. // LoadBalancer-specific fields
  183. Private bool `json:"private,omitempty"`
  184. Ip string `json:"ip,omitempty"`
  185. // Cloud-specific fields
  186. Credit float64 `json:"credit,omitempty"`
  187. }
  188. // NodeOverhead represents node overhead information
  189. type NodeOverhead struct {
  190. RamOverheadFraction float64 `json:"ramOverheadFraction"`
  191. CpuOverheadFraction float64 `json:"cpuOverheadFraction"`
  192. OverheadCostFraction float64 `json:"overheadCostFraction"`
  193. }
  194. type AssetProperties struct {
  195. Category string `json:"category,omitempty"`
  196. Provider string `json:"provider,omitempty"`
  197. Account string `json:"account,omitempty"`
  198. Project string `json:"project,omitempty"`
  199. Service string `json:"service,omitempty"`
  200. Cluster string `json:"cluster,omitempty"`
  201. Name string `json:"name,omitempty"`
  202. ProviderID string `json:"providerID,omitempty"`
  203. }
  204. type AssetBreakdown struct {
  205. Idle float64 `json:"idle"`
  206. Other float64 `json:"other"`
  207. System float64 `json:"system"`
  208. User float64 `json:"user"`
  209. }
  210. // CloudCostResponse represents the cloud cost data returned to the AI agent.
  211. type CloudCostResponse struct {
  212. // The cloud cost data, as a map of cloud cost sets.
  213. CloudCosts map[string]*CloudCostSet `json:"cloudCosts"`
  214. // Summary information
  215. Summary *CloudCostSummary `json:"summary,omitempty"`
  216. }
  217. // CloudCostSummary provides summary information about cloud costs
  218. type CloudCostSummary struct {
  219. TotalNetCost float64 `json:"totalNetCost"`
  220. TotalAmortizedCost float64 `json:"totalAmortizedCost"`
  221. TotalInvoicedCost float64 `json:"totalInvoicedCost"`
  222. KubernetesPercent float64 `json:"kubernetesPercent"`
  223. ProviderBreakdown map[string]float64 `json:"providerBreakdown,omitempty"`
  224. ServiceBreakdown map[string]float64 `json:"serviceBreakdown,omitempty"`
  225. RegionBreakdown map[string]float64 `json:"regionBreakdown,omitempty"`
  226. }
  227. // CloudCostSet represents a set of cloud cost data.
  228. type CloudCostSet struct {
  229. // The name of the cloud cost set.
  230. Name string `json:"name"`
  231. // The cloud cost data for the set.
  232. CloudCosts []*CloudCost `json:"cloudCosts"`
  233. // Aggregation information
  234. AggregationProperties []string `json:"aggregationProperties,omitempty"`
  235. // Time window
  236. Window *TimeWindow `json:"window,omitempty"`
  237. }
  238. // TimeWindow represents a time range
  239. type TimeWindow struct {
  240. Start time.Time `json:"start"`
  241. End time.Time `json:"end"`
  242. }
  243. // CloudCostProperties defines the properties of a cloud cost item.
  244. type CloudCostProperties struct {
  245. ProviderID string `json:"providerID,omitempty"`
  246. Provider string `json:"provider,omitempty"`
  247. AccountID string `json:"accountID,omitempty"`
  248. AccountName string `json:"accountName,omitempty"`
  249. InvoiceEntityID string `json:"invoiceEntityID,omitempty"`
  250. InvoiceEntityName string `json:"invoiceEntityName,omitempty"`
  251. RegionID string `json:"regionID,omitempty"`
  252. AvailabilityZone string `json:"availabilityZone,omitempty"`
  253. Service string `json:"service,omitempty"`
  254. Category string `json:"category,omitempty"`
  255. Labels map[string]string `json:"labels,omitempty"`
  256. }
  257. // CloudCost represents a single cloud cost data point.
  258. type CloudCost struct {
  259. Properties CloudCostProperties `json:"properties"`
  260. Window TimeWindow `json:"window"`
  261. ListCost CostMetric `json:"listCost"`
  262. NetCost CostMetric `json:"netCost"`
  263. AmortizedNetCost CostMetric `json:"amortizedNetCost"`
  264. InvoicedCost CostMetric `json:"invoicedCost"`
  265. AmortizedCost CostMetric `json:"amortizedCost"`
  266. }
  267. // CostMetric represents a cost value with Kubernetes percentage
  268. type CostMetric struct {
  269. Cost float64 `json:"cost"`
  270. KubernetesPercent float64 `json:"kubernetesPercent"`
  271. }
  272. // EfficiencyResponse represents the efficiency data returned to the AI agent.
  273. type EfficiencyResponse struct {
  274. Efficiencies []*EfficiencyMetric `json:"efficiencies"`
  275. }
  276. // EfficiencyMetric represents efficiency data for a single pod/workload.
  277. type EfficiencyMetric struct {
  278. Name string `json:"name"` // Pod/namespace/controller name based on aggregation
  279. // Current state
  280. CPUEfficiency float64 `json:"cpuEfficiency"` // Usage / Request ratio (0-1+)
  281. MemoryEfficiency float64 `json:"memoryEfficiency"` // Usage / Request ratio (0-1+)
  282. // Current requests and usage
  283. CPUCoresRequested float64 `json:"cpuCoresRequested"`
  284. CPUCoresUsed float64 `json:"cpuCoresUsed"`
  285. RAMBytesRequested float64 `json:"ramBytesRequested"`
  286. RAMBytesUsed float64 `json:"ramBytesUsed"`
  287. // Recommendations (based on actual usage with buffer)
  288. RecommendedCPURequest float64 `json:"recommendedCpuRequest"` // Recommended CPU cores
  289. RecommendedRAMRequest float64 `json:"recommendedRamRequest"` // Recommended RAM bytes
  290. // Resulting efficiency after applying recommendations
  291. ResultingCPUEfficiency float64 `json:"resultingCpuEfficiency"`
  292. ResultingMemoryEfficiency float64 `json:"resultingMemoryEfficiency"`
  293. // Cost analysis
  294. CurrentTotalCost float64 `json:"currentTotalCost"` // Current total cost
  295. RecommendedCost float64 `json:"recommendedCost"` // Estimated cost with recommendations
  296. CostSavings float64 `json:"costSavings"` // Potential savings
  297. CostSavingsPercent float64 `json:"costSavingsPercent"` // Savings as percentage
  298. // Buffer multiplier used for recommendations
  299. EfficiencyBufferMultiplier float64 `json:"efficiencyBufferMultiplier"` // Buffer multiplier applied (e.g., 1.2 for 20% headroom)
  300. // Time window
  301. Start time.Time `json:"start"`
  302. End time.Time `json:"end"`
  303. }
  304. // MCPServer holds the dependencies for the MCP API server.
  305. type MCPServer struct {
  306. costModel *costmodel.CostModel
  307. provider models.Provider
  308. cloudQuerier cloudcost.Querier
  309. }
  310. // NewMCPServer creates a new MCP Server.
  311. func NewMCPServer(costModel *costmodel.CostModel, provider models.Provider, cloudQuerier cloudcost.Querier) *MCPServer {
  312. return &MCPServer{
  313. costModel: costModel,
  314. provider: provider,
  315. cloudQuerier: cloudQuerier,
  316. }
  317. }
  318. // ProcessMCPRequest processes an MCP request and returns an MCP response.
  319. func (s *MCPServer) ProcessMCPRequest(request *MCPRequest) (*MCPResponse, error) {
  320. // 1. Validate Request
  321. if err := validate.Struct(request); err != nil {
  322. return nil, fmt.Errorf("validation failed: %w", err)
  323. }
  324. // 2. Query Dispatching
  325. var data interface{}
  326. var err error
  327. queryStart := time.Now()
  328. switch request.Query.QueryType {
  329. case AllocationQueryType:
  330. data, err = s.QueryAllocations(request.Query)
  331. case AssetQueryType:
  332. data, err = s.QueryAssets(request.Query)
  333. case CloudCostQueryType:
  334. data, err = s.QueryCloudCosts(request.Query)
  335. case EfficiencyQueryType:
  336. data, err = s.QueryEfficiency(request.Query)
  337. default:
  338. return nil, fmt.Errorf("unsupported query type: %s", request.Query.QueryType)
  339. }
  340. if err != nil {
  341. // Handle error appropriately, maybe return a JSON-RPC error response
  342. return nil, err
  343. }
  344. processingTime := time.Since(queryStart)
  345. // 3. Construct Final Response
  346. mcpResponse := &MCPResponse{
  347. Data: data,
  348. QueryInfo: QueryMetadata{
  349. QueryID: generateQueryID(),
  350. Timestamp: time.Now(),
  351. ProcessingTime: processingTime,
  352. },
  353. }
  354. return mcpResponse, nil
  355. }
  356. // validate is the singleton validator instance.
  357. var validate = validator.New()
  358. func generateQueryID() string {
  359. bytes := make([]byte, 8) // 16 hex characters
  360. if _, err := rand.Read(bytes); err != nil {
  361. // Fallback to timestamp-based ID if crypto/rand fails
  362. return fmt.Sprintf("query-%d", time.Now().UnixNano())
  363. }
  364. return fmt.Sprintf("query-%s", hex.EncodeToString(bytes))
  365. }
  366. func (s *MCPServer) QueryAllocations(query *OpenCostQueryRequest) (*AllocationResponse, error) {
  367. // 1. Parse Window
  368. window, err := opencost.ParseWindowWithOffset(query.Window, 0) // 0 offset for UTC
  369. if err != nil {
  370. return nil, fmt.Errorf("failed to parse window '%s': %w", query.Window, err)
  371. }
  372. // 2. Set default parameters
  373. var step time.Duration
  374. var aggregateBy []string
  375. var includeIdle, idleByNode, includeProportionalAssetResourceCosts, includeAggregatedMetadata, sharedLoadBalancer, shareIdle bool
  376. var accumulateBy opencost.AccumulateOption
  377. var filterString string
  378. // 3. Parse allocation parameters if provided
  379. if query.AllocationParams != nil {
  380. // Set step duration (default to window duration if not specified)
  381. if query.AllocationParams.Step > 0 {
  382. step = query.AllocationParams.Step
  383. } else {
  384. step = window.Duration()
  385. }
  386. // Parse aggregation properties
  387. if query.AllocationParams.Aggregate != "" {
  388. aggregateBy = strings.Split(query.AllocationParams.Aggregate, ",")
  389. }
  390. // Set boolean parameters
  391. includeIdle = query.AllocationParams.IncludeIdle
  392. idleByNode = query.AllocationParams.IdleByNode
  393. includeProportionalAssetResourceCosts = query.AllocationParams.IncludeProportionalAssetResourceCosts
  394. includeAggregatedMetadata = query.AllocationParams.IncludeAggregatedMetadata
  395. sharedLoadBalancer = query.AllocationParams.ShareLB
  396. shareIdle = query.AllocationParams.ShareIdle
  397. // Set filter string
  398. filterString = query.AllocationParams.Filter
  399. // Validate filter string if provided
  400. if filterString != "" {
  401. parser := allocation.NewAllocationFilterParser()
  402. _, err := parser.Parse(filterString)
  403. if err != nil {
  404. return nil, fmt.Errorf("invalid allocation filter '%s': %w", filterString, err)
  405. }
  406. }
  407. // Set accumulation option
  408. if query.AllocationParams.Accumulate {
  409. accumulateBy = opencost.AccumulateOptionAll
  410. } else {
  411. accumulateBy = opencost.AccumulateOptionNone
  412. }
  413. } else {
  414. // Default values when no parameters provided
  415. step = window.Duration()
  416. accumulateBy = opencost.AccumulateOptionNone
  417. filterString = ""
  418. }
  419. // 4. Call the existing QueryAllocation function with all parameters
  420. asr, err := s.costModel.QueryAllocation(
  421. window,
  422. step,
  423. aggregateBy,
  424. includeIdle,
  425. idleByNode,
  426. includeProportionalAssetResourceCosts,
  427. includeAggregatedMetadata,
  428. sharedLoadBalancer,
  429. accumulateBy,
  430. shareIdle,
  431. filterString,
  432. )
  433. if err != nil {
  434. return nil, fmt.Errorf("failed to query allocations: %w", err)
  435. }
  436. // 5. Handle the AllocationSetRange result
  437. if asr == nil || len(asr.Allocations) == 0 {
  438. return &AllocationResponse{
  439. Allocations: make(map[string]*AllocationSet),
  440. }, nil
  441. }
  442. // 6. Transform the result to MCP format
  443. // If we have multiple sets, we'll combine them or return the first one
  444. // For now, let's return the first allocation set
  445. firstSet := asr.Allocations[0]
  446. return transformAllocationSet(firstSet), nil
  447. }
  448. // transformAllocationSet converts an opencost.AllocationSet into the MCP's AllocationResponse format.
  449. func transformAllocationSet(allocSet *opencost.AllocationSet) *AllocationResponse {
  450. if allocSet == nil {
  451. return &AllocationResponse{Allocations: make(map[string]*AllocationSet)}
  452. }
  453. mcpAllocations := make(map[string]*AllocationSet)
  454. // Create a single set for all allocations
  455. mcpSet := &AllocationSet{
  456. Name: "allocations",
  457. Allocations: []*Allocation{},
  458. }
  459. // Convert each allocation
  460. for _, alloc := range allocSet.Allocations {
  461. if alloc == nil {
  462. continue
  463. }
  464. mcpAlloc := &Allocation{
  465. Name: alloc.Name,
  466. CPUCost: alloc.CPUCost,
  467. GPUCost: alloc.GPUCost,
  468. RAMCost: alloc.RAMCost,
  469. PVCost: alloc.PVCost(), // Call the method
  470. NetworkCost: alloc.NetworkCost,
  471. SharedCost: alloc.SharedCost,
  472. ExternalCost: alloc.ExternalCost,
  473. TotalCost: alloc.TotalCost(),
  474. CPUCoreHours: alloc.CPUCoreHours,
  475. RAMByteHours: alloc.RAMByteHours,
  476. GPUHours: alloc.GPUHours,
  477. PVByteHours: alloc.PVBytes(), // Use the method directly
  478. Start: alloc.Start,
  479. End: alloc.End,
  480. }
  481. mcpSet.Allocations = append(mcpSet.Allocations, mcpAlloc)
  482. }
  483. mcpAllocations["allocations"] = mcpSet
  484. return &AllocationResponse{
  485. Allocations: mcpAllocations,
  486. }
  487. }
  488. func (s *MCPServer) QueryAssets(query *OpenCostQueryRequest) (*AssetResponse, error) {
  489. // 1. Parse Window
  490. window, err := opencost.ParseWindowWithOffset(query.Window, 0) // 0 offset for UTC
  491. if err != nil {
  492. return nil, fmt.Errorf("failed to parse window '%s': %w", query.Window, err)
  493. }
  494. // 2. Set Query Options
  495. start := *window.Start()
  496. end := *window.End()
  497. // 3. Call CostModel to get the asset set
  498. assetSet, err := s.costModel.ComputeAssets(start, end)
  499. if err != nil {
  500. return nil, fmt.Errorf("failed to compute assets: %w", err)
  501. }
  502. // 4. Transform Response for the MCP API
  503. return transformAssetSet(assetSet), nil
  504. }
  505. // transformAssetSet converts a opencost.AssetSet into the MCP's AssetResponse format.
  506. func transformAssetSet(assetSet *opencost.AssetSet) *AssetResponse {
  507. if assetSet == nil {
  508. return &AssetResponse{Assets: make(map[string]*AssetSet)}
  509. }
  510. mcpAssets := make(map[string]*AssetSet)
  511. // Create a single set for all assets
  512. mcpSet := &AssetSet{
  513. Name: "assets",
  514. Assets: []*Asset{},
  515. }
  516. for _, asset := range assetSet.Assets {
  517. if asset == nil {
  518. continue
  519. }
  520. properties := asset.GetProperties()
  521. labels := asset.GetLabels()
  522. mcpAsset := &Asset{
  523. Type: asset.Type().String(),
  524. Properties: AssetProperties{
  525. Category: properties.Category,
  526. Provider: properties.Provider,
  527. Account: properties.Account,
  528. Project: properties.Project,
  529. Service: properties.Service,
  530. Cluster: properties.Cluster,
  531. Name: properties.Name,
  532. ProviderID: properties.ProviderID,
  533. },
  534. Labels: labels,
  535. Start: asset.GetStart(),
  536. End: asset.GetEnd(),
  537. Minutes: asset.Minutes(),
  538. Adjustment: asset.GetAdjustment(),
  539. TotalCost: asset.TotalCost(),
  540. }
  541. // Handle type-specific fields
  542. switch a := asset.(type) {
  543. case *opencost.Disk:
  544. mcpAsset.ByteHours = a.ByteHours
  545. mcpAsset.ByteHoursUsed = a.ByteHoursUsed
  546. mcpAsset.ByteUsageMax = a.ByteUsageMax
  547. mcpAsset.StorageClass = a.StorageClass
  548. mcpAsset.VolumeName = a.VolumeName
  549. mcpAsset.ClaimName = a.ClaimName
  550. mcpAsset.ClaimNamespace = a.ClaimNamespace
  551. mcpAsset.Local = a.Local
  552. if a.Breakdown != nil {
  553. mcpAsset.Breakdown = &AssetBreakdown{
  554. Idle: a.Breakdown.Idle,
  555. Other: a.Breakdown.Other,
  556. System: a.Breakdown.System,
  557. User: a.Breakdown.User,
  558. }
  559. }
  560. case *opencost.Node:
  561. mcpAsset.NodeType = a.NodeType
  562. mcpAsset.CPUCoreHours = a.CPUCoreHours
  563. mcpAsset.RAMByteHours = a.RAMByteHours
  564. mcpAsset.GPUHours = a.GPUHours
  565. mcpAsset.GPUCount = a.GPUCount
  566. mcpAsset.CPUCost = a.CPUCost
  567. mcpAsset.GPUCost = a.GPUCost
  568. mcpAsset.RAMCost = a.RAMCost
  569. mcpAsset.Discount = a.Discount
  570. mcpAsset.Preemptible = a.Preemptible
  571. if a.CPUBreakdown != nil {
  572. mcpAsset.CPUBreakdown = &AssetBreakdown{
  573. Idle: a.CPUBreakdown.Idle,
  574. Other: a.CPUBreakdown.Other,
  575. System: a.CPUBreakdown.System,
  576. User: a.CPUBreakdown.User,
  577. }
  578. }
  579. if a.RAMBreakdown != nil {
  580. mcpAsset.RAMBreakdown = &AssetBreakdown{
  581. Idle: a.RAMBreakdown.Idle,
  582. Other: a.RAMBreakdown.Other,
  583. System: a.RAMBreakdown.System,
  584. User: a.RAMBreakdown.User,
  585. }
  586. }
  587. if a.Overhead != nil {
  588. mcpAsset.Overhead = &NodeOverhead{
  589. RamOverheadFraction: a.Overhead.RamOverheadFraction,
  590. CpuOverheadFraction: a.Overhead.CpuOverheadFraction,
  591. OverheadCostFraction: a.Overhead.OverheadCostFraction,
  592. }
  593. }
  594. case *opencost.LoadBalancer:
  595. mcpAsset.Private = a.Private
  596. mcpAsset.Ip = a.Ip
  597. case *opencost.Network:
  598. // Network assets have no specific fields beyond the base asset structure
  599. // All relevant data is in Properties, Labels, Cost, etc.
  600. case *opencost.Cloud:
  601. mcpAsset.Credit = a.Credit
  602. case *opencost.ClusterManagement:
  603. // ClusterManagement assets have no specific fields beyond the base asset structure
  604. // All relevant data is in Properties, Labels, Cost, etc.
  605. }
  606. mcpSet.Assets = append(mcpSet.Assets, mcpAsset)
  607. }
  608. mcpAssets["assets"] = mcpSet
  609. return &AssetResponse{
  610. Assets: mcpAssets,
  611. }
  612. }
  613. // QueryCloudCosts translates an MCP query into a CloudCost repository query and transforms the result.
  614. func (s *MCPServer) QueryCloudCosts(query *OpenCostQueryRequest) (*CloudCostResponse, error) {
  615. // 1. Check if cloud cost querier is available
  616. if s.cloudQuerier == nil {
  617. return nil, fmt.Errorf("cloud cost querier not configured - check cloud-integration.json file")
  618. }
  619. // 2. Parse Window
  620. window, err := opencost.ParseWindowWithOffset(query.Window, 0) // 0 offset for UTC
  621. if err != nil {
  622. return nil, fmt.Errorf("failed to parse window '%s': %w", query.Window, err)
  623. }
  624. // 3. Build query request
  625. request := cloudcost.QueryRequest{
  626. Start: *window.Start(),
  627. End: *window.End(),
  628. Filter: nil, // Will be set from CloudCostParams if provided
  629. }
  630. // 4. Apply filtering and aggregation from CloudCostParams
  631. if query.CloudCostParams != nil {
  632. request = s.buildCloudCostQueryRequest(request, query.CloudCostParams)
  633. }
  634. // 5. Query the repository (this handles multiple cloud providers automatically)
  635. ccsr, err := s.cloudQuerier.Query(context.TODO(), request)
  636. if err != nil {
  637. return nil, fmt.Errorf("failed to query cloud costs: %w", err)
  638. }
  639. // 6. Transform Response
  640. return transformCloudCostSetRange(ccsr), nil
  641. }
  642. // buildCloudCostQueryRequest builds a QueryRequest from CloudCostParams
  643. func (s *MCPServer) buildCloudCostQueryRequest(request cloudcost.QueryRequest, params *CloudCostQuery) cloudcost.QueryRequest {
  644. // Set aggregation
  645. if params.Aggregate != "" {
  646. aggregateBy := strings.Split(params.Aggregate, ",")
  647. request.AggregateBy = aggregateBy
  648. }
  649. // Set accumulation
  650. if params.Accumulate != "" {
  651. request.Accumulate = opencost.ParseAccumulate(params.Accumulate)
  652. }
  653. // Build filter from individual parameters or filter string
  654. var filter filter.Filter
  655. var err error
  656. if params.Filter != "" {
  657. // Parse the filter string directly
  658. parser := cloudcostfilter.NewCloudCostFilterParser()
  659. filter, err = parser.Parse(params.Filter)
  660. if err != nil {
  661. // Log error but continue without filter rather than failing the entire request
  662. fmt.Printf("Warning: failed to parse filter string '%s': %v\n", params.Filter, err)
  663. }
  664. } else {
  665. // Build filter from individual parameters
  666. filter = s.buildFilterFromParams(params)
  667. }
  668. request.Filter = filter
  669. return request
  670. }
  671. // buildFilterFromParams creates a filter from individual CloudCostQuery parameters
  672. func (s *MCPServer) buildFilterFromParams(params *CloudCostQuery) filter.Filter {
  673. var filterParts []string
  674. // Add provider filter
  675. if params.Provider != "" {
  676. filterParts = append(filterParts, fmt.Sprintf(`provider:"%s"`, params.Provider))
  677. }
  678. // Add providerID filter
  679. if params.ProviderID != "" {
  680. filterParts = append(filterParts, fmt.Sprintf(`providerID:"%s"`, params.ProviderID))
  681. }
  682. // Add service filter
  683. if params.Service != "" {
  684. filterParts = append(filterParts, fmt.Sprintf(`service:"%s"`, params.Service))
  685. }
  686. // Add category filter
  687. if params.Category != "" {
  688. filterParts = append(filterParts, fmt.Sprintf(`category:"%s"`, params.Category))
  689. }
  690. // Region is intentionally not supported here
  691. // Add account filter (maps to accountID)
  692. if params.AccountID != "" {
  693. filterParts = append(filterParts, fmt.Sprintf(`accountID:"%s"`, params.AccountID))
  694. }
  695. // Add invoiceEntityID filter
  696. if params.InvoiceEntityID != "" {
  697. filterParts = append(filterParts, fmt.Sprintf(`invoiceEntityID:"%s"`, params.InvoiceEntityID))
  698. }
  699. // Add label filters (label[key]:"value")
  700. if len(params.Labels) > 0 {
  701. for k, v := range params.Labels {
  702. if k == "" {
  703. continue
  704. }
  705. filterParts = append(filterParts, fmt.Sprintf(`label[%s]:"%s"`, k, v))
  706. }
  707. }
  708. // If no filters specified, return nil
  709. if len(filterParts) == 0 {
  710. return nil
  711. }
  712. // Combine all filter parts with AND logic (parser expects 'and')
  713. filterString := strings.Join(filterParts, " and ")
  714. // Parse the combined filter string
  715. parser := cloudcostfilter.NewCloudCostFilterParser()
  716. filter, err := parser.Parse(filterString)
  717. if err != nil {
  718. // Log error but return nil rather than failing
  719. fmt.Printf("Warning: failed to parse combined filter '%s': %v\n", filterString, err)
  720. return nil
  721. }
  722. return filter
  723. }
  724. // transformCloudCostSetRange converts a opencost.CloudCostSetRange into the MCP's CloudCostResponse format.
  725. func transformCloudCostSetRange(ccsr *opencost.CloudCostSetRange) *CloudCostResponse {
  726. if ccsr == nil || len(ccsr.CloudCostSets) == 0 {
  727. return &CloudCostResponse{
  728. CloudCosts: make(map[string]*CloudCostSet),
  729. Summary: &CloudCostSummary{
  730. TotalNetCost: 0,
  731. },
  732. }
  733. }
  734. mcpCloudCosts := make(map[string]*CloudCostSet)
  735. var totalNetCost, totalAmortizedCost, totalInvoicedCost float64
  736. providerBreakdown := make(map[string]float64)
  737. serviceBreakdown := make(map[string]float64)
  738. regionBreakdown := make(map[string]float64)
  739. // Process each cloud cost set in the range
  740. for i, ccSet := range ccsr.CloudCostSets {
  741. if ccSet == nil {
  742. continue
  743. }
  744. setName := fmt.Sprintf("cloudcosts_%d", i)
  745. mcpSet := &CloudCostSet{
  746. Name: setName,
  747. CloudCosts: []*CloudCost{},
  748. AggregationProperties: ccSet.AggregationProperties,
  749. Window: &TimeWindow{
  750. Start: *ccSet.Window.Start(),
  751. End: *ccSet.Window.End(),
  752. },
  753. }
  754. // Convert each cloud cost item
  755. for _, item := range ccSet.CloudCosts {
  756. if item == nil {
  757. continue
  758. }
  759. mcpCC := &CloudCost{
  760. Properties: CloudCostProperties{
  761. ProviderID: item.Properties.ProviderID,
  762. Provider: item.Properties.Provider,
  763. AccountID: item.Properties.AccountID,
  764. AccountName: item.Properties.AccountName,
  765. InvoiceEntityID: item.Properties.InvoiceEntityID,
  766. InvoiceEntityName: item.Properties.InvoiceEntityName,
  767. RegionID: item.Properties.RegionID,
  768. AvailabilityZone: item.Properties.AvailabilityZone,
  769. Service: item.Properties.Service,
  770. Category: item.Properties.Category,
  771. Labels: item.Properties.Labels,
  772. },
  773. Window: TimeWindow{
  774. Start: *item.Window.Start(),
  775. End: *item.Window.End(),
  776. },
  777. ListCost: CostMetric{
  778. Cost: item.ListCost.Cost,
  779. KubernetesPercent: item.ListCost.KubernetesPercent,
  780. },
  781. NetCost: CostMetric{
  782. Cost: item.NetCost.Cost,
  783. KubernetesPercent: item.NetCost.KubernetesPercent,
  784. },
  785. AmortizedNetCost: CostMetric{
  786. Cost: item.AmortizedNetCost.Cost,
  787. KubernetesPercent: item.AmortizedNetCost.KubernetesPercent,
  788. },
  789. InvoicedCost: CostMetric{
  790. Cost: item.InvoicedCost.Cost,
  791. KubernetesPercent: item.InvoicedCost.KubernetesPercent,
  792. },
  793. AmortizedCost: CostMetric{
  794. Cost: item.AmortizedCost.Cost,
  795. KubernetesPercent: item.AmortizedCost.KubernetesPercent,
  796. },
  797. }
  798. mcpSet.CloudCosts = append(mcpSet.CloudCosts, mcpCC)
  799. // Update summary totals
  800. totalNetCost += item.NetCost.Cost
  801. totalAmortizedCost += item.AmortizedNetCost.Cost
  802. totalInvoicedCost += item.InvoicedCost.Cost
  803. // Update breakdowns
  804. providerBreakdown[item.Properties.Provider] += item.NetCost.Cost
  805. serviceBreakdown[item.Properties.Service] += item.NetCost.Cost
  806. regionBreakdown[item.Properties.RegionID] += item.NetCost.Cost
  807. }
  808. mcpCloudCosts[setName] = mcpSet
  809. }
  810. // Calculate cost-weighted average Kubernetes percentage (by NetCost)
  811. var avgKubernetesPercent float64
  812. var numerator, denominator float64
  813. for _, ccSet := range ccsr.CloudCostSets {
  814. for _, item := range ccSet.CloudCosts {
  815. if item == nil {
  816. continue
  817. }
  818. cost := item.NetCost.Cost
  819. percent := item.NetCost.KubernetesPercent
  820. if cost <= 0 {
  821. continue
  822. }
  823. numerator += cost * percent
  824. denominator += cost
  825. }
  826. }
  827. if denominator > 0 {
  828. avgKubernetesPercent = numerator / denominator
  829. }
  830. summary := &CloudCostSummary{
  831. TotalNetCost: totalNetCost,
  832. TotalAmortizedCost: totalAmortizedCost,
  833. TotalInvoicedCost: totalInvoicedCost,
  834. KubernetesPercent: avgKubernetesPercent,
  835. ProviderBreakdown: providerBreakdown,
  836. ServiceBreakdown: serviceBreakdown,
  837. RegionBreakdown: regionBreakdown,
  838. }
  839. return &CloudCostResponse{
  840. CloudCosts: mcpCloudCosts,
  841. Summary: summary,
  842. }
  843. }
  844. // QueryEfficiency queries allocation data and computes efficiency metrics with recommendations.
  845. func (s *MCPServer) QueryEfficiency(query *OpenCostQueryRequest) (*EfficiencyResponse, error) {
  846. // 1. Parse Window
  847. window, err := opencost.ParseWindowWithOffset(query.Window, 0)
  848. if err != nil {
  849. return nil, fmt.Errorf("failed to parse window '%s': %w", query.Window, err)
  850. }
  851. // 2. Set default parameters
  852. var aggregateBy []string
  853. var filterString string
  854. var bufferMultiplier float64 = efficiencyBufferMultiplier // Default to 1.2 (20% headroom)
  855. // 3. Parse efficiency parameters if provided
  856. if query.EfficiencyParams != nil {
  857. // Parse aggregation properties (default to pod if not specified)
  858. if query.EfficiencyParams.Aggregate != "" {
  859. aggregateBy = strings.Split(query.EfficiencyParams.Aggregate, ",")
  860. } else {
  861. aggregateBy = []string{"pod"}
  862. }
  863. // Set filter string
  864. filterString = query.EfficiencyParams.Filter
  865. // Validate filter string if provided
  866. if filterString != "" {
  867. parser := allocation.NewAllocationFilterParser()
  868. _, err := parser.Parse(filterString)
  869. if err != nil {
  870. return nil, fmt.Errorf("invalid allocation filter '%s': %w", filterString, err)
  871. }
  872. }
  873. // Set buffer multiplier if provided, otherwise use default
  874. if query.EfficiencyParams.EfficiencyBufferMultiplier != nil {
  875. bufferMultiplier = *query.EfficiencyParams.EfficiencyBufferMultiplier
  876. }
  877. } else {
  878. // Default to pod-level aggregation
  879. aggregateBy = []string{"pod"}
  880. filterString = ""
  881. }
  882. // 4. Query allocations with the specified parameters
  883. // Use the entire window as step to get aggregated data
  884. step := window.Duration()
  885. asr, err := s.costModel.QueryAllocation(
  886. window,
  887. step,
  888. aggregateBy,
  889. false, // includeIdle
  890. false, // idleByNode
  891. false, // includeProportionalAssetResourceCosts
  892. false, // includeAggregatedMetadata
  893. false, // sharedLoadBalancer
  894. opencost.AccumulateOptionNone,
  895. false, // shareIdle
  896. filterString,
  897. )
  898. if err != nil {
  899. return nil, fmt.Errorf("failed to query allocations: %w", err)
  900. }
  901. // 5. Handle empty results
  902. if asr == nil || len(asr.Allocations) == 0 {
  903. return &EfficiencyResponse{
  904. Efficiencies: []*EfficiencyMetric{},
  905. }, nil
  906. }
  907. // 6. Compute efficiency metrics from allocations using concurrent processing
  908. var (
  909. mu sync.Mutex
  910. wg sync.WaitGroup
  911. efficiencies = make([]*EfficiencyMetric, 0)
  912. )
  913. // Process each allocation set (typically one per time window) concurrently
  914. for _, allocSet := range asr.Allocations {
  915. if allocSet == nil {
  916. continue
  917. }
  918. // Process this allocation set in a goroutine
  919. wg.Add(1)
  920. go func(allocSet *opencost.AllocationSet) {
  921. defer wg.Done()
  922. // Compute metrics for all allocations in this set
  923. localMetrics := make([]*EfficiencyMetric, 0, len(allocSet.Allocations))
  924. for _, alloc := range allocSet.Allocations {
  925. if metric := computeEfficiencyMetric(alloc, bufferMultiplier); metric != nil {
  926. localMetrics = append(localMetrics, metric)
  927. }
  928. }
  929. // Append results to shared slice (thread-safe)
  930. if len(localMetrics) > 0 {
  931. mu.Lock()
  932. efficiencies = append(efficiencies, localMetrics...)
  933. mu.Unlock()
  934. }
  935. }(allocSet)
  936. }
  937. // Wait for all goroutines to complete
  938. wg.Wait()
  939. return &EfficiencyResponse{
  940. Efficiencies: efficiencies,
  941. }, nil
  942. }
  943. // safeDiv performs division and returns 0 if denominator is 0.
  944. func safeDiv(numerator, denominator float64) float64 {
  945. if denominator == 0 {
  946. return 0
  947. }
  948. return numerator / denominator
  949. }
  950. // computeEfficiencyMetric calculates efficiency metrics for a single allocation.
  951. func computeEfficiencyMetric(alloc *opencost.Allocation, bufferMultiplier float64) *EfficiencyMetric {
  952. if alloc == nil {
  953. return nil
  954. }
  955. // Calculate time duration in hours
  956. hours := alloc.Minutes() / 60.0
  957. if hours <= 0 {
  958. return nil
  959. }
  960. // Get current usage (average over the period)
  961. cpuCoresUsed := alloc.CPUCoreHours / hours
  962. ramBytesUsed := alloc.RAMByteHours / hours
  963. // Get requested amounts
  964. cpuCoresRequested := alloc.CPUCoreRequestAverage
  965. ramBytesRequested := alloc.RAMBytesRequestAverage
  966. // Calculate current efficiency (will be 0 if no requests are set)
  967. cpuEfficiency := safeDiv(cpuCoresUsed, cpuCoresRequested)
  968. memoryEfficiency := safeDiv(ramBytesUsed, ramBytesRequested)
  969. // Calculate recommendations with buffer for headroom
  970. recommendedCPU := cpuCoresUsed * bufferMultiplier
  971. recommendedRAM := ramBytesUsed * bufferMultiplier
  972. // Ensure recommendations meet minimum thresholds
  973. if recommendedCPU < efficiencyMinCPU {
  974. recommendedCPU = efficiencyMinCPU
  975. }
  976. if recommendedRAM < efficiencyMinRAM {
  977. recommendedRAM = efficiencyMinRAM
  978. }
  979. // Calculate resulting efficiency after applying recommendations
  980. resultingCPUEff := safeDiv(cpuCoresUsed, recommendedCPU)
  981. resultingMemEff := safeDiv(ramBytesUsed, recommendedRAM)
  982. // Calculate cost per unit based on REQUESTED amounts (not used amounts)
  983. // This gives us the cost per core-hour or byte-hour that the cluster charges
  984. cpuCostPerCoreHour := safeDiv(alloc.CPUCost, cpuCoresRequested*hours)
  985. ramCostPerByteHour := safeDiv(alloc.RAMCost, ramBytesRequested*hours)
  986. // Current total cost
  987. currentTotalCost := alloc.TotalCost()
  988. // Estimate recommended cost based on recommended requests
  989. recommendedCPUCost := recommendedCPU * hours * cpuCostPerCoreHour
  990. recommendedRAMCost := recommendedRAM * hours * ramCostPerByteHour
  991. // Keep other costs the same (PV, network, shared, external, GPU)
  992. otherCosts := alloc.PVCost() + alloc.NetworkCost + alloc.SharedCost + alloc.ExternalCost + alloc.GPUCost
  993. recommendedTotalCost := recommendedCPUCost + recommendedRAMCost + otherCosts
  994. // Clamp recommended cost to avoid rounding issues making it higher than current
  995. if recommendedTotalCost > currentTotalCost && (recommendedTotalCost-currentTotalCost) < 0.0001 {
  996. recommendedTotalCost = currentTotalCost
  997. }
  998. // Calculate savings
  999. costSavings := currentTotalCost - recommendedTotalCost
  1000. costSavingsPercent := safeDiv(costSavings, currentTotalCost) * 100
  1001. return &EfficiencyMetric{
  1002. Name: alloc.Name,
  1003. CPUEfficiency: cpuEfficiency,
  1004. MemoryEfficiency: memoryEfficiency,
  1005. CPUCoresRequested: cpuCoresRequested,
  1006. CPUCoresUsed: cpuCoresUsed,
  1007. RAMBytesRequested: ramBytesRequested,
  1008. RAMBytesUsed: ramBytesUsed,
  1009. RecommendedCPURequest: recommendedCPU,
  1010. RecommendedRAMRequest: recommendedRAM,
  1011. ResultingCPUEfficiency: resultingCPUEff,
  1012. ResultingMemoryEfficiency: resultingMemEff,
  1013. CurrentTotalCost: currentTotalCost,
  1014. RecommendedCost: recommendedTotalCost,
  1015. CostSavings: costSavings,
  1016. CostSavingsPercent: costSavingsPercent,
  1017. EfficiencyBufferMultiplier: bufferMultiplier,
  1018. Start: alloc.Start,
  1019. End: alloc.End,
  1020. }
  1021. }