server.go 58 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661
  1. package mcp
  2. import (
  3. "context"
  4. "crypto/rand"
  5. "encoding/hex"
  6. "fmt"
  7. "sort"
  8. "strings"
  9. "sync"
  10. "time"
  11. "github.com/go-playground/validator/v10"
  12. "github.com/opencost/opencost/core/pkg/filter"
  13. "github.com/opencost/opencost/core/pkg/filter/allocation"
  14. cloudcostfilter "github.com/opencost/opencost/core/pkg/filter/cloudcost"
  15. "github.com/opencost/opencost/core/pkg/log"
  16. "github.com/opencost/opencost/core/pkg/opencost"
  17. models "github.com/opencost/opencost/pkg/cloud/models"
  18. "github.com/opencost/opencost/pkg/cloudcost"
  19. "github.com/opencost/opencost/pkg/costmodel"
  20. )
  21. // QueryType defines the type of query to be executed.
  22. type QueryType string
  23. const (
  24. AllocationQueryType QueryType = "allocation"
  25. AssetQueryType QueryType = "asset"
  26. CloudCostQueryType QueryType = "cloudcost"
  27. EfficiencyQueryType QueryType = "efficiency"
  28. RecommendationsQueryType QueryType = "recommendations"
  29. )
  30. // Efficiency calculation constants
  31. const (
  32. efficiencyBufferMultiplier = 1.2 // 20% headroom for stability
  33. efficiencyMinCPU = 0.001 // minimum CPU cores
  34. efficiencyMinRAM = 1024 * 1024 // 1 MB minimum RAM
  35. )
  36. // Recommendation thresholds
  37. const (
  38. // Idle detection thresholds
  39. idleCPUThreshold = 0.05 // <5% CPU usage considered idle
  40. idleMemoryThreshold = 0.05 // <5% memory usage considered idle
  41. // Oversized detection thresholds
  42. oversizedCPUThreshold = 0.3 // <30% CPU efficiency is oversized
  43. oversizedMemoryThreshold = 0.3 // <30% memory efficiency is oversized
  44. // Severely oversized threshold (for high priority)
  45. severelyOversizedThreshold = 0.1 // <10% efficiency is severely oversized
  46. // Underprovisioned detection thresholds
  47. underprovisionedCPUThreshold = 0.9 // >90% CPU efficiency may be underprovisioned
  48. underprovisionedMemoryThreshold = 0.9 // >90% memory efficiency may be underprovisioned
  49. // Minimum savings threshold for recommendations
  50. minSavingsThreshold = 0.01 // Minimum $0.01 savings to generate recommendation
  51. // Input validation bounds
  52. minBufferMultiplier = 1.0 // Minimum buffer multiplier (no buffer below 1.0)
  53. maxBufferMultiplier = 10.0 // Maximum buffer multiplier to prevent unrealistic recommendations
  54. maxTopN = 10000 // Maximum number of recommendations to return
  55. )
  56. // RecommendationType defines the type of cost recommendation
  57. type RecommendationType string
  58. const (
  59. RecommendationTypeIdle RecommendationType = "idle"
  60. RecommendationTypeOversized RecommendationType = "oversized"
  61. RecommendationTypeRightsize RecommendationType = "rightsize"
  62. RecommendationTypeUnderprovisioned RecommendationType = "underprovisioned"
  63. )
  64. // RecommendationPriority defines the priority level of a recommendation
  65. type RecommendationPriority string
  66. const (
  67. RecommendationPriorityHigh RecommendationPriority = "high"
  68. RecommendationPriorityMedium RecommendationPriority = "medium"
  69. RecommendationPriorityLow RecommendationPriority = "low"
  70. )
  71. // MCPRequest represents a single turn in a conversation with the OpenCost MCP server.
  72. type MCPRequest struct {
  73. SessionID string `json:"sessionId"`
  74. Query *OpenCostQueryRequest `json:"query"`
  75. }
  76. // MCPResponse is the response from the OpenCost MCP server for a single turn.
  77. type MCPResponse struct {
  78. Data interface{} `json:"data"`
  79. QueryInfo QueryMetadata `json:"queryInfo"`
  80. }
  81. // QueryMetadata contains metadata about the query execution.
  82. type QueryMetadata struct {
  83. QueryID string `json:"queryId"`
  84. Timestamp time.Time `json:"timestamp"`
  85. ProcessingTime time.Duration `json:"processingTime"`
  86. }
  87. // OpenCostQueryRequest provides a unified interface for all OpenCost query types.
  88. type OpenCostQueryRequest struct {
  89. QueryType QueryType `json:"queryType" validate:"required,oneof=allocation asset cloudcost efficiency recommendations"`
  90. Window string `json:"window" validate:"required"`
  91. AllocationParams *AllocationQuery `json:"allocationParams,omitempty"`
  92. AssetParams *AssetQuery `json:"assetParams,omitempty"`
  93. CloudCostParams *CloudCostQuery `json:"cloudCostParams,omitempty"`
  94. EfficiencyParams *EfficiencyQuery `json:"efficiencyParams,omitempty"`
  95. RecommendationsParams *RecommendationsQuery `json:"recommendationsParams,omitempty"`
  96. }
  97. // AllocationQuery contains the parameters for an allocation query.
  98. type AllocationQuery struct {
  99. Step time.Duration `json:"step,omitempty"`
  100. Accumulate bool `json:"accumulate,omitempty"`
  101. ShareIdle bool `json:"shareIdle,omitempty"`
  102. Aggregate string `json:"aggregate,omitempty"`
  103. IncludeIdle bool `json:"includeIdle,omitempty"`
  104. IdleByNode bool `json:"idleByNode,omitempty"`
  105. IncludeProportionalAssetResourceCosts bool `json:"includeProportionalAssetResourceCosts,omitempty"`
  106. IncludeAggregatedMetadata bool `json:"includeAggregatedMetadata,omitempty"`
  107. ShareLB bool `json:"sharelb,omitempty"`
  108. Filter string `json:"filter,omitempty"` // Filter expression for allocations (e.g., "cluster:production", "namespace:kube-system")
  109. }
  110. // AssetQuery contains the parameters for an asset query.
  111. type AssetQuery struct {
  112. // Currently no specific parameters needed for asset queries as it only takes window as parameter
  113. }
  114. // CloudCostQuery contains the parameters for a cloud cost query.
  115. type CloudCostQuery struct {
  116. Aggregate string `json:"aggregate,omitempty"` // Comma-separated list of aggregation properties
  117. Accumulate string `json:"accumulate,omitempty"` // e.g., "week", "day", "month"
  118. Filter string `json:"filter,omitempty"` // Filter expression for cloud costs
  119. Provider string `json:"provider,omitempty"` // Cloud provider filter (aws, gcp, azure, etc.)
  120. Service string `json:"service,omitempty"` // Service filter (ec2, s3, compute, etc.)
  121. Category string `json:"category,omitempty"` // Category filter (compute, storage, network, etc.)
  122. Region string `json:"region,omitempty"` // Region filter
  123. // Additional explicit fields for filtering
  124. AccountID string `json:"accountID,omitempty"` // Alias of Account; maps to accountID
  125. InvoiceEntityID string `json:"invoiceEntityID,omitempty"` // Invoice entity ID filter
  126. ProviderID string `json:"providerID,omitempty"` // Cloud provider resource ID filter
  127. Labels map[string]string `json:"labels,omitempty"` // Label filters (key->value)
  128. }
  129. // EfficiencyQuery contains the parameters for an efficiency query.
  130. type EfficiencyQuery struct {
  131. Aggregate string `json:"aggregate,omitempty"` // Aggregation properties (e.g., "pod", "namespace", "controller")
  132. Filter string `json:"filter,omitempty"` // Filter expression for allocations (same as AllocationQuery)
  133. EfficiencyBufferMultiplier *float64 `json:"efficiencyBufferMultiplier,omitempty"` // Buffer multiplier for recommendations (default: 1.2 for 20% headroom)
  134. }
  135. // RecommendationsQuery contains the parameters for a cost recommendations query.
  136. type RecommendationsQuery struct {
  137. Aggregate string `json:"aggregate,omitempty"` // Aggregation level (e.g., "pod", "namespace", "controller")
  138. Filter string `json:"filter,omitempty"` // Filter expression for allocations
  139. BufferMultiplier *float64 `json:"bufferMultiplier,omitempty"` // Buffer multiplier for sizing recommendations (default: 1.2)
  140. MinSavings *float64 `json:"minSavings,omitempty"` // Minimum savings threshold to include recommendation (default: 0.01)
  141. IncludeIdle bool `json:"includeIdle,omitempty"` // Include idle resource detection (default: true)
  142. IncludeOversized bool `json:"includeOversized,omitempty"` // Include oversized resource detection (default: true)
  143. IncludeRightsize bool `json:"includeRightsize,omitempty"` // Include rightsizing recommendations (default: true)
  144. TopN *int `json:"topN,omitempty"` // Limit to top N recommendations by savings (default: no limit)
  145. }
  146. // AllocationResponse represents the allocation data returned to the AI agent.
  147. type AllocationResponse struct {
  148. // The allocation data, as a map of allocation sets.
  149. Allocations map[string]*AllocationSet `json:"allocations"`
  150. }
  151. // AllocationSet represents a set of allocation data.
  152. type AllocationSet struct {
  153. // The name of the allocation set.
  154. Name string `json:"name"`
  155. Properties map[string]string `json:"properties"`
  156. Allocations []*Allocation `json:"allocations"`
  157. }
  158. // TotalCost calculates the total cost of all allocations in the set.
  159. func (as *AllocationSet) TotalCost() float64 {
  160. var total float64
  161. for _, alloc := range as.Allocations {
  162. total += alloc.TotalCost
  163. }
  164. return total
  165. }
  166. // Allocation represents a single allocation data point.
  167. type Allocation struct {
  168. Name string `json:"name"` // Allocation key (namespace, cluster, etc.)
  169. CPUCost float64 `json:"cpuCost"` // Cost of CPU usage
  170. GPUCost float64 `json:"gpuCost"` // Cost of GPU usage
  171. RAMCost float64 `json:"ramCost"` // Cost of memory usage
  172. PVCost float64 `json:"pvCost"` // Cost of persistent volumes
  173. NetworkCost float64 `json:"networkCost"` // Cost of network usage
  174. SharedCost float64 `json:"sharedCost"` // Shared/unallocated costs assigned here
  175. ExternalCost float64 `json:"externalCost"` // External costs (cloud services, etc.)
  176. TotalCost float64 `json:"totalCost"` // Sum of all costs above
  177. CPUCoreHours float64 `json:"cpuCoreHours"` // Usage metrics: CPU core-hours
  178. RAMByteHours float64 `json:"ramByteHours"` // Usage metrics: RAM byte-hours
  179. GPUHours float64 `json:"gpuHours"` // Usage metrics: GPU-hours
  180. PVByteHours float64 `json:"pvByteHours"` // Usage metrics: PV byte-hours
  181. Start time.Time `json:"start"` // Start timestamp for this allocation
  182. End time.Time `json:"end"` // End timestamp for this allocation
  183. }
  184. // AssetResponse represents the asset data returned to the AI agent.
  185. type AssetResponse struct {
  186. // The asset data, as a map of asset sets.
  187. Assets map[string]*AssetSet `json:"assets"`
  188. }
  189. // AssetSet represents a set of asset data.
  190. type AssetSet struct {
  191. // The name of the asset set.
  192. Name string `json:"name"`
  193. // The asset data for the set.
  194. Assets []*Asset `json:"assets"`
  195. }
  196. // Asset represents a single asset data point.
  197. type Asset struct {
  198. Type string `json:"type"`
  199. Properties AssetProperties `json:"properties"`
  200. Labels map[string]string `json:"labels,omitempty"`
  201. Start time.Time `json:"start"`
  202. End time.Time `json:"end"`
  203. Minutes float64 `json:"minutes"`
  204. Adjustment float64 `json:"adjustment"`
  205. TotalCost float64 `json:"totalCost"`
  206. // Disk-specific fields
  207. ByteHours float64 `json:"byteHours,omitempty"`
  208. ByteHoursUsed *float64 `json:"byteHoursUsed,omitempty"`
  209. ByteUsageMax *float64 `json:"byteUsageMax,omitempty"`
  210. StorageClass string `json:"storageClass,omitempty"`
  211. VolumeName string `json:"volumeName,omitempty"`
  212. ClaimName string `json:"claimName,omitempty"`
  213. ClaimNamespace string `json:"claimNamespace,omitempty"`
  214. Local float64 `json:"local,omitempty"`
  215. // Node-specific fields
  216. NodeType string `json:"nodeType,omitempty"`
  217. CPUCoreHours float64 `json:"cpuCoreHours,omitempty"`
  218. RAMByteHours float64 `json:"ramByteHours,omitempty"`
  219. GPUHours float64 `json:"gpuHours,omitempty"`
  220. GPUCount float64 `json:"gpuCount,omitempty"`
  221. CPUCost float64 `json:"cpuCost,omitempty"`
  222. GPUCost float64 `json:"gpuCost,omitempty"`
  223. RAMCost float64 `json:"ramCost,omitempty"`
  224. Discount float64 `json:"discount,omitempty"`
  225. Preemptible float64 `json:"preemptible,omitempty"`
  226. // Breakdown fields (can be used for different types)
  227. Breakdown *AssetBreakdown `json:"breakdown,omitempty"`
  228. CPUBreakdown *AssetBreakdown `json:"cpuBreakdown,omitempty"`
  229. RAMBreakdown *AssetBreakdown `json:"ramBreakdown,omitempty"`
  230. // Overhead (Node-specific)
  231. Overhead *NodeOverhead `json:"overhead,omitempty"`
  232. // LoadBalancer-specific fields
  233. Private bool `json:"private,omitempty"`
  234. Ip string `json:"ip,omitempty"`
  235. // Cloud-specific fields
  236. Credit float64 `json:"credit,omitempty"`
  237. }
  238. // NodeOverhead represents node overhead information
  239. type NodeOverhead struct {
  240. RamOverheadFraction float64 `json:"ramOverheadFraction"`
  241. CpuOverheadFraction float64 `json:"cpuOverheadFraction"`
  242. OverheadCostFraction float64 `json:"overheadCostFraction"`
  243. }
  244. type AssetProperties struct {
  245. Category string `json:"category,omitempty"`
  246. Provider string `json:"provider,omitempty"`
  247. Account string `json:"account,omitempty"`
  248. Project string `json:"project,omitempty"`
  249. Service string `json:"service,omitempty"`
  250. Cluster string `json:"cluster,omitempty"`
  251. Name string `json:"name,omitempty"`
  252. ProviderID string `json:"providerID,omitempty"`
  253. }
  254. type AssetBreakdown struct {
  255. Idle float64 `json:"idle"`
  256. Other float64 `json:"other"`
  257. System float64 `json:"system"`
  258. User float64 `json:"user"`
  259. }
  260. // CloudCostResponse represents the cloud cost data returned to the AI agent.
  261. type CloudCostResponse struct {
  262. // The cloud cost data, as a map of cloud cost sets.
  263. CloudCosts map[string]*CloudCostSet `json:"cloudCosts"`
  264. // Summary information
  265. Summary *CloudCostSummary `json:"summary,omitempty"`
  266. }
  267. // CloudCostSummary provides summary information about cloud costs
  268. type CloudCostSummary struct {
  269. TotalNetCost float64 `json:"totalNetCost"`
  270. TotalAmortizedCost float64 `json:"totalAmortizedCost"`
  271. TotalInvoicedCost float64 `json:"totalInvoicedCost"`
  272. KubernetesPercent float64 `json:"kubernetesPercent"`
  273. ProviderBreakdown map[string]float64 `json:"providerBreakdown,omitempty"`
  274. ServiceBreakdown map[string]float64 `json:"serviceBreakdown,omitempty"`
  275. RegionBreakdown map[string]float64 `json:"regionBreakdown,omitempty"`
  276. }
  277. // CloudCostSet represents a set of cloud cost data.
  278. type CloudCostSet struct {
  279. // The name of the cloud cost set.
  280. Name string `json:"name"`
  281. // The cloud cost data for the set.
  282. CloudCosts []*CloudCost `json:"cloudCosts"`
  283. // Aggregation information
  284. AggregationProperties []string `json:"aggregationProperties,omitempty"`
  285. // Time window
  286. Window *TimeWindow `json:"window,omitempty"`
  287. }
  288. // TimeWindow represents a time range
  289. type TimeWindow struct {
  290. Start time.Time `json:"start"`
  291. End time.Time `json:"end"`
  292. }
  293. // CloudCostProperties defines the properties of a cloud cost item.
  294. type CloudCostProperties struct {
  295. ProviderID string `json:"providerID,omitempty"`
  296. Provider string `json:"provider,omitempty"`
  297. AccountID string `json:"accountID,omitempty"`
  298. AccountName string `json:"accountName,omitempty"`
  299. InvoiceEntityID string `json:"invoiceEntityID,omitempty"`
  300. InvoiceEntityName string `json:"invoiceEntityName,omitempty"`
  301. RegionID string `json:"regionID,omitempty"`
  302. AvailabilityZone string `json:"availabilityZone,omitempty"`
  303. Service string `json:"service,omitempty"`
  304. Category string `json:"category,omitempty"`
  305. Labels map[string]string `json:"labels,omitempty"`
  306. }
  307. // CloudCost represents a single cloud cost data point.
  308. type CloudCost struct {
  309. Properties CloudCostProperties `json:"properties"`
  310. Window TimeWindow `json:"window"`
  311. ListCost CostMetric `json:"listCost"`
  312. NetCost CostMetric `json:"netCost"`
  313. AmortizedNetCost CostMetric `json:"amortizedNetCost"`
  314. InvoicedCost CostMetric `json:"invoicedCost"`
  315. AmortizedCost CostMetric `json:"amortizedCost"`
  316. }
  317. // CostMetric represents a cost value with Kubernetes percentage
  318. type CostMetric struct {
  319. Cost float64 `json:"cost"`
  320. KubernetesPercent float64 `json:"kubernetesPercent"`
  321. }
  322. // EfficiencyResponse represents the efficiency data returned to the AI agent.
  323. type EfficiencyResponse struct {
  324. Efficiencies []*EfficiencyMetric `json:"efficiencies"`
  325. }
  326. // EfficiencyMetric represents efficiency data for a single pod/workload.
  327. type EfficiencyMetric struct {
  328. Name string `json:"name"` // Pod/namespace/controller name based on aggregation
  329. // Current state
  330. CPUEfficiency float64 `json:"cpuEfficiency"` // Usage / Request ratio (0-1+)
  331. MemoryEfficiency float64 `json:"memoryEfficiency"` // Usage / Request ratio (0-1+)
  332. // Current requests and usage
  333. CPUCoresRequested float64 `json:"cpuCoresRequested"`
  334. CPUCoresUsed float64 `json:"cpuCoresUsed"`
  335. RAMBytesRequested float64 `json:"ramBytesRequested"`
  336. RAMBytesUsed float64 `json:"ramBytesUsed"`
  337. // Recommendations (based on actual usage with buffer)
  338. RecommendedCPURequest float64 `json:"recommendedCpuRequest"` // Recommended CPU cores
  339. RecommendedRAMRequest float64 `json:"recommendedRamRequest"` // Recommended RAM bytes
  340. // Resulting efficiency after applying recommendations
  341. ResultingCPUEfficiency float64 `json:"resultingCpuEfficiency"`
  342. ResultingMemoryEfficiency float64 `json:"resultingMemoryEfficiency"`
  343. // Cost analysis
  344. CurrentTotalCost float64 `json:"currentTotalCost"` // Current total cost
  345. RecommendedCost float64 `json:"recommendedCost"` // Estimated cost with recommendations
  346. CostSavings float64 `json:"costSavings"` // Potential savings
  347. CostSavingsPercent float64 `json:"costSavingsPercent"` // Savings as percentage
  348. // Buffer multiplier used for recommendations
  349. EfficiencyBufferMultiplier float64 `json:"efficiencyBufferMultiplier"` // Buffer multiplier applied (e.g., 1.2 for 20% headroom)
  350. // Time window
  351. Start time.Time `json:"start"`
  352. End time.Time `json:"end"`
  353. }
  354. // RecommendationsResponse represents cost optimization recommendations returned to the AI agent.
  355. type RecommendationsResponse struct {
  356. Recommendations []*Recommendation `json:"recommendations"` // List of recommendations sorted by savings
  357. Summary *RecommendationsSummary `json:"summary"` // Summary of all recommendations
  358. Window *TimeWindow `json:"window"` // Time window analyzed
  359. }
  360. // RecommendationsSummary provides summary statistics for recommendations.
  361. type RecommendationsSummary struct {
  362. TotalRecommendations int `json:"totalRecommendations"` // Total number of recommendations
  363. TotalPotentialSavings float64 `json:"totalPotentialSavings"` // Sum of all potential savings
  364. ByType map[string]int `json:"byType"` // Count by recommendation type
  365. ByPriority map[string]int `json:"byPriority"` // Count by priority level
  366. IdleResourceCount int `json:"idleResourceCount"` // Number of idle resources identified
  367. OversizedCount int `json:"oversizedCount"` // Number of oversized resources
  368. RightsizeCount int `json:"rightsizeCount"` // Number of rightsizing opportunities
  369. }
  370. // Recommendation represents a single cost optimization recommendation.
  371. type Recommendation struct {
  372. ID string `json:"id"` // Unique identifier for the recommendation
  373. Type RecommendationType `json:"type"` // Type of recommendation (idle, oversized, rightsize)
  374. Priority RecommendationPriority `json:"priority"` // Priority level (high, medium, low)
  375. ResourceName string `json:"resourceName"` // Name of the resource (pod, namespace, etc.)
  376. Description string `json:"description"` // Human-readable description of the recommendation
  377. Action string `json:"action"` // Recommended action to take
  378. // Current state
  379. CurrentCPURequest float64 `json:"currentCpuRequest"` // Current CPU request in cores
  380. CurrentRAMRequest float64 `json:"currentRamRequest"` // Current RAM request in bytes
  381. CurrentCPUUsage float64 `json:"currentCpuUsage"` // Current CPU usage in cores
  382. CurrentRAMUsage float64 `json:"currentRamUsage"` // Current RAM usage in bytes
  383. CurrentCost float64 `json:"currentCost"` // Current cost
  384. // Efficiency metrics
  385. CPUEfficiency float64 `json:"cpuEfficiency"` // Current CPU efficiency (0-1+)
  386. MemoryEfficiency float64 `json:"memoryEfficiency"` // Current memory efficiency (0-1+)
  387. // Recommendation details
  388. RecommendedCPURequest float64 `json:"recommendedCpuRequest"` // Recommended CPU request
  389. RecommendedRAMRequest float64 `json:"recommendedRamRequest"` // Recommended RAM request
  390. RecommendedCost float64 `json:"recommendedCost"` // Estimated cost after optimization
  391. // Savings analysis
  392. EstimatedSavings float64 `json:"estimatedSavings"` // Estimated cost savings
  393. EstimatedSavingsPercent float64 `json:"estimatedSavingsPercent"` // Savings as percentage
  394. // Time window
  395. Start time.Time `json:"start"`
  396. End time.Time `json:"end"`
  397. }
  398. // MCPServer holds the dependencies for the MCP API server.
  399. type MCPServer struct {
  400. costModel *costmodel.CostModel
  401. provider models.Provider
  402. cloudQuerier cloudcost.Querier
  403. }
  404. // NewMCPServer creates a new MCP Server.
  405. func NewMCPServer(costModel *costmodel.CostModel, provider models.Provider, cloudQuerier cloudcost.Querier) *MCPServer {
  406. return &MCPServer{
  407. costModel: costModel,
  408. provider: provider,
  409. cloudQuerier: cloudQuerier,
  410. }
  411. }
  412. // ProcessMCPRequest processes an MCP request and returns an MCP response.
  413. func (s *MCPServer) ProcessMCPRequest(request *MCPRequest) (*MCPResponse, error) {
  414. // 1. Validate Request
  415. if err := validate.Struct(request); err != nil {
  416. return nil, fmt.Errorf("validation failed: %w", err)
  417. }
  418. // 2. Query Dispatching
  419. var data interface{}
  420. var err error
  421. queryStart := time.Now()
  422. switch request.Query.QueryType {
  423. case AllocationQueryType:
  424. data, err = s.QueryAllocations(request.Query)
  425. case AssetQueryType:
  426. data, err = s.QueryAssets(request.Query)
  427. case CloudCostQueryType:
  428. data, err = s.QueryCloudCosts(request.Query)
  429. case EfficiencyQueryType:
  430. data, err = s.QueryEfficiency(request.Query)
  431. case RecommendationsQueryType:
  432. data, err = s.QueryRecommendations(request.Query)
  433. default:
  434. return nil, fmt.Errorf("unsupported query type: %s", request.Query.QueryType)
  435. }
  436. if err != nil {
  437. // Handle error appropriately, maybe return a JSON-RPC error response
  438. return nil, err
  439. }
  440. processingTime := time.Since(queryStart)
  441. // 3. Construct Final Response
  442. mcpResponse := &MCPResponse{
  443. Data: data,
  444. QueryInfo: QueryMetadata{
  445. QueryID: generateQueryID(),
  446. Timestamp: time.Now(),
  447. ProcessingTime: processingTime,
  448. },
  449. }
  450. return mcpResponse, nil
  451. }
  452. // validate is the singleton validator instance.
  453. var validate = validator.New()
  454. func generateQueryID() string {
  455. bytes := make([]byte, 8) // 16 hex characters
  456. if _, err := rand.Read(bytes); err != nil {
  457. // Fallback to timestamp-based ID if crypto/rand fails
  458. return fmt.Sprintf("query-%d", time.Now().UnixNano())
  459. }
  460. return fmt.Sprintf("query-%s", hex.EncodeToString(bytes))
  461. }
  462. func (s *MCPServer) QueryAllocations(query *OpenCostQueryRequest) (*AllocationResponse, error) {
  463. // 1. Parse Window
  464. window, err := opencost.ParseWindowWithOffset(query.Window, 0) // 0 offset for UTC
  465. if err != nil {
  466. return nil, fmt.Errorf("failed to parse window '%s': %w", query.Window, err)
  467. }
  468. // 2. Set default parameters
  469. var step time.Duration
  470. var aggregateBy []string
  471. var includeIdle, idleByNode, includeProportionalAssetResourceCosts, includeAggregatedMetadata, sharedLoadBalancer, shareIdle bool
  472. var accumulateBy opencost.AccumulateOption
  473. var filterString string
  474. // 3. Parse allocation parameters if provided
  475. if query.AllocationParams != nil {
  476. // Set step duration (default to window duration if not specified)
  477. if query.AllocationParams.Step > 0 {
  478. step = query.AllocationParams.Step
  479. } else {
  480. step = window.Duration()
  481. }
  482. // Parse aggregation properties
  483. if query.AllocationParams.Aggregate != "" {
  484. aggregateBy = strings.Split(query.AllocationParams.Aggregate, ",")
  485. }
  486. // Set boolean parameters
  487. includeIdle = query.AllocationParams.IncludeIdle
  488. idleByNode = query.AllocationParams.IdleByNode
  489. includeProportionalAssetResourceCosts = query.AllocationParams.IncludeProportionalAssetResourceCosts
  490. includeAggregatedMetadata = query.AllocationParams.IncludeAggregatedMetadata
  491. sharedLoadBalancer = query.AllocationParams.ShareLB
  492. shareIdle = query.AllocationParams.ShareIdle
  493. // Set filter string
  494. filterString = query.AllocationParams.Filter
  495. // Validate filter string if provided
  496. if filterString != "" {
  497. parser := allocation.NewAllocationFilterParser()
  498. _, err := parser.Parse(filterString)
  499. if err != nil {
  500. return nil, fmt.Errorf("invalid allocation filter '%s': %w", filterString, err)
  501. }
  502. }
  503. // Set accumulation option
  504. if query.AllocationParams.Accumulate {
  505. accumulateBy = opencost.AccumulateOptionAll
  506. } else {
  507. accumulateBy = opencost.AccumulateOptionNone
  508. }
  509. } else {
  510. // Default values when no parameters provided
  511. step = window.Duration()
  512. accumulateBy = opencost.AccumulateOptionNone
  513. filterString = ""
  514. }
  515. // 4. Call the existing QueryAllocation function with all parameters
  516. asr, err := s.costModel.QueryAllocation(
  517. window,
  518. step,
  519. aggregateBy,
  520. includeIdle,
  521. idleByNode,
  522. includeProportionalAssetResourceCosts,
  523. includeAggregatedMetadata,
  524. sharedLoadBalancer,
  525. accumulateBy,
  526. shareIdle,
  527. filterString,
  528. )
  529. if err != nil {
  530. return nil, fmt.Errorf("failed to query allocations: %w", err)
  531. }
  532. // 5. Handle the AllocationSetRange result
  533. if asr == nil || len(asr.Allocations) == 0 {
  534. return &AllocationResponse{
  535. Allocations: make(map[string]*AllocationSet),
  536. }, nil
  537. }
  538. // 6. Transform the result to MCP format
  539. // If we have multiple sets, we'll combine them or return the first one
  540. // For now, let's return the first allocation set
  541. firstSet := asr.Allocations[0]
  542. return transformAllocationSet(firstSet), nil
  543. }
  544. // transformAllocationSet converts an opencost.AllocationSet into the MCP's AllocationResponse format.
  545. func transformAllocationSet(allocSet *opencost.AllocationSet) *AllocationResponse {
  546. if allocSet == nil {
  547. return &AllocationResponse{Allocations: make(map[string]*AllocationSet)}
  548. }
  549. mcpAllocations := make(map[string]*AllocationSet)
  550. // Create a single set for all allocations
  551. mcpSet := &AllocationSet{
  552. Name: "allocations",
  553. Allocations: []*Allocation{},
  554. }
  555. // Convert each allocation
  556. for _, alloc := range allocSet.Allocations {
  557. if alloc == nil {
  558. continue
  559. }
  560. mcpAlloc := &Allocation{
  561. Name: alloc.Name,
  562. CPUCost: alloc.CPUCost,
  563. GPUCost: alloc.GPUCost,
  564. RAMCost: alloc.RAMCost,
  565. PVCost: alloc.PVCost(), // Call the method
  566. NetworkCost: alloc.NetworkCost,
  567. SharedCost: alloc.SharedCost,
  568. ExternalCost: alloc.ExternalCost,
  569. TotalCost: alloc.TotalCost(),
  570. CPUCoreHours: alloc.CPUCoreHours,
  571. RAMByteHours: alloc.RAMByteHours,
  572. GPUHours: alloc.GPUHours,
  573. PVByteHours: alloc.PVBytes(), // Use the method directly
  574. Start: alloc.Start,
  575. End: alloc.End,
  576. }
  577. mcpSet.Allocations = append(mcpSet.Allocations, mcpAlloc)
  578. }
  579. mcpAllocations["allocations"] = mcpSet
  580. return &AllocationResponse{
  581. Allocations: mcpAllocations,
  582. }
  583. }
  584. func (s *MCPServer) QueryAssets(query *OpenCostQueryRequest) (*AssetResponse, error) {
  585. // 1. Parse Window
  586. window, err := opencost.ParseWindowWithOffset(query.Window, 0) // 0 offset for UTC
  587. if err != nil {
  588. return nil, fmt.Errorf("failed to parse window '%s': %w", query.Window, err)
  589. }
  590. // 2. Set Query Options
  591. start := *window.Start()
  592. end := *window.End()
  593. // 3. Call CostModel to get the asset set
  594. assetSet, err := s.costModel.ComputeAssets(start, end)
  595. if err != nil {
  596. return nil, fmt.Errorf("failed to compute assets: %w", err)
  597. }
  598. // 4. Transform Response for the MCP API
  599. return transformAssetSet(assetSet), nil
  600. }
  601. // transformAssetSet converts a opencost.AssetSet into the MCP's AssetResponse format.
  602. func transformAssetSet(assetSet *opencost.AssetSet) *AssetResponse {
  603. if assetSet == nil {
  604. return &AssetResponse{Assets: make(map[string]*AssetSet)}
  605. }
  606. mcpAssets := make(map[string]*AssetSet)
  607. // Create a single set for all assets
  608. mcpSet := &AssetSet{
  609. Name: "assets",
  610. Assets: []*Asset{},
  611. }
  612. for _, asset := range assetSet.Assets {
  613. if asset == nil {
  614. continue
  615. }
  616. properties := asset.GetProperties()
  617. labels := asset.GetLabels()
  618. mcpAsset := &Asset{
  619. Type: asset.Type().String(),
  620. Properties: AssetProperties{
  621. Category: properties.Category,
  622. Provider: properties.Provider,
  623. Account: properties.Account,
  624. Project: properties.Project,
  625. Service: properties.Service,
  626. Cluster: properties.Cluster,
  627. Name: properties.Name,
  628. ProviderID: properties.ProviderID,
  629. },
  630. Labels: labels,
  631. Start: asset.GetStart(),
  632. End: asset.GetEnd(),
  633. Minutes: asset.Minutes(),
  634. Adjustment: asset.GetAdjustment(),
  635. TotalCost: asset.TotalCost(),
  636. }
  637. // Handle type-specific fields
  638. switch a := asset.(type) {
  639. case *opencost.Disk:
  640. mcpAsset.ByteHours = a.ByteHours
  641. mcpAsset.ByteHoursUsed = a.ByteHoursUsed
  642. mcpAsset.ByteUsageMax = a.ByteUsageMax
  643. mcpAsset.StorageClass = a.StorageClass
  644. mcpAsset.VolumeName = a.VolumeName
  645. mcpAsset.ClaimName = a.ClaimName
  646. mcpAsset.ClaimNamespace = a.ClaimNamespace
  647. mcpAsset.Local = a.Local
  648. if a.Breakdown != nil {
  649. mcpAsset.Breakdown = &AssetBreakdown{
  650. Idle: a.Breakdown.Idle,
  651. Other: a.Breakdown.Other,
  652. System: a.Breakdown.System,
  653. User: a.Breakdown.User,
  654. }
  655. }
  656. case *opencost.Node:
  657. mcpAsset.NodeType = a.NodeType
  658. mcpAsset.CPUCoreHours = a.CPUCoreHours
  659. mcpAsset.RAMByteHours = a.RAMByteHours
  660. mcpAsset.GPUHours = a.GPUHours
  661. mcpAsset.GPUCount = a.GPUCount
  662. mcpAsset.CPUCost = a.CPUCost
  663. mcpAsset.GPUCost = a.GPUCost
  664. mcpAsset.RAMCost = a.RAMCost
  665. mcpAsset.Discount = a.Discount
  666. mcpAsset.Preemptible = a.Preemptible
  667. if a.CPUBreakdown != nil {
  668. mcpAsset.CPUBreakdown = &AssetBreakdown{
  669. Idle: a.CPUBreakdown.Idle,
  670. Other: a.CPUBreakdown.Other,
  671. System: a.CPUBreakdown.System,
  672. User: a.CPUBreakdown.User,
  673. }
  674. }
  675. if a.RAMBreakdown != nil {
  676. mcpAsset.RAMBreakdown = &AssetBreakdown{
  677. Idle: a.RAMBreakdown.Idle,
  678. Other: a.RAMBreakdown.Other,
  679. System: a.RAMBreakdown.System,
  680. User: a.RAMBreakdown.User,
  681. }
  682. }
  683. if a.Overhead != nil {
  684. mcpAsset.Overhead = &NodeOverhead{
  685. RamOverheadFraction: a.Overhead.RamOverheadFraction,
  686. CpuOverheadFraction: a.Overhead.CpuOverheadFraction,
  687. OverheadCostFraction: a.Overhead.OverheadCostFraction,
  688. }
  689. }
  690. case *opencost.LoadBalancer:
  691. mcpAsset.Private = a.Private
  692. mcpAsset.Ip = a.Ip
  693. case *opencost.Network:
  694. // Network assets have no specific fields beyond the base asset structure
  695. // All relevant data is in Properties, Labels, Cost, etc.
  696. case *opencost.Cloud:
  697. mcpAsset.Credit = a.Credit
  698. case *opencost.ClusterManagement:
  699. // ClusterManagement assets have no specific fields beyond the base asset structure
  700. // All relevant data is in Properties, Labels, Cost, etc.
  701. }
  702. mcpSet.Assets = append(mcpSet.Assets, mcpAsset)
  703. }
  704. mcpAssets["assets"] = mcpSet
  705. return &AssetResponse{
  706. Assets: mcpAssets,
  707. }
  708. }
  709. // QueryCloudCosts translates an MCP query into a CloudCost repository query and transforms the result.
  710. func (s *MCPServer) QueryCloudCosts(query *OpenCostQueryRequest) (*CloudCostResponse, error) {
  711. // 1. Check if cloud cost querier is available
  712. if s.cloudQuerier == nil {
  713. return nil, fmt.Errorf("cloud cost querier not configured - check cloud-integration.json file")
  714. }
  715. // 2. Parse Window
  716. window, err := opencost.ParseWindowWithOffset(query.Window, 0) // 0 offset for UTC
  717. if err != nil {
  718. return nil, fmt.Errorf("failed to parse window '%s': %w", query.Window, err)
  719. }
  720. // 3. Build query request
  721. request := cloudcost.QueryRequest{
  722. Start: *window.Start(),
  723. End: *window.End(),
  724. Filter: nil, // Will be set from CloudCostParams if provided
  725. }
  726. // 4. Apply filtering and aggregation from CloudCostParams
  727. if query.CloudCostParams != nil {
  728. request = s.buildCloudCostQueryRequest(request, query.CloudCostParams)
  729. }
  730. // 5. Query the repository (this handles multiple cloud providers automatically)
  731. ccsr, err := s.cloudQuerier.Query(context.TODO(), request)
  732. if err != nil {
  733. return nil, fmt.Errorf("failed to query cloud costs: %w", err)
  734. }
  735. // 6. Transform Response
  736. return transformCloudCostSetRange(ccsr), nil
  737. }
  738. // buildCloudCostQueryRequest builds a QueryRequest from CloudCostParams
  739. func (s *MCPServer) buildCloudCostQueryRequest(request cloudcost.QueryRequest, params *CloudCostQuery) cloudcost.QueryRequest {
  740. // Set aggregation
  741. if params.Aggregate != "" {
  742. aggregateBy := strings.Split(params.Aggregate, ",")
  743. request.AggregateBy = aggregateBy
  744. }
  745. // Set accumulation
  746. if params.Accumulate != "" {
  747. request.Accumulate = opencost.ParseAccumulate(params.Accumulate)
  748. }
  749. // Build filter from individual parameters or filter string
  750. var filter filter.Filter
  751. var err error
  752. if params.Filter != "" {
  753. // Parse the filter string directly
  754. parser := cloudcostfilter.NewCloudCostFilterParser()
  755. filter, err = parser.Parse(params.Filter)
  756. if err != nil {
  757. // Log error but continue without filter rather than failing the entire request
  758. log.Warnf("failed to parse filter string '%s': %v", params.Filter, err)
  759. }
  760. } else {
  761. // Build filter from individual parameters
  762. filter = s.buildFilterFromParams(params)
  763. }
  764. request.Filter = filter
  765. return request
  766. }
  767. // buildFilterFromParams creates a filter from individual CloudCostQuery parameters
  768. func (s *MCPServer) buildFilterFromParams(params *CloudCostQuery) filter.Filter {
  769. var filterParts []string
  770. // Add provider filter
  771. if params.Provider != "" {
  772. filterParts = append(filterParts, fmt.Sprintf(`provider:"%s"`, params.Provider))
  773. }
  774. // Add providerID filter
  775. if params.ProviderID != "" {
  776. filterParts = append(filterParts, fmt.Sprintf(`providerID:"%s"`, params.ProviderID))
  777. }
  778. // Add service filter
  779. if params.Service != "" {
  780. filterParts = append(filterParts, fmt.Sprintf(`service:"%s"`, params.Service))
  781. }
  782. // Add category filter
  783. if params.Category != "" {
  784. filterParts = append(filterParts, fmt.Sprintf(`category:"%s"`, params.Category))
  785. }
  786. // Region is intentionally not supported here
  787. // Add account filter (maps to accountID)
  788. if params.AccountID != "" {
  789. filterParts = append(filterParts, fmt.Sprintf(`accountID:"%s"`, params.AccountID))
  790. }
  791. // Add invoiceEntityID filter
  792. if params.InvoiceEntityID != "" {
  793. filterParts = append(filterParts, fmt.Sprintf(`invoiceEntityID:"%s"`, params.InvoiceEntityID))
  794. }
  795. // Add label filters (label[key]:"value")
  796. if len(params.Labels) > 0 {
  797. for k, v := range params.Labels {
  798. if k == "" {
  799. continue
  800. }
  801. filterParts = append(filterParts, fmt.Sprintf(`label[%s]:"%s"`, k, v))
  802. }
  803. }
  804. // If no filters specified, return nil
  805. if len(filterParts) == 0 {
  806. return nil
  807. }
  808. // Combine all filter parts with AND logic (parser expects 'and')
  809. filterString := strings.Join(filterParts, " and ")
  810. // Parse the combined filter string
  811. parser := cloudcostfilter.NewCloudCostFilterParser()
  812. filter, err := parser.Parse(filterString)
  813. if err != nil {
  814. // Log error but return nil rather than failing
  815. log.Warnf("failed to parse combined filter '%s': %v", filterString, err)
  816. return nil
  817. }
  818. return filter
  819. }
  820. // transformCloudCostSetRange converts a opencost.CloudCostSetRange into the MCP's CloudCostResponse format.
  821. func transformCloudCostSetRange(ccsr *opencost.CloudCostSetRange) *CloudCostResponse {
  822. if ccsr == nil || len(ccsr.CloudCostSets) == 0 {
  823. return &CloudCostResponse{
  824. CloudCosts: make(map[string]*CloudCostSet),
  825. Summary: &CloudCostSummary{
  826. TotalNetCost: 0,
  827. },
  828. }
  829. }
  830. mcpCloudCosts := make(map[string]*CloudCostSet)
  831. var totalNetCost, totalAmortizedCost, totalInvoicedCost float64
  832. providerBreakdown := make(map[string]float64)
  833. serviceBreakdown := make(map[string]float64)
  834. regionBreakdown := make(map[string]float64)
  835. // Process each cloud cost set in the range
  836. for i, ccSet := range ccsr.CloudCostSets {
  837. if ccSet == nil {
  838. continue
  839. }
  840. setName := fmt.Sprintf("cloudcosts_%d", i)
  841. mcpSet := &CloudCostSet{
  842. Name: setName,
  843. CloudCosts: []*CloudCost{},
  844. AggregationProperties: ccSet.AggregationProperties,
  845. Window: &TimeWindow{
  846. Start: *ccSet.Window.Start(),
  847. End: *ccSet.Window.End(),
  848. },
  849. }
  850. // Convert each cloud cost item
  851. for _, item := range ccSet.CloudCosts {
  852. if item == nil {
  853. continue
  854. }
  855. mcpCC := &CloudCost{
  856. Properties: CloudCostProperties{
  857. ProviderID: item.Properties.ProviderID,
  858. Provider: item.Properties.Provider,
  859. AccountID: item.Properties.AccountID,
  860. AccountName: item.Properties.AccountName,
  861. InvoiceEntityID: item.Properties.InvoiceEntityID,
  862. InvoiceEntityName: item.Properties.InvoiceEntityName,
  863. RegionID: item.Properties.RegionID,
  864. AvailabilityZone: item.Properties.AvailabilityZone,
  865. Service: item.Properties.Service,
  866. Category: item.Properties.Category,
  867. Labels: item.Properties.Labels,
  868. },
  869. Window: TimeWindow{
  870. Start: *item.Window.Start(),
  871. End: *item.Window.End(),
  872. },
  873. ListCost: CostMetric{
  874. Cost: item.ListCost.Cost,
  875. KubernetesPercent: item.ListCost.KubernetesPercent,
  876. },
  877. NetCost: CostMetric{
  878. Cost: item.NetCost.Cost,
  879. KubernetesPercent: item.NetCost.KubernetesPercent,
  880. },
  881. AmortizedNetCost: CostMetric{
  882. Cost: item.AmortizedNetCost.Cost,
  883. KubernetesPercent: item.AmortizedNetCost.KubernetesPercent,
  884. },
  885. InvoicedCost: CostMetric{
  886. Cost: item.InvoicedCost.Cost,
  887. KubernetesPercent: item.InvoicedCost.KubernetesPercent,
  888. },
  889. AmortizedCost: CostMetric{
  890. Cost: item.AmortizedCost.Cost,
  891. KubernetesPercent: item.AmortizedCost.KubernetesPercent,
  892. },
  893. }
  894. mcpSet.CloudCosts = append(mcpSet.CloudCosts, mcpCC)
  895. // Update summary totals
  896. totalNetCost += item.NetCost.Cost
  897. totalAmortizedCost += item.AmortizedNetCost.Cost
  898. totalInvoicedCost += item.InvoicedCost.Cost
  899. // Update breakdowns
  900. providerBreakdown[item.Properties.Provider] += item.NetCost.Cost
  901. serviceBreakdown[item.Properties.Service] += item.NetCost.Cost
  902. regionBreakdown[item.Properties.RegionID] += item.NetCost.Cost
  903. }
  904. mcpCloudCosts[setName] = mcpSet
  905. }
  906. // Calculate cost-weighted average Kubernetes percentage (by NetCost)
  907. var avgKubernetesPercent float64
  908. var numerator, denominator float64
  909. for _, ccSet := range ccsr.CloudCostSets {
  910. for _, item := range ccSet.CloudCosts {
  911. if item == nil {
  912. continue
  913. }
  914. cost := item.NetCost.Cost
  915. percent := item.NetCost.KubernetesPercent
  916. if cost <= 0 {
  917. continue
  918. }
  919. numerator += cost * percent
  920. denominator += cost
  921. }
  922. }
  923. if denominator > 0 {
  924. avgKubernetesPercent = numerator / denominator
  925. }
  926. summary := &CloudCostSummary{
  927. TotalNetCost: totalNetCost,
  928. TotalAmortizedCost: totalAmortizedCost,
  929. TotalInvoicedCost: totalInvoicedCost,
  930. KubernetesPercent: avgKubernetesPercent,
  931. ProviderBreakdown: providerBreakdown,
  932. ServiceBreakdown: serviceBreakdown,
  933. RegionBreakdown: regionBreakdown,
  934. }
  935. return &CloudCostResponse{
  936. CloudCosts: mcpCloudCosts,
  937. Summary: summary,
  938. }
  939. }
  940. // QueryEfficiency queries allocation data and computes efficiency metrics with recommendations.
  941. func (s *MCPServer) QueryEfficiency(query *OpenCostQueryRequest) (*EfficiencyResponse, error) {
  942. // 1. Parse Window
  943. window, err := opencost.ParseWindowWithOffset(query.Window, 0)
  944. if err != nil {
  945. return nil, fmt.Errorf("failed to parse window '%s': %w", query.Window, err)
  946. }
  947. // 2. Set default parameters
  948. var aggregateBy []string
  949. var filterString string
  950. var bufferMultiplier float64 = efficiencyBufferMultiplier // Default to 1.2 (20% headroom)
  951. // 3. Parse efficiency parameters if provided
  952. if query.EfficiencyParams != nil {
  953. // Parse aggregation properties (default to pod if not specified)
  954. if query.EfficiencyParams.Aggregate != "" {
  955. aggregateBy = strings.Split(query.EfficiencyParams.Aggregate, ",")
  956. } else {
  957. aggregateBy = []string{"pod"}
  958. }
  959. // Set filter string
  960. filterString = query.EfficiencyParams.Filter
  961. // Validate filter string if provided
  962. if filterString != "" {
  963. parser := allocation.NewAllocationFilterParser()
  964. _, err := parser.Parse(filterString)
  965. if err != nil {
  966. return nil, fmt.Errorf("invalid allocation filter '%s': %w", filterString, err)
  967. }
  968. }
  969. // Set buffer multiplier if provided, otherwise use default
  970. if query.EfficiencyParams.EfficiencyBufferMultiplier != nil {
  971. bufferMultiplier = *query.EfficiencyParams.EfficiencyBufferMultiplier
  972. }
  973. } else {
  974. // Default to pod-level aggregation
  975. aggregateBy = []string{"pod"}
  976. filterString = ""
  977. }
  978. // 4. Query allocations with the specified parameters
  979. // Use the entire window as step to get aggregated data
  980. step := window.Duration()
  981. asr, err := s.costModel.QueryAllocation(
  982. window,
  983. step,
  984. aggregateBy,
  985. false, // includeIdle
  986. false, // idleByNode
  987. false, // includeProportionalAssetResourceCosts
  988. false, // includeAggregatedMetadata
  989. false, // sharedLoadBalancer
  990. opencost.AccumulateOptionNone,
  991. false, // shareIdle
  992. filterString,
  993. )
  994. if err != nil {
  995. return nil, fmt.Errorf("failed to query allocations: %w", err)
  996. }
  997. // 5. Handle empty results
  998. if asr == nil || len(asr.Allocations) == 0 {
  999. return &EfficiencyResponse{
  1000. Efficiencies: []*EfficiencyMetric{},
  1001. }, nil
  1002. }
  1003. // 6. Compute efficiency metrics from allocations using concurrent processing
  1004. var (
  1005. mu sync.Mutex
  1006. wg sync.WaitGroup
  1007. efficiencies = make([]*EfficiencyMetric, 0)
  1008. )
  1009. // Process each allocation set (typically one per time window) concurrently
  1010. for _, allocSet := range asr.Allocations {
  1011. if allocSet == nil {
  1012. continue
  1013. }
  1014. // Process this allocation set in a goroutine
  1015. wg.Add(1)
  1016. go func(allocSet *opencost.AllocationSet) {
  1017. defer wg.Done()
  1018. // Compute metrics for all allocations in this set
  1019. localMetrics := make([]*EfficiencyMetric, 0, len(allocSet.Allocations))
  1020. for _, alloc := range allocSet.Allocations {
  1021. if metric := computeEfficiencyMetric(alloc, bufferMultiplier); metric != nil {
  1022. localMetrics = append(localMetrics, metric)
  1023. }
  1024. }
  1025. // Append results to shared slice (thread-safe)
  1026. if len(localMetrics) > 0 {
  1027. mu.Lock()
  1028. efficiencies = append(efficiencies, localMetrics...)
  1029. mu.Unlock()
  1030. }
  1031. }(allocSet)
  1032. }
  1033. // Wait for all goroutines to complete
  1034. wg.Wait()
  1035. return &EfficiencyResponse{
  1036. Efficiencies: efficiencies,
  1037. }, nil
  1038. }
  1039. // safeDiv performs division and returns 0 if denominator is 0.
  1040. func safeDiv(numerator, denominator float64) float64 {
  1041. if denominator == 0 {
  1042. return 0
  1043. }
  1044. return numerator / denominator
  1045. }
  1046. // computeEfficiencyMetric calculates efficiency metrics for a single allocation.
  1047. func computeEfficiencyMetric(alloc *opencost.Allocation, bufferMultiplier float64) *EfficiencyMetric {
  1048. if alloc == nil {
  1049. return nil
  1050. }
  1051. // Calculate time duration in hours
  1052. hours := alloc.Minutes() / 60.0
  1053. if hours <= 0 {
  1054. return nil
  1055. }
  1056. // Get current usage (average over the period)
  1057. cpuCoresUsed := alloc.CPUCoreHours / hours
  1058. ramBytesUsed := alloc.RAMByteHours / hours
  1059. // Get requested amounts
  1060. cpuCoresRequested := alloc.CPUCoreRequestAverage
  1061. ramBytesRequested := alloc.RAMBytesRequestAverage
  1062. // Calculate current efficiency (will be 0 if no requests are set)
  1063. cpuEfficiency := safeDiv(cpuCoresUsed, cpuCoresRequested)
  1064. memoryEfficiency := safeDiv(ramBytesUsed, ramBytesRequested)
  1065. // Calculate recommendations with buffer for headroom
  1066. recommendedCPU := cpuCoresUsed * bufferMultiplier
  1067. recommendedRAM := ramBytesUsed * bufferMultiplier
  1068. // Ensure recommendations meet minimum thresholds
  1069. if recommendedCPU < efficiencyMinCPU {
  1070. recommendedCPU = efficiencyMinCPU
  1071. }
  1072. if recommendedRAM < efficiencyMinRAM {
  1073. recommendedRAM = efficiencyMinRAM
  1074. }
  1075. // Calculate resulting efficiency after applying recommendations
  1076. resultingCPUEff := safeDiv(cpuCoresUsed, recommendedCPU)
  1077. resultingMemEff := safeDiv(ramBytesUsed, recommendedRAM)
  1078. // Calculate cost per unit based on REQUESTED amounts (not used amounts)
  1079. // This gives us the cost per core-hour or byte-hour that the cluster charges
  1080. cpuCostPerCoreHour := safeDiv(alloc.CPUCost, cpuCoresRequested*hours)
  1081. ramCostPerByteHour := safeDiv(alloc.RAMCost, ramBytesRequested*hours)
  1082. // Current total cost
  1083. currentTotalCost := alloc.TotalCost()
  1084. // Estimate recommended cost based on recommended requests
  1085. recommendedCPUCost := recommendedCPU * hours * cpuCostPerCoreHour
  1086. recommendedRAMCost := recommendedRAM * hours * ramCostPerByteHour
  1087. // Keep other costs the same (PV, network, shared, external, GPU)
  1088. otherCosts := alloc.PVCost() + alloc.NetworkCost + alloc.SharedCost + alloc.ExternalCost + alloc.GPUCost
  1089. recommendedTotalCost := recommendedCPUCost + recommendedRAMCost + otherCosts
  1090. // Clamp recommended cost to avoid rounding issues making it higher than current
  1091. if recommendedTotalCost > currentTotalCost && (recommendedTotalCost-currentTotalCost) < 0.0001 {
  1092. recommendedTotalCost = currentTotalCost
  1093. }
  1094. // Calculate savings
  1095. costSavings := currentTotalCost - recommendedTotalCost
  1096. costSavingsPercent := safeDiv(costSavings, currentTotalCost) * 100
  1097. return &EfficiencyMetric{
  1098. Name: alloc.Name,
  1099. CPUEfficiency: cpuEfficiency,
  1100. MemoryEfficiency: memoryEfficiency,
  1101. CPUCoresRequested: cpuCoresRequested,
  1102. CPUCoresUsed: cpuCoresUsed,
  1103. RAMBytesRequested: ramBytesRequested,
  1104. RAMBytesUsed: ramBytesUsed,
  1105. RecommendedCPURequest: recommendedCPU,
  1106. RecommendedRAMRequest: recommendedRAM,
  1107. ResultingCPUEfficiency: resultingCPUEff,
  1108. ResultingMemoryEfficiency: resultingMemEff,
  1109. CurrentTotalCost: currentTotalCost,
  1110. RecommendedCost: recommendedTotalCost,
  1111. CostSavings: costSavings,
  1112. CostSavingsPercent: costSavingsPercent,
  1113. EfficiencyBufferMultiplier: bufferMultiplier,
  1114. Start: alloc.Start,
  1115. End: alloc.End,
  1116. }
  1117. }
  1118. // QueryRecommendations generates cost optimization recommendations based on allocation data.
  1119. func (s *MCPServer) QueryRecommendations(query *OpenCostQueryRequest) (*RecommendationsResponse, error) {
  1120. // 0. Validate server dependencies
  1121. if s.costModel == nil {
  1122. return nil, fmt.Errorf("cost model not initialized")
  1123. }
  1124. // 1. Parse Window
  1125. window, err := opencost.ParseWindowWithOffset(query.Window, 0)
  1126. if err != nil {
  1127. return nil, fmt.Errorf("failed to parse window: %w", err)
  1128. }
  1129. // 2. Set default parameters
  1130. var aggregateBy []string
  1131. var filterString string
  1132. var bufferMultiplier float64 = efficiencyBufferMultiplier
  1133. var minSavings float64 = minSavingsThreshold
  1134. includeIdle := true
  1135. includeOversized := true
  1136. includeRightsize := true
  1137. var topNValue int
  1138. // 3. Parse recommendations parameters if provided
  1139. if query.RecommendationsParams != nil {
  1140. if query.RecommendationsParams.Aggregate != "" {
  1141. aggregateBy = strings.Split(query.RecommendationsParams.Aggregate, ",")
  1142. } else {
  1143. aggregateBy = []string{"pod"}
  1144. }
  1145. filterString = query.RecommendationsParams.Filter
  1146. if filterString != "" {
  1147. parser := allocation.NewAllocationFilterParser()
  1148. _, err := parser.Parse(filterString)
  1149. if err != nil {
  1150. return nil, fmt.Errorf("invalid allocation filter: %w", err)
  1151. }
  1152. }
  1153. // Validate and apply buffer multiplier
  1154. if query.RecommendationsParams.BufferMultiplier != nil {
  1155. bufferMultiplier = *query.RecommendationsParams.BufferMultiplier
  1156. if bufferMultiplier < minBufferMultiplier {
  1157. bufferMultiplier = minBufferMultiplier
  1158. } else if bufferMultiplier > maxBufferMultiplier {
  1159. bufferMultiplier = maxBufferMultiplier
  1160. }
  1161. }
  1162. // Validate and apply minimum savings threshold
  1163. if query.RecommendationsParams.MinSavings != nil {
  1164. minSavings = *query.RecommendationsParams.MinSavings
  1165. if minSavings < 0 {
  1166. minSavings = 0
  1167. }
  1168. }
  1169. // Handle include flags: if none are explicitly set, default all to true
  1170. noneSet := !query.RecommendationsParams.IncludeIdle &&
  1171. !query.RecommendationsParams.IncludeOversized &&
  1172. !query.RecommendationsParams.IncludeRightsize
  1173. if noneSet {
  1174. includeIdle = true
  1175. includeOversized = true
  1176. includeRightsize = true
  1177. } else {
  1178. includeIdle = query.RecommendationsParams.IncludeIdle
  1179. includeOversized = query.RecommendationsParams.IncludeOversized
  1180. includeRightsize = query.RecommendationsParams.IncludeRightsize
  1181. }
  1182. // Validate and apply topN
  1183. if query.RecommendationsParams.TopN != nil {
  1184. topNValue = *query.RecommendationsParams.TopN
  1185. if topNValue < 0 {
  1186. topNValue = 0
  1187. } else if topNValue > maxTopN {
  1188. topNValue = maxTopN
  1189. }
  1190. }
  1191. } else {
  1192. aggregateBy = []string{"pod"}
  1193. }
  1194. // 4. Query allocations
  1195. step := window.Duration()
  1196. asr, err := s.costModel.QueryAllocation(
  1197. window,
  1198. step,
  1199. aggregateBy,
  1200. false, // includeIdle
  1201. false, // idleByNode
  1202. false, // includeProportionalAssetResourceCosts
  1203. false, // includeAggregatedMetadata
  1204. false, // sharedLoadBalancer
  1205. opencost.AccumulateOptionNone,
  1206. false, // shareIdle
  1207. filterString,
  1208. )
  1209. if err != nil {
  1210. return nil, fmt.Errorf("failed to query allocations: %w", err)
  1211. }
  1212. // 5. Handle empty results
  1213. if asr == nil || len(asr.Allocations) == 0 {
  1214. return &RecommendationsResponse{
  1215. Recommendations: []*Recommendation{},
  1216. Summary: createEmptyRecommendationsSummary(),
  1217. Window: &TimeWindow{
  1218. Start: *window.Start(),
  1219. End: *window.End(),
  1220. },
  1221. }, nil
  1222. }
  1223. // 6. Generate recommendations from allocations
  1224. var recommendations []*Recommendation
  1225. for _, allocSet := range asr.Allocations {
  1226. if allocSet == nil {
  1227. continue
  1228. }
  1229. for _, alloc := range allocSet.Allocations {
  1230. recs := generateRecommendationsFromAllocation(alloc, bufferMultiplier, minSavings, includeIdle, includeOversized, includeRightsize)
  1231. recommendations = append(recommendations, recs...)
  1232. }
  1233. }
  1234. // 7. Sort recommendations by estimated savings (highest first)
  1235. sortRecommendationsBySavings(recommendations)
  1236. // 8. Apply topN limit if specified
  1237. if topNValue > 0 && len(recommendations) > topNValue {
  1238. recommendations = recommendations[:topNValue]
  1239. }
  1240. // 9. Build summary
  1241. summary := buildRecommendationsSummary(recommendations)
  1242. return &RecommendationsResponse{
  1243. Recommendations: recommendations,
  1244. Summary: summary,
  1245. Window: &TimeWindow{
  1246. Start: *window.Start(),
  1247. End: *window.End(),
  1248. },
  1249. }, nil
  1250. }
  1251. // generateRecommendationsFromAllocation creates recommendations for a single allocation.
  1252. func generateRecommendationsFromAllocation(alloc *opencost.Allocation, bufferMultiplier, minSavings float64, includeIdle, includeOversized, includeRightsize bool) []*Recommendation {
  1253. if alloc == nil {
  1254. return nil
  1255. }
  1256. hours := alloc.Minutes() / 60.0
  1257. if hours <= 0 {
  1258. return nil
  1259. }
  1260. var recommendations []*Recommendation
  1261. // Calculate usage metrics
  1262. cpuCoresUsed := alloc.CPUCoreHours / hours
  1263. ramBytesUsed := alloc.RAMByteHours / hours
  1264. cpuCoresRequested := alloc.CPUCoreRequestAverage
  1265. ramBytesRequested := alloc.RAMBytesRequestAverage
  1266. // Calculate efficiency
  1267. cpuEfficiency := safeDiv(cpuCoresUsed, cpuCoresRequested)
  1268. memoryEfficiency := safeDiv(ramBytesUsed, ramBytesRequested)
  1269. // Calculate recommended values
  1270. recommendedCPU := cpuCoresUsed * bufferMultiplier
  1271. recommendedRAM := ramBytesUsed * bufferMultiplier
  1272. if recommendedCPU < efficiencyMinCPU {
  1273. recommendedCPU = efficiencyMinCPU
  1274. }
  1275. if recommendedRAM < efficiencyMinRAM {
  1276. recommendedRAM = efficiencyMinRAM
  1277. }
  1278. // Calculate costs
  1279. cpuCostPerCoreHour := safeDiv(alloc.CPUCost, cpuCoresRequested*hours)
  1280. ramCostPerByteHour := safeDiv(alloc.RAMCost, ramBytesRequested*hours)
  1281. currentTotalCost := alloc.TotalCost()
  1282. recommendedCPUCost := recommendedCPU * hours * cpuCostPerCoreHour
  1283. recommendedRAMCost := recommendedRAM * hours * ramCostPerByteHour
  1284. otherCosts := alloc.PVCost() + alloc.NetworkCost + alloc.SharedCost + alloc.ExternalCost + alloc.GPUCost
  1285. recommendedTotalCost := recommendedCPUCost + recommendedRAMCost + otherCosts
  1286. if recommendedTotalCost > currentTotalCost && (recommendedTotalCost-currentTotalCost) < 0.0001 {
  1287. recommendedTotalCost = currentTotalCost
  1288. }
  1289. savings := currentTotalCost - recommendedTotalCost
  1290. savingsPercent := safeDiv(savings, currentTotalCost) * 100
  1291. // Skip if savings are below threshold
  1292. if savings < minSavings {
  1293. return nil
  1294. }
  1295. // Check for idle resources
  1296. if includeIdle && cpuEfficiency < idleCPUThreshold && memoryEfficiency < idleMemoryThreshold && cpuCoresRequested > 0 && ramBytesRequested > 0 {
  1297. rec := &Recommendation{
  1298. ID: generateRecommendationID(),
  1299. Type: RecommendationTypeIdle,
  1300. Priority: RecommendationPriorityHigh,
  1301. ResourceName: alloc.Name,
  1302. Description: fmt.Sprintf("Resource '%s' appears to be idle with <%.0f%% CPU and <%.0f%% memory utilization", alloc.Name, idleCPUThreshold*100, idleMemoryThreshold*100),
  1303. Action: "Consider removing or scaling down this resource. Verify it's not needed before deletion.",
  1304. CurrentCPURequest: cpuCoresRequested,
  1305. CurrentRAMRequest: ramBytesRequested,
  1306. CurrentCPUUsage: cpuCoresUsed,
  1307. CurrentRAMUsage: ramBytesUsed,
  1308. CurrentCost: currentTotalCost,
  1309. CPUEfficiency: cpuEfficiency,
  1310. MemoryEfficiency: memoryEfficiency,
  1311. RecommendedCPURequest: recommendedCPU,
  1312. RecommendedRAMRequest: recommendedRAM,
  1313. RecommendedCost: recommendedTotalCost,
  1314. EstimatedSavings: savings,
  1315. EstimatedSavingsPercent: savingsPercent,
  1316. Start: alloc.Start,
  1317. End: alloc.End,
  1318. }
  1319. recommendations = append(recommendations, rec)
  1320. return recommendations // Return early, idle is the most critical
  1321. }
  1322. // Check for oversized resources
  1323. if includeOversized && (cpuEfficiency < oversizedCPUThreshold || memoryEfficiency < oversizedMemoryThreshold) && cpuCoresRequested > 0 && ramBytesRequested > 0 {
  1324. priority := RecommendationPriorityMedium
  1325. if cpuEfficiency < severelyOversizedThreshold || memoryEfficiency < severelyOversizedThreshold {
  1326. priority = RecommendationPriorityHigh
  1327. }
  1328. rec := &Recommendation{
  1329. ID: generateRecommendationID(),
  1330. Type: RecommendationTypeOversized,
  1331. Priority: priority,
  1332. ResourceName: alloc.Name,
  1333. Description: fmt.Sprintf("Resource '%s' is significantly oversized with %.1f%% CPU and %.1f%% memory efficiency", alloc.Name, cpuEfficiency*100, memoryEfficiency*100),
  1334. Action: fmt.Sprintf("Reduce CPU request from %.3f to %.3f cores and RAM request from %.0f to %.0f bytes", cpuCoresRequested, recommendedCPU, ramBytesRequested, recommendedRAM),
  1335. CurrentCPURequest: cpuCoresRequested,
  1336. CurrentRAMRequest: ramBytesRequested,
  1337. CurrentCPUUsage: cpuCoresUsed,
  1338. CurrentRAMUsage: ramBytesUsed,
  1339. CurrentCost: currentTotalCost,
  1340. CPUEfficiency: cpuEfficiency,
  1341. MemoryEfficiency: memoryEfficiency,
  1342. RecommendedCPURequest: recommendedCPU,
  1343. RecommendedRAMRequest: recommendedRAM,
  1344. RecommendedCost: recommendedTotalCost,
  1345. EstimatedSavings: savings,
  1346. EstimatedSavingsPercent: savingsPercent,
  1347. Start: alloc.Start,
  1348. End: alloc.End,
  1349. }
  1350. recommendations = append(recommendations, rec)
  1351. return recommendations
  1352. }
  1353. // General rightsizing recommendation
  1354. if includeRightsize && savings >= minSavings {
  1355. priority := RecommendationPriorityLow
  1356. if savingsPercent >= 30 {
  1357. priority = RecommendationPriorityMedium
  1358. }
  1359. if savingsPercent >= 50 {
  1360. priority = RecommendationPriorityHigh
  1361. }
  1362. rec := &Recommendation{
  1363. ID: generateRecommendationID(),
  1364. Type: RecommendationTypeRightsize,
  1365. Priority: priority,
  1366. ResourceName: alloc.Name,
  1367. Description: fmt.Sprintf("Resource '%s' can be rightsized for %.1f%% cost savings", alloc.Name, savingsPercent),
  1368. Action: fmt.Sprintf("Adjust CPU request to %.3f cores (from %.3f) and RAM request to %.0f bytes (from %.0f)", recommendedCPU, cpuCoresRequested, recommendedRAM, ramBytesRequested),
  1369. CurrentCPURequest: cpuCoresRequested,
  1370. CurrentRAMRequest: ramBytesRequested,
  1371. CurrentCPUUsage: cpuCoresUsed,
  1372. CurrentRAMUsage: ramBytesUsed,
  1373. CurrentCost: currentTotalCost,
  1374. CPUEfficiency: cpuEfficiency,
  1375. MemoryEfficiency: memoryEfficiency,
  1376. RecommendedCPURequest: recommendedCPU,
  1377. RecommendedRAMRequest: recommendedRAM,
  1378. RecommendedCost: recommendedTotalCost,
  1379. EstimatedSavings: savings,
  1380. EstimatedSavingsPercent: savingsPercent,
  1381. Start: alloc.Start,
  1382. End: alloc.End,
  1383. }
  1384. recommendations = append(recommendations, rec)
  1385. }
  1386. return recommendations
  1387. }
  1388. // sortRecommendationsBySavings sorts recommendations by estimated savings in descending order.
  1389. func sortRecommendationsBySavings(recs []*Recommendation) {
  1390. sort.Slice(recs, func(i, j int) bool {
  1391. return recs[i].EstimatedSavings > recs[j].EstimatedSavings
  1392. })
  1393. }
  1394. // generateRecommendationID creates a unique ID for a recommendation.
  1395. func generateRecommendationID() string {
  1396. bytes := make([]byte, 8)
  1397. if _, err := rand.Read(bytes); err != nil {
  1398. return fmt.Sprintf("rec-%d", time.Now().UnixNano())
  1399. }
  1400. return fmt.Sprintf("rec-%s", hex.EncodeToString(bytes))
  1401. }
  1402. // createEmptyRecommendationsSummary creates an empty summary for when there are no recommendations.
  1403. func createEmptyRecommendationsSummary() *RecommendationsSummary {
  1404. return &RecommendationsSummary{
  1405. TotalRecommendations: 0,
  1406. TotalPotentialSavings: 0,
  1407. ByType: make(map[string]int),
  1408. ByPriority: make(map[string]int),
  1409. IdleResourceCount: 0,
  1410. OversizedCount: 0,
  1411. RightsizeCount: 0,
  1412. }
  1413. }
  1414. // buildRecommendationsSummary creates a summary from a list of recommendations.
  1415. func buildRecommendationsSummary(recommendations []*Recommendation) *RecommendationsSummary {
  1416. summary := &RecommendationsSummary{
  1417. TotalRecommendations: len(recommendations),
  1418. ByType: make(map[string]int),
  1419. ByPriority: make(map[string]int),
  1420. }
  1421. for _, rec := range recommendations {
  1422. summary.TotalPotentialSavings += rec.EstimatedSavings
  1423. summary.ByType[string(rec.Type)]++
  1424. summary.ByPriority[string(rec.Priority)]++
  1425. switch rec.Type {
  1426. case RecommendationTypeIdle:
  1427. summary.IdleResourceCount++
  1428. case RecommendationTypeOversized:
  1429. summary.OversizedCount++
  1430. case RecommendationTypeRightsize:
  1431. summary.RightsizeCount++
  1432. }
  1433. }
  1434. return summary
  1435. }